一个Django应用运行在AWS实例上,通过gunicorn和nginx配置,运行了一年多,但是突然,我收到502 bad gateway的错误,然后我在nginx错误日志中看到了下面提到的消息,
2017/05/17 16:18:35 [error] 1040#0: *7460 connect() to unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock failed (111: Connection refused) while connecting to upstream, client: xx.xxxx.xx.xxx, server: xx.xx.xx.xxx, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock:/", host: "xx.xx.xx.xxx", referrer: "http://xx.xx.xx.xxx"
我的 nginx 配置:
server {
client_max_body_size 200M;
listen 80;
listen [::]:80 ipv6only=on;
server_name xx.xx.xx.xxx;
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/myserver.crt;
ssl_certificate_key /etc/nginx/ssl/myserver.key;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ubuntu/webapps/myproject/myproject;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock;
proxy_set_header X-Forwarded-Protocol $scheme;
}
if ($scheme = http){
return 301 https://xx.xx.xx.xxx$request_uri;
}
if ($http_host = pas-cash.com){
return 303 https://xx.xx.xx.xxx$request_uri;
}
}
我的 gunicorn.conf
description "Gunicorn application server handling myproject"
start on runlevel [6789]
stop on runlevel [!6789]
respawn
setuid ubuntu
setgid www-data
chdir /home/ubuntu/webapps/myproject/myproject
exec /home/ubuntu/webapps/myproject/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock myproject.wsgi:application
之后我通过以下命令重新启动了nginx
sudo service nginx restart
重新启动后,应用程序运行良好,我找不到这个错误背后的具体原因,我为此搜索了它,但我得到了不同类型的答案,但没有适合我的答案,请你们帮帮我因为,为什么会发生这种情况,我的配置中是否缺少任何东西,或者这种行为背后的常见/一般原因是什么。这对我很有帮助,提前致谢。
最佳答案
这是“突然”引起的,不是因为 nginx 错误,而是因为 gunicorn 或您的应用程序的错误(代码错误、未安装软件包等)。不过,记录和修复应该相对容易。
首先尝试从服务器运行您的应用程序 python manage.py runserver
看看你有没有问题。 ... migrate
也一样.生产不工作但本地工作的问题通常是因为缺少包或缺少迁移。在本地创建一个 requirements.txt 文件并将其安装在生产环境中。
如果错误仍然存在,请使用 gunicorn --log-file=- YourApp.wsgi:application
检查 gunicorn 日志.纠正所有这些错误后,运行
sudo systemctl status gunicorn.socket
sudo systemctl status gunicorn
并且您希望同时事件和运行。如果您开始收到 400 错误,这是一个好兆头,因为它现在是 Django 错误(通常是允许的主机)。打开 debug=True 以查看 django 的确切错误。记住每当对代码运行进行任何更改时
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
仅供引用,如果以上都不起作用,那么您可以随时使用以下命令检查您的 nginx 日志sudo tail -30 /var/log/nginx/error.log
关于Django gunicorn nginx (111 : Connection refused) while connecting to upstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046611/