Can't restart nginx - django

I'm using nginx with Django on Ubunto 10:04. The problem is when I restart nginx I get this error.
sudo /etc/init.d/nginx restart
Restarting nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
configuration file /etc/nginx/nginx.conf test is successful
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
Also, I have tried stop and then start but still get the error.
Here's the output from lsof:
sudo lsof -i tcp:80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 27141 root 6u IPv4 245906 0t0 TCP *:www (LISTEN)
nginx 27142 nobody 6u IPv4 245906 0t0 TCP *:www (LISTEN)
If I kill the process with PID 27141 it works. However, I would like to get to the bottom
of why I can't just do a restart.
Here's the nginx.conf:
worker_processes 1;
user nobody nogroup;
pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;
events {
worker_connections 1024;
accept_mutex off;
}
http {
include mime.types;
default_type application/octet-stream;
access_log /tmp/nginx.access.log combined;
sendfile on;
upstream app_server {
# server unix:/tmp/gunicorn.sock fail_timeout=0;
# For a TCP configuration:
server 127.0.0.1:8000 fail_timeout=0;
}
server {
listen 80 default;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# path for static files
root /home/apps/venvs/app1/app1;
location / {
# checks for static file, if not found proxy to app
try_files $uri #proxy_to_app;
}
location #proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /path/to/app/current/public;
}
}
}
Any ideas?

Try:
$ sudo fuser -k 80/tcp ; sudo /etc/init.d/nginx restart

This worked for me
sudo fuser -k 80/tcp
And then
service nginx start
Source: https://rtcamp.com/tutorials/nginx/troubleshooting/emerg-bind-failed-98-address-already-in-use/

Daemontools starting nginx successfully, then nginx daemonizes, and then daemontools tries to start nginx again, unsuccessfully, logging an error to the log.
The solution to this problem is to disable daemon mode in the main section of the nginx.conf:
daemon off;
Site: http://wiki.nginx.org/CoreModule

Tired with nginx restart issues and "address in use" faults. Decided to make it work once and for all.
Added just one line at the end stop and restart action in /etc/init.d/nginx file
nginx -s quit
so it looks now like (and ensure that nginx folder is in PATH variable, otherwise specify the full path)
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
nginx -s quit
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon --stop --quiet --pidfile \
/var/run/$NAME.pid --exec $DAEMON || true
nginx -s quit
sleep 1
test_nginx_config
start-stop-daemon --start --quiet --pidfile \
/var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
Hope that this solution will work for others.

Always test your config first, it will show syntax errors and duplicate lines and point you there.
nginx -t
You will see logs there showing you what is causing the failure.

It's because you aren't restarting as root.
Change to root:
sudo -i
Restart:
service nginx restart
Or:
/etc/init.d/nginx restart

Related

Best way to config gunicorn and nginx with django?

