nginx - Python Django call_command 权限 gunicorn+nginx
问题描述
问题
当我尝试通过 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文件中,这只是一个尝试。
解决方案
我意识到这是超时的问题
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;
重新启动nginx和gunicorn,这就像一个魅力
推荐阅读
- node.js - 同步流输出
- .net - AutoFixture:为生成的所有随机日期指定边界(或设置为“现在”)
- c++ - 成对的可变参数模板(命名元组)
- typescript - 汇总是否支持汇总配置文件中的打字稿?
- javascript - 如何在我的 jquery 函数中使用动态变量名称
- batch-file - 将字符串值设置为变量
- templates - 错误!提供的额外变量数据无效。'@./vars.yaml' 无法制成字典
- css - CSS动画:悬停时应用svg旋转和变换:悬停时旋转角度重置
- git - jenkins 工作分支说明符中的 master 和 refs/heads/master 有什么区别
- c++ - C ++:在cout语句后返回意外数字的bool方法