Sub topic 10
Putting Nginx in front of Gunicorn with proxy_pass
This chapter connects Nginx to a running Gunicorn server. It assumes you can already run a WSGI app under Gunicorn and manage it with systemd. It also assumes you know basic Nginx server blocks and location matching, and that you are on a Debian/Ubuntu-style host. The example app lives in /srv/myapp, and its WSGI callable is application in app.py.
Why put Nginx in front
Gunicorn is a good application server, but it is not meant to face the internet directly. It handles slow clients badly, it does not serve static files efficiently, and it does not terminate TLS in a typical deployment. Nginx does these jobs well.
In this arrangement, Nginx is a reverse proxy. It accepts the client's connection, forwards the request to Gunicorn as a new request, and relays the response back. Gunicorn's workers are freed as soon as they hand over the response, even if the client downloads it slowly.
Step 1: Run Gunicorn under systemd
Before Nginx can forward anything, Gunicorn must be listening. Use the unit below. It binds a Unix socket in /run/gunicorn.
[Unit]
Description=Gunicorn for myapp
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/srv/myapp
RuntimeDirectory=gunicorn
ExecStart=/srv/myapp/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn/app.sock app:application
Restart=on-failure
[Install]
WantedBy=multi-user.targetRuntimeDirectory=gunicorn makes systemd create /run/gunicorn owned by www-data each time the service starts. It also removes the directory on stop, so you never have a stale socket from a crashed run. Save the file as /etc/systemd/system/gunicorn.service, then run:
sudo systemctl daemon-reload
sudo systemctl enable --now gunicornYou can test the socket without Nginx. curl can talk to a Unix socket directly:
curl --unix-socket /run/gunicorn/app.sock http://localhost/If this fails, fix Gunicorn first. Debugging two layers at once is slower than debugging one.
Step 2: The Nginx server block
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;
}
}On Debian/Ubuntu, save it as /etc/nginx/sites-available/myapp and link it into sites-enabled:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
sudo nginx -t
sudo systemctl reload nginx
curl -I http://example.com/What each part does
location /static/matches paths that begin with/static/. Nginx reads the file from disk and never contacts Gunicorn. Because this prefix is more specific than/, it wins.location /matches everything else, so every non-static request is proxied.proxy_pass http://unix:/run/gunicorn/app.sock;names the upstream. Theunix:prefix tells Nginx the address is a socket path and not a host name. For a TCP upstream you would writeproxy_pass http://127.0.0.1:8000;and bind Gunicorn to127.0.0.1:8000.- The
proxy_set_headerlines add request headers. They are explained below.
alias versus root
With alias, the matched location prefix is replaced by the alias path. A request for /static/site.css reads /srv/myapp/static/site.css. With root, the full URI is appended to the root, so the same request would read /srv/myapp/static/static/site.css. Keep the trailing slash on both the location and the alias, or you will get paths such as /srv/myapp/staticsite.css.
Headers: why Host and friends are set by hand
Nginx builds a new request to Gunicorn. By default it sets Host to the name of the upstream ($proxy_host), which for a socket is a meaningless value. Your app would then generate wrong absolute URLs and fail host validation. proxy_set_header Host $host; restores the name the client used.
The other three headers carry information that the app cannot see otherwise, because from Gunicorn's point of view every connection comes from Nginx:
| Header | Value | Purpose |
|---|---|---|
| `X-Real-IP` | `$remote_addr` | The address of the connecting client |
| `X-Forwarded-For` | `$proxy_add_x_forwarded_for` | The client address appended to any existing chain |
| `X-Forwarded-Proto` | `$scheme` | `http` or `https`, so the app can build correct links |
The app only benefits if it trusts these headers. Gunicorn honors X-Forwarded-Proto only from addresses listed in its forwarded_allow_ips setting, and frameworks such as Flask and Django need their own proxy settings to read X-Forwarded-For. Trust these headers only when the app is reachable solely through Nginx. Otherwise a client can forge them.
How proxy_pass treats the URI
Whether proxy_pass has a path part changes what Gunicorn receives.
- Without a URI (
proxy_pass http://127.0.0.1:8000;), the original request path is passed unchanged. - With a URI (
proxy_pass http://127.0.0.1:8000/;), the part of the path that matched thelocationis replaced by that URI.
Take location /app/ with a request for /app/users. With no URI, Gunicorn sees /app/users. With a trailing /, it sees /users. This is the most common cause of an app that works at / but returns 404 under a sub-path. For a Unix socket, the URI form is proxy_pass http://unix:/run/gunicorn/app.sock:/;, with a colon after the socket path.
Also note that using variables inside proxy_pass changes its behavior. Nginx then does no automatic path replacement and may need a resolver for host names.
Socket permissions
The Nginx worker process must be able to connect to the socket. That requires execute permission on every directory in the path and write permission on the socket file itself. In this chapter both Gunicorn and Nginx workers run as www-data, so it works. If Gunicorn runs as a different user such as myapp, there are two usual fixes:
- Give Gunicorn the group
www-data(Group=www-datain the unit) and start it with--umask 007, so the socket is group-writable and other users have no access. - Switch to a TCP binding on
127.0.0.1, where file permissions do not apply.
Timeouts and buffering
Defaults you may need to change:
proxy_read_timeoutis 60 seconds. If Gunicorn takes longer to send a response, Nginx returns 504. Raise it only for endpoints that truly need it, and make sure Gunicorn's own--timeout(30 seconds by default) is consistent, because Gunicorn kills a worker that exceeds it.proxy_bufferingis on. Nginx reads the whole response from Gunicorn quickly and then feeds it to the client. This is what frees workers early. Turn it off only for streaming responses such as server-sent events.client_max_body_sizeis 1 MB. Uploads larger than that fail with 413 before Gunicorn sees them.
Diagnosing failures
After every change, run sudo nginx -t before reloading. When a response is wrong, check the Nginx error log first:
sudo tail -n 20 /var/log/nginx/error.log| Symptom | Typical log line | Cause and fix |
|---|---|---|
| 502 Bad Gateway | `connect() to unix:/run/gunicorn/app.sock failed (2: No such file or directory)` | Gunicorn is not running or binds elsewhere. Check `systemctl status gunicorn` and the socket path. |
| 502 Bad Gateway | `failed (13: Permission denied)` | Nginx cannot open the socket. Fix ownership, group, or umask as described above. |
| 502 Bad Gateway | `failed (111: Connection refused)` | A TCP upstream has no listener on that port. |
| 504 Gateway Timeout | `upstream timed out (110: ...)` | The app is slower than `proxy_read_timeout`. Find the slow code path, or raise the timeout. |
| 404 on `/static/...` | `open() "/srv/myapp/static/..." failed (2: ...)` | Wrong `alias` path, a missing trailing slash, or the files were never collected. |
| 403 on `/static/...` | `(13: Permission denied)` | The Nginx user cannot read the files or traverse a parent directory. |
To tell whether a 404 came from Nginx or from the app, look at the body. Nginx's own error page names Nginx. A page styled by your framework came from Gunicorn. Then compare with the direct curl --unix-socket request from Step 1.
Exercise
Users report that https://example.com/app/users returns 404, but the same route works when you call Gunicorn directly at /users. Your block is location /app/ { proxy_pass http://unix:/run/gunicorn/app.sock; }. What is wrong, and what change fixes it?
Show answer
Without a URI part on proxypass, Nginx forwards the original path, so Gunicorn receives /app/users, which the app does not define. Add a URI so the matched prefix is replaced: `proxypass http://unix:/run/gunicorn/app.sock:/;. Gunicorn then receives /users. Run sudo nginx -t` and reload to apply it.
Exercise
Nginx returns 502 and the error log says connect() to unix:/run/gunicorn/app.sock failed (13: Permission denied). Gunicorn runs as user myapp. Name two ways to fix this.
Show answer
Run Gunicorn with Group=www-data and a group-writable socket (for example --umask 007) so the Nginx worker can write to it, or bind Gunicorn to 127.0.0.1 on a TCP port so file permissions no longer apply. Also confirm that the /run/gunicorn directory is traversable by the Nginx user.