I am trying to deploy django with gunicorn and nginx on heroku, and i'm kinda confused with the way to config gunicorn and nginx, when i searched through internet, they usually create gunicorn.socket
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
and gunicorn.service
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
myproject.wsgi:application
[Install]
WantedBy=multi-user.target
but when i go to gunicorn docs : https://docs.gunicorn.org/en/stable/deploy.html. nginx has a config file like this
worker_processes 1;
user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024; # increase if you have lots of clients
accept_mutex off; # set to 'on' if nginx worker_processes > 1
# 'use epoll;' to enable for Linux 2.6+
# 'use kqueue;' to enable for FreeBSD, OSX
}
http {
include mime.types;
# fallback in case we can't determine a type
default_type application/octet-stream;
access_log /var/log/nginx/access.log combined;
sendfile on;
upstream app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response
# for UNIX domain socket setups
server unix:/tmp/gunicorn.sock fail_timeout=0;
# for a TCP configuration
# server 192.168.0.7:8000 fail_timeout=0;
}
server {
# if no Host match, close the connection to prevent host spoofing
listen 80 default_server;
return 444;
}
server {
# use 'listen 80 deferred;' for Linux
# use 'listen 80 accept_filter=httpready;' for FreeBSD
listen 80;
client_max_body_size 4G;
# set the correct host(s) for your site
server_name example.com www.example.com;
keepalive_timeout 5;
# path for static files
root /path/to/app/current/public;
location / {
# checks for static file, if not found proxy to app
try_files $uri #proxy_to_app;
}
location #proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
proxy_pass http://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /path/to/app/current/public;
}
}
}
So i wonder what the different between these and which is the best way to setup gunicorn, nginx.
Thanks
you can try following steps to deploy django project using nginx, supervisor and gunicron
1- Create new gunicorn script in /myprojectenv/bin/script name e.g gunicorn_start
#!/bin/bash
NAME="myproject"
DJANGODIR=/home/sammy/myprojectdir/myproject
SOCKFILE=/home/sammy/myprojectdir/myproject/run/proj_name.sock
USER=sammy
GROUP=www-data
NUM_WORKERS=3
DJANGO_SETTINGS_MODULE=myproject.settings
DJANGO_WSGI_MODULE=myproject.wsgi
echo "Starting $NAME as whoami"
cd $DJANGODIR
source ../myprojectenv/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
exec ../myprojectenv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application
--name $NAME
--workers $NUM_WORKERS
--user=$USER --group=$GROUP
--bind=unix:$SOCKFILE
--log-level=debug
--log-file=-
2- Install supervisorctl
pip or yum install supervisor
3- Create conf file under /etc/supervisor.d
Example config file
[program:myproject]
directory=/home/sammy/myprojectdir/myproject
command=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn_start --workers 3 --bind uxix:/home/sammy/myprojectdir/myproject/run/proj_name.sock myproject.wsgi:application
autostart=true
autorestart=true
stderr_logfile=/home/sammy/myprojectdir/myproject/Logs/gunicorn_supervisor.log
stdout_logfile=/home/sammy/myprojectdir/myproject/Logs/gunicorn_supervisor.log
user=sammy
group=www-data
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
4- Supervisorctl reread & supervisorctl update
5- nano /etc/nginx/site-available/app.conf
6- ln -s /etc/nginx/sites-available/app.conf /etc/nginx/sites-enabled
7- systemctl restart nginx
Please change folder names and path according to your project.

Gunicorn, nginx, django, inside of a docker container. Gunicorn successfully runs on port 80 but nginx fails

