0

问题

当我尝试通过 gunicorn 执行 django 管理命令时收到 502 bad gateway

逻辑线

我认为问题出在权限上,像gunicorn这样的东西不能调用命令。我这么说是因为我可以在不使用 gunicorn 的本地运行它。

我可以用这两种方法运行它:

  • python manage.py runserver之后,使用 Postman 启动它就可以了。

  • 第二个是通过终端呼叫python manage.py command_name,这也可以。

  • 在生产中,我也可以使用python manage.py command_name. 但不是邮递员,因为它返回 502(主要问题)

PS。如果我删除call_command它返回 200 ok,那么,核心问题似乎是这个命令的执行。

编码

class TestCommandView(views.APIView):
    def post(self, request):
        id = request.data['id']

        try:
            call_command('command_name', target_id=id)
            return Response({"status": "success"})
        except Exception as error:
            return Response({"status": "error: " + str(error) })

返回样品

<html>
    <head>
        <title>502 Bad Gateway</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>502 Bad Gateway</h1>
        </center>
        <hr>
        <center>nginx/1.14.0 (Ubuntu)</center>
    </body>
</html>

独角兽会议

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
RuntimeDirectory=gunicorn
WorkingDirectory=/var/www/project
ExecStart=/var/www/project/venv/bin/ddtrace-run /var/www/project/venv/bin/guni$
Environment="DJANGO_SETTINGS_MODULE=project.settings.prod"

[Install]
WantedBy=multi-user.target

Nginx 日志错误

2019/03/13 13:43:38 [error] 27552#27552: *3128 upstream prematurely closed connection while reading response header from upstream, client: IP, server: api.project.com, request: "POST /api/project/endpoint/ HTTP/1.1", upstream: "http://unix:/tmp/project.sock:/api/project/endpoint/", host: "api.project.com"

我试过的

  • sudo chown -R www-data:www-data /var/www/project
  • sudo chown -R ubuntu:ubuntu /var/www/project
  • 根据这个问题解决方案更改我在 gunicorn 配置上的 Environment 值Django call_command permissions nginx+gunicorn+supervisord。添加PYTHONPATH,但是这个人在主管配置上使用它,这个项目不使用主管,所以我试图把它放在gunicorn文件中,这只是一个尝试。
4

1 回答 1

0

我意识到这是超时的问题

gunicorn的默认超时时间是 30 秒,基于其文档。

博士。 沉默超过这么多秒的工人被杀死并重新启动。

我的请求超过了 30 秒,所以,gunicorn杀死了进程并且nginx返回了 502。

解决方案

  • 更改gunicorn默认超时
  • 更改 nginx 超时

独角兽

我在gunicorn ExecStart行中添加了超时选项

--超时 300

    ExecStart=/var/www/project/venv/bin/ddtrace-run /var/www/project/venv/bin/gunicorn --bind unix:/tmp/project.sock project.wsgi:application --access-logfile /home/ubuntu/gunicorn.log --error-logfile /home/ubuntu/gunicorn.error.log --timeout 720 --workers 3

Nginx

将此选项添加到 nginx conf 的 HTTP 部分

proxy_read_timeout 300s;

重新启动nginxgunicorn,这就像一个魅力

于 2019-03-14T14:31:28.600 回答