502 Bad Gateway django + gunicorn + nginx配置

时间:2016-01-14 20:38:13

标签: django nginx gunicorn

当我尝试访问我的网站时,我收到了502 Bad Gateway。所以我查看了我的日志,我可以看到,当我运行我的gunicorn脚本时,我收到以下错误消息:

2016/01/14 19:52:22 [error] 25232#0: *1 connect() to unix:/home/dvotedfan/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 130.211.0.242, server: dvotedfan.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/dvotedfan/run/gunicorn.sock:/", host: "10.240.0.2"

我的nginx配置文件:

    upstream dvotedfan_app_server {
  server unix:/home/dvotedfan/run/gunicorn.sock fail_timeout=0;
}
server {
    listen 80;
    server_name www.dvotedfan.com dvotedfan.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/dvotedfan/static;
    }
    location /media/ {
        root /home/dvotedfan/media;
    }
    location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    if (!-f $request_filename) {
            proxy_pass http://dvotedfan_app_server;
            break;
        }
       }
}

我的gunicorn脚本看起来像这样:

    #!/bin/bash
NAME="dvotedfan"
DJANGODIR=/home/dvotedfan/src
SOCKFILE=/home/dvotedfan/run/gunicorn.sock
USER=dvotedfan

NUM_WORKERS=3

MAX_REQUESTS=1
DJANGO_SETTINGS_MODULE=dvotedfan.settings.production
DJANGO_WSGI_MODULE=dvotedfan.wsgi # WSGI module name

echo "Starting $NAME"

cd $DJANGODIR
source /home/dvotedfan/.virtualenvs/dvotedfan/bin/activate

export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

exec /home/dvotedfan/.virtualenvs/dvotedfan/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--user=$USER \
--workers $NUM_WORKERS \
--max-requests $MAX_REQUESTS \
--bind=unix:/home/dvotedfan/run/gunicorn.sock \
--log-level=error \
--log-file=-

如果我运行ps -ef | grep gunicorn

dvotedf+ 26820 24452  0 21:11 pts/0    00:00:00 nano /home/dvotedfan/scripts/gunicorn.sh
dvotedf+ 26821 24452  0 21:11 pts/0    00:00:00 nano /home/dvotedfan/scripts/gunicorn.sh
dvotedf+ 27003 24452  0 21:16 pts/0    00:00:00 /home/dvotedfan/.virtualenvs/dvotedfan/bin/python /home/dvotedfan/.
virtualenvs/dvotedfan/bin/gunicorn --bind 0.0.0.0:8000 dvotedfan.wsgi:application
dvotedf+ 27008 27003  0 21:16 pts/0    00:00:00 /home/dvotedfan/.virtualenvs/dvotedfan/bin/python /home/dvotedfan/.
virtualenvs/dvotedfan/bin/gunicorn --bind 0.0.0.0:8000 dvotedfan.wsgi:application
dvotedf+ 27199 27123  0 21:20 pts/2    00:00:00 grep --color=auto gunicorn

我的想法让我无处不在,无法找到解决方案。

1 个答案:

答案 0 :(得分:1)

您的gunicorn正在侦听端口8000,因此您需要连接到该端口。 你的nginx conf看起来像这样

http {
  upstream django {
      server 127.0.0.1:8000;
  }

  server {
      listen 80;
      ...
      location / {
        uwsgi_pass django;
        include uwsgi_params;
      }
   }
}