Sub topic 10
Putting Nginx in Front of Gunicorn with `proxy_pass`
Prerequisites and request flow
Assume you know basic Linux commands, file permissions, HTTP status codes, and how to manage services on Debian or Ubuntu. This chapter also assumes that your Python application works with WSGI and that Gunicorn can serve it.
Nginx is the public-facing web server. Gunicorn is the application server. Nginx accepts the client connection, serves static files when possible, and forwards application requests to Gunicorn. Gunicorn then calls the Python application and returns the response to Nginx.
A reverse proxy is a server that receives a request and sends it to another server. Nginx uses the proxy_pass directive to configure this handoff.
Configure the reverse proxy
The following server block serves files under /static/ directly. Every other request goes to Gunicorn through a Unix domain socket. A Unix socket is a local communication endpoint represented by a file. It avoids opening an application port on the network.
server {
listen 80;
server_name example.com;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
proxy_set_header Host $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;
}
}The Host header preserves the hostname requested by the client. X-Real-IP and X-Forwarded-For carry the client address. X-Forwarded-Proto tells the application whether the original request used HTTP or HTTPS.
The application must trust these headers only when they come from a trusted proxy. Otherwise, a client could send false header values directly.
The trailing behavior of proxy_pass matters. With location / and no URI path in proxy_pass, Nginx passes the original request path to Gunicorn. For example, /users remains /users.
Test the connection
Check the configuration before reloading Nginx:
sudo nginx -t
sudo systemctl reload nginx
curl -I http://example.com/
sudo tail -n 20 /var/log/nginx/error.logA 502 Bad Gateway usually means Nginx cannot reach Gunicorn. Check that Gunicorn is running, that the socket exists, and that Nginx has permission to connect to it.
A 403 Forbidden often means a file or directory permission problem. An unexpected 404 Not Found may indicate that the request was sent to the wrong location or that the application has no matching route.
Exercise
A request for /static/logo.css reaches Gunicorn instead of being served by Nginx. What should you inspect first?
Show answer
Inspect the location /static/ block, its alias path, and the actual file location. Then run sudo nginx -t and reload Nginx after correcting the configuration.