search by tags

for the user

adventures into the land of the command line

using nginx as a reverse proxy

a lot of people don’t recommend using gunicorn as a production webserver on its own. they recommend putting a reverse proxy in front of it that can scale effectively. i wanted to learn how to use nginx, so here is what worked for me

install nginx

$ sudo yum install nginx

the default nginx config file goes here

/etc/nginx/nginx.conf

and you can add your app specific ones like this

/etc/nginx/conf.d/myapp1.conf
/etc/nginx/conf.d/myapp2.conf

set up a specific config file for your app(s) in /etc/nginx/conf.d/

$ sudo vim /etc/nginx/conf.d/myapp.conf

server {
    listen                      80;
    server_name                 127.0.0.1;
    access_log  /var/log/nginx/nginx_access_myapp.log;
    error_log  /var/log/nginx/nginx_error_myapp.log;

    location / {
        proxy_pass http://0.0.0.0:5002;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        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;
    }

    location /static {
        root /var/www/myapp;
    }
}

this config file tells nginx to listen for requests coming in on a specific port and pass the request to the address and port you have gunicorn running on, this part

listen                      80;
server_name                 127.0.0.1;

location / {
    proxy_pass http://0.0.0.0:5002;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
}

under which cases a request should be passed to the next gunicorn server, only possible if nothing has been sent to a client yet

proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;

pass the real requester’s ip address to the gunicorn application logs. otherwise gunicorn will see the ip address of the computer nginx is running on as the requester

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

also, i encountered what i thought was an issue with my dev environment while using nginx for development. it seemed like whenever i made a change to a css file and reloaded my browser, nginx would still serve the old file without the changes i’d made. the answer was to actually tell nginx to serve static files as well.

location /static {
    root /var/www/myapp;
}

i don’t think you need to do this last step if you were using apache.

go nginx go!