I'm trying to set up a simple blogging site that I wrote using the django framework. The website works except that it isn't serving static files. I imagine that's because nginx isn't running. However, when I configure it to run on any port other than 80 I get the following error:
nginx: [emerg] bind() to 172.17.0.1:9000 failed (99: Cannot assign requested address)
When I run it on a port that is already being used by gunicorn I get the following error:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
My nginx configuration file is as follows:
upstream django {
server 127.0.0.1:8080;
}
server {
listen 172.17.0.1:9000;
server_name my.broken.blog;
index index.html;
location = /assets/favicon.ico { access_log off; log_not_found off; }
location /assets {
autoindex on;
alias /var/www/html/mysite/assets;
}
location / {
autoindex on;
uwsgi_pass unix:///run/uwsgi/django/socket;
include /var/www/html/mysite/mysite/uwsgi_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
But if I run nginx without starting guincorn it runs properly but I get a 403 forbidden error.
Going with the suggested answer I don't get any errors, but the site is returning 403 forbidden and doesn't present the part of the website gunicorn is supposed to deliver.
Configure Nginx and Gunicorn in following way to make it work,
Use unix socket to comminicate between nginx and gunicron rather than running gunicorn in some port
Create a unit file for gunicorn in the following location
sudo nano /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=root
Group=nginx
WorkingDirectory=/path-to-project-folder
ExecStart=/<path-to-env>/bin/gunicorn --workers 9 --bind unix:/path-to-sockfile/<blog>.sock app.wsgi:application
Restart=on-failure
[Install]
WantedBy=multi-user.target
Then start and enable gunicorn service
It will generate a sock file in the specified path.
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
Note: Choose the suitable number of workers for gunicorn, can sepecify log files as follows
ExecStart=//bin/gunicorn --workers 9 --bind unix:/path-to-sockfile/.sock app.wsgi:application --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/error.log
create a new configuration file specific to the project in /etct/nginx rather than edit the default nginx.conf
nano /etc/nginx/blog.conf
and add the following lines ( can also add the file in /etc/nginx/default.d/)
server {
listen 80;
server_name 172.17.0.1; # your Ip
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path-to-static-folder;
}
location /media/ {
root /path-to-media-folder;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/path-to-sock-file/<blog-sock-file>.sock;
}
}
include the /etc/nginx/blog.conf to nignx.conf
---------
----------
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/blog.conf; # the new conf file added
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
------
-------
run sudo nginx -t // to check for errors in nginx configuration.
run sudo systemctl nginx restart
refer: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04

I don't know why Nginx server is not working

Hi there i'm trying to put in production some django app using nginx + gunicorn + supervisor.
Following this guide i was able to reproduce all steps with success but for some reason i can't make it work. I believe that the problem is with the nginx part of the project since I'm not able to even serve a static file for testing. It's my first time using all these tools.
Config files are as follows:
nginx.conf:
worker_processes 1;
user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
error_log /home/seba94/log/nginx/nginx.error.log warn;
#pid /run/nginx.pid;
events {
worker_connections 1024; # increase if you have lots of clients
accept_mutex off; # set to 'on' if nginx worker_processes > 1
# 'use epoll;' to enable for Linux 2.6+
# 'use kqueue;' to enable for FreeBSD, OSX
}
http {
include /etc/nginx/mime.types;
# fallback in case we can't determine a type
default_type application/octet-stream;
access_log /home/seba94/log/nginx/nginx.access.log combined;
sendfile on;
upstream app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response
# for UNIX domain socket setups
server unix:/tmp/gunicorn.sock fail_timeout=10s;
# for a TCP configuration
#server 127.0.0.1:8000 fail_timeout=0;
}
server {
# if no Host match, close the connection to prevent host spoofing
listen 80 default_server;
return 444;
}
server {
# use 'listen 80 deferred;' for Linux
# use 'listen 80 accept_filter=httpready;' for FreeBSD
listen 80;
client_max_body_size 4G;
# set the correct host(s) for your site
server_name reg.rocstar.tv;
keepalive_timeout 5;
# path for static files
root /home/seba94/static;
location /register/ {
# checks for static file, if not found proxy to app
try_files $uri #proxy_to_app;
}
location /media/ {
#path for Django media files
alias /home/seba94/register-page/register_page/media;
}
location /static/ {
#path for Django static files
alias /home/seba94/register-page/register_page/static;
}
location /todd-logo.png {
alias /home/seba94/static/todd-logo.png;
}
location #proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
proxy_pass http://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /home/seba94/static;
}
}
supervisord.conf:
[supervisord]
logfile=/home/seba94/log/supervisord/supervisord.log
[inet_http_server]
port=127.0.0.1:9001
[rpcinterface:supervisor]
supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface
[program:register-page-django]
command=/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/bin/gunicorn register_page.wsgi -c /home/seba94/conf/gunicorn.conf.py
directory=/home/seba94/register-page/register_page
user=seba94
autostart=true
autorestart=true
stdout_logfile=/home/seba94/log/supervisord/register_page.log
stderr_logfile=/home/seba94/log/supervisord/register_page.err.log
[supervisorctl]
gunicorn.conf.py:
import multiprocessing
#Server socket config
bind = "unix:/tmp/gunicorn.sock"
backlog = 2048
#Workers config. Eventlet is an asynchronus worker
workers = multiprocessing.cpu_count() * 2
worker_class = "eventlet"
worker_connections = 1000
#access-logfile = "/home/seba94/log/gunicorn/gunicorn.log"
#error-logfile = "/home/seba94/log/gunicorn/gunicorn.error.log"
name = "register-page-gunicorn"
#Server mechanics
#daemon = True
I'm able to run successfully all processes with no errors from the cmd using the following commands:
sudo service nginx start
sudo supervisord -c /home/seba94/conf/supervisord.conf
sudo supervisorctrl start register-page-django
Nginx status is the following:
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2019-10-23 20:38:58 UTC; 31min ago
Docs: man:nginx(8)
Process: 5552 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
Process: 5599 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 5594 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 5601 (nginx)
Tasks: 2 (limit: 1108)
CGroup: /system.slice/nginx.service
├─5601 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─5760 nginx: worker process
oct 23 20:38:58 register-page-server systemd[1]: Starting A high performance web server and a reverse proxy server...
oct 23 20:38:58 register-page-server systemd[1]: Started A high performance web server and a reverse proxy server.
Honestly i can't find any errors not even in the log files so i don't know why i can't even see my static todd-logo.png file. Neither can i see the Django app running. Any help is more than welcomed
Edit:
Seems that all config files and commands in this issue are fine, the problem appeared to be a firewall configuration from a previous project. This could be an example of usage of these tools currently working
Please share the output of curl -v http://domain-name in the question as well.

Gunicorn is not binding my domain by using ".sock" file

I am trying to host multiple sites on VPS using sock file but the problem is that I can't see the website up and running using gunicorn sock. But I can't see my website live. I need to know how do I change the following screen showing my app binds with particular port instead of sock file or if it has to be a sock file then why I can't see it in browser at mydomain.com.
Gunicorn upscript is as follows:
#!/bin/bash
NAME="dressika" # Name of the application
DJANGODIR=/django/mydomain # Django project directory
SOCKFILE=/django/mydomain/run/gunicorn.sock # we will communicte using this unix socket
USER=django # the user to run as
GROUP=django # the group to run as
NUM_WORKERS=3 # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=mydomain.settings # which settings file should Django use
DJANGO_WSGI_MODULE=mydomain.wsgi # WSGI module name
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source ../bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--bind=unix:$SOCKFILE \
--name $NAME \
--workers $NUM_WORKERS \
--user=$USER --group=$GROUP \
--log-level=debug \
--log-file=-
With above settings gunicorn startup script runs fine but I couldn't see my site live on browser or client end. I guess I need to bind it with some port. I am not sure if my assumption is correct. My app settings.py shows in ALLOWED_HOSTS=['mydomain.com', 'www.mydomain.com]. Still the url isn't working.
My Nginx settings are:
upstream mydomain_server {
server 127.0.0.1:9500 fail_timeout=0;
}
server {
listen 80;
listen [::]:80;
root /home/django/mydomain;
index index.html index.htm;
client_max_body_size 4G;
server_name mydomain.com www.mydomain.com;
keepalive_timeout 5;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
expires 365d;
}
# Your Django project's media files - amend as required
location /media {
alias /home/django/mydomain/media/;
}
# your Django project's static files - amend as required
location static/static-only {
alias /home/django/mydomain/static-only/;
}
# Django static images
location /static/mydomain/images {
alias /home/django/mydomain/static-only/images/;
}
# Proxy the static assests for the Django Admin panel
location /static/admin {
alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://mydomain_server;
proxy_connect_timeout 60s;
}
}
I've also tried binding /home/django/mydomain/run/gunicorn.sock with upstream server instead of IP:Port but still couldn't see the site up and running.
I have the same problem, .sock doesn't create. This method helps me.
Prerequests:
Installed nginx: when you type in browser 127.0.0.1 - obtain "Wellcome to nginx...".
You install python2 or 3 no matter, and other stuffs: pip, django, gunicorn...
You installed and settled virtualenv. (in my case, I use virtualenvwrapper - this is good staffs, saves all you env in one folder: /home/user/.virtualenvs/)
You created django project, and when: python manage.py runserver -
you obtain "It works..." - this good news.
When you type gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application - you have the same result, as a step 4.
Next step for setting you dj.project throgh gunicorn to nginx:
You create file in /etc/systemd/system/any_file_name.service - you can named this file as you want, at DO - it names as gunicorn.service.
my method:
$cd /etc/systemd/system
$sudo touch gunicorn.service
and open it your favorite text editor
$sudo subl gunicorn.service
Inside it you write:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=vetal
Group=www-data
WorkingDirectory=/var/www/apple.net
ExecStart=/home/vetal/.virtualenvs/univ/bin/gunicorn --workers 3 --bind unix:/var/www/apple.net/mysite/mysite.sock mysite.wsgi:application
[Install] WantedBy=multi-user.target
ExecStart - what will be started by nginx, when your virualenv will be turned off. Do you remember, gunicorn was install through pip, when your env was turn on ?
-- bind unix:... - this address WHERE your .sock will created! Pay attention for this!
CHECK EVERY LETTER!TWISE!!! (of course with you links..)
Type:
$ls -l
if you see in attributes to your 'gunicorn.service' something:
-rw-r--r-- 1 root root 0 Янв 12 11:48 gunicorn.service
this means - this file is not executable, and you .sock - file will never created! Make next:
$sudo chmod 755 gunicorn.service
and check:
$ls -l
if you get:
-rwxr-xr-x 1 root root 305 Янв 11 19:48 gunicorn.service
this good! Everything allright!
Then you created nginx block, in /etc/nginx/site-available/ it likes next:
server {
listen 80;
root /var/www/apple.net;
server_name apple.net;
location = /favicon.ico { access_log off; log_not_found off; }
location = /static/ {
alias /var/www/apple.net/static/;
}
location / {
include proxy_params;
proxy_pass http://unix:/var/www/apple.net/mysite/mysite.sock;
} }
Notice: proxy_pass - must be identicaly correct with folder where .sock file created in gunicorn.service!
Copies this file to /sites-enable
$ sudo cp /etc/nginx/site-avaliable/apple.net /etc/nginx/site-enable
I don't have any domaine, so I modify my /etc/hosts file, add row:
127.0.0.10 apple.net
Very important steps!!!
$pkill gunicorn - this step kill daemon, which you may started before. gunicorn in this case, means name of file which you created before with .service extention, in /etc/systemd/system - folder.
Start gunicorn.service daemon:
$sudo systemctl start gunicorn
$sudo systemctl enable gunicorn
Start(or restart nginx)
$sudo /etc/init.d/nginx (re)start
Check your domane name in browser.
Since gunicorn is running on a socket, you need to bind to that socket, not to a port, in the upstream section.
upstream mydomain_server {
server unix:/home/django/mydomain/run/gunicorn.sock fail_timeout=0;
}
I have nginx serving up a .sock file from gunicorn. My typical gunicorn call looks like this:
exec gunicorn \
--pid /web/gunicorn.pid \
--workers '4' \
--name myapp \
--chdir /src/myapp \
--bind unix:/web/.sock \
--log-file=- \
myapp.wsgi:application
My nginx conf for / looks like this; the main difference seems to be that your proxy_pass statement doesn't point to the .sock file:
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/web/.sock;
}

bad gateway on django+gunicorn+nginx configuration

when I try to access my site I only see 502 error.
Here's my nginx configuration:
upstream pzw_server {
# server unix:/home/pzw/pzw/run/gunicorn.sock fail_timeout=0;
server 127.0.0.1:8000 fail_timeout=0;
}
server {
listen 80;
server_name my_server_ip_addr;
client_max_body_size 4G;
access_log /home/pzw/pzw/log/nginx-access.log;
error_log /home/pzw/pzw/log/nginx-error.log;
location /static/ {
alias /home/pzw/pzw/static/;
}
location /media/ {
alias /home/pzw/pzw/media/;
}
location / {
try_files $uri #proxy;
}
location #proxy {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://my_server_ip_addr;
}
}
Gunicorn startup script which I'm using:
#!/bin/bash
NAME='app_name'
DJANGODIR=/home/pzw/pzw
SOCKFILE=/home/pzw/pzw/run/gunicorn.sock
USER=pzw
GROUP=pzw
NUM_WORKERS=3
DJANGO_SETTINGS_MODULE=app_name.settings
VIRTENVDIR=/home/pzw/.virtualenvs/pzw
echo "STARTING $NAME"
cd $DJANGODIR
source "${VIRTENVDIR}/bin/activate"
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
exec "${VIRTENVDIR}/bin/gunicorn_django" \
--name $NAME \
--workers $NUM_WORKERS \
--user=$USER --group=$GROUP \
--debug \
--log-level debug #\
# --bind=unix:$SOCKFILE
Nginx logs following error:
2013/08/03 23:26:04 [error] 8582#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: my_ip, server: my_server_ip, request: "GET / HTTP/1.1", upstream: "http://my_server_ip:80/", host: "my_server_ip"
When I try to connect to 127.0.0.1:8000 on my server using lynx everything seems to be fine. Initially I tried to use unix socket, but since it didn't work(same error), I switched to TCP. Gunicorn logs nothing about connection with nginx.
The proxy_pass directive in your nginx server configuration should reflect the upstream server you configured.
proxy_pass http://pzw_server;
http://wiki.nginx.org/HttpUpstreamModule
xaxes,
Whenever you set your TEMPLATE_DEBUG to False, you also need to set ALLOWED_HOSTS so that Django knows which hosts/domains to process requests for. Apparently, the localhost works implicitly when ALLOWED_HOSTS is just the empty list.
I hope this helps!