Join our Newsletter — 33% off our NHI Course
Home› Guides› Gunicorn and uWSGI Hardening Guide: Running Python Web…
Guide Application Security

Gunicorn and uWSGI Hardening Guide: Running Python Web Apps Safely in Production

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 19 November 2026 14 min read
On this page

The Python application server sits between your reverse proxy and your code, and a handful of settings there decide who can reach the workers, which headers your app trusts, what user the code runs as and how much damage a slow or malicious client can do. This guide covers hardening Gunicorn and uWSGI for production: network exposure, proxy trust, process identity, request limits, timeouts, logging, secrets and patching.

Gunicorn and uWSGI are covered in alphabetical order, each in its own section with the same depth. This is not a comparison and neither tool is ranked; pick the one your team already runs and apply its section. Setting names and defaults are taken from each project's own documentation as published in its source repository in November 2026. Defaults can change between releases, so confirm them against the documentation for the version you deploy. For the operating system underneath, see our Linux Server Hardening Guide.

Key takeaways

  • Put the application server behind a reverse proxy, bind it to loopback or a Unix socket, and never expose its native protocol to an untrusted network.
  • Trust forwarded headers only from known proxy addresses. A wildcard trust setting is only safe when nothing else can reach the server.
  • Start as root only if you must, and drop to a dedicated unprivileged service account for the workers. That account is a non-human identity and should be owned, reviewed and given only the file access it needs.
  • Keep request size limits, worker timeouts and periodic worker recycling switched on, and never run development reloaders in production.
  • Keep secrets out of command lines and config files that are world readable, log enough to investigate an incident, and patch the server and its Python dependencies on a schedule.

Where the application server fits

A typical Python web deployment has three layers. A reverse proxy or load balancer terminates TLS and talks to the internet. The application server manages a pool of worker processes and translates HTTP or a binary protocol into calls to your WSGI application. Your Flask, Django or other framework code runs inside those workers.

The application server is often configured once and forgotten, yet it controls several security boundaries: the listening socket, the trust placed in proxy headers, the operating system identity of the code, resource limits per request and the shape of the logs. Hardening this layer does not replace secure application code, and our Flask Security Guide and Django Security Guide cover the framework side. It does make many classes of mistake far less damaging.

Both projects document that they should sit behind a proxy in production. Gunicorn's deployment guide says the project strongly recommends running Gunicorn behind a proxy server. uWSGI's best practice page says never to expose a socket speaking the uwsgi protocol to the public network, because that protocol is meant to be sanitised and validated by a proxy.

Gunicorn hardening

All setting names below are from the Gunicorn settings reference. Each can be set in a Python config file, on the command line or through the GUNICORN_CMD_ARGS environment variable.

Binding and exposure

The bind setting (-b) accepts HOST:PORT, unix:PATH or fd://FD. Its default is 127.0.0.1:8000, but if the PORT environment variable is set the default becomes 0.0.0.0:$PORT, which listens on every interface. Set bind explicitly so a platform environment variable cannot widen exposure by surprise. A Unix socket readable only by the proxy's group is the tightest option on a single host; use umask to control the permissions Gunicorn gives that socket.

Proxy trust

Three settings decide which headers Gunicorn believes:

  • forwarded_allow_ips (--forwarded-allow-ips) lists the proxy addresses or CIDR ranges allowed to set secure scheme headers. The default is 127.0.0.1,::1, or the value of the FORWARDED_ALLOW_IPS environment variable.
  • secure_scheme_headers maps headers such as X-FORWARDED-PROTO: https to a decision that the request was HTTPS. The documentation stresses that your proxy must make sure clients cannot pass these headers directly.
  • forwarder_headers lists headers the proxy may set to populate the WSGI environment, by default SCRIPT_NAME and PATH_INFO, and it can carry REMOTE_USER. The same warning applies: if a client can set REMOTE_USER through an untrusted path, it can claim an identity.

The deployment guide calls --forwarded-allow-ips='*' dangerous if untrusted clients can reach Gunicorn directly, because forged headers could make the application serve secure content over plain HTTP. Note also that these checks do not apply to Unix socket connections, which are treated as allowed unconditionally, so socket file permissions are the control there.

If you use the PROXY protocol, set proxy_protocol and restrict proxy_allow_ips (--proxy-allow-from) to your load balancer addresses. Gunicorn can also accept the uwsgi binary protocol, controlled by uwsgi_allow_ips, with the same loopback default.

Header parsing

Gunicorn has several settings that loosen HTTP parsing, all off by default: permit_obsolete_folding, strip_header_spaces, permit_unconventional_http_method, permit_unconventional_http_version and casefold_http_method. The documentation describes them as diagnostic or temporary, and says strip_header_spaces is known to induce vulnerabilities, linking to research on request smuggling. Leave them off. The header_map setting defaults to drop, which silently drops headers whose names would collide in the WSGI environment, such as names with underscores; refuse rejects such requests and dangerous restores older ambiguous mapping. Keep drop or choose refuse. Our HTTP Request Smuggling Guide explains why parser disagreements between proxy and backend matter.

Process identity

The user and group settings switch worker processes to the named account. Their defaults are the effective user and group that started Gunicorn, so if you start it as root and set nothing, the workers stay root. Set both to a dedicated service account. initgroups adds that user's supplementary groups, which you usually do not want unless a group grants a specific file permission. chdir sets the working directory before the app loads.

Limits and timeouts

  • limit_request_line defaults to 4094 bytes, with 0 meaning unlimited. limit_request_fields defaults to 100 headers. limit_request_field_size defaults to 8190 bytes per header, and the documentation warns that very high or unlimited values can open up denial of service attacks.
  • timeout defaults to 30 seconds; workers silent for longer are killed and restarted. Setting it to 0 disables timeouts entirely, which removes a key protection against hung workers.
  • graceful_timeout defaults to 30 seconds and keepalive to 2 seconds.
  • max_requests and max_requests_jitter restart each worker after a number of requests, staggered by jitter. Both default to 0, which disables recycling.

The deployment guide also warns that with the default synchronous workers, your proxy must buffer slow clients, otherwise Gunicorn becomes vulnerable to denial of service.

Development features and control interfaces

reload is documented as intended for development, and the documentation warns that while the reloader is active any client that can make requests can see the full exception and traceback if the application fails to load. Keep it off in production. Newer releases add a control socket for the gunicornc tool, documented as added in 25.1.0, with a default permission mode of 0600; keep that mode, or disable the socket with --no-control-socket if you do not use it.

TLS and logging

Gunicorn can terminate TLS itself with certfile, keyfile and ssl_context; the older ssl_version setting is documented as deprecated and ignored. Most deployments terminate TLS at the proxy instead. For logs, set accesslog and errorlog, consider capture_output so application stdout and stderr reach the error log, and adjust access_log_format to record the forwarded client address, because behind a proxy REMOTE_ADDR records the proxy rather than the client.

uWSGI hardening

All option names below are from the uWSGI options reference and the project's "Things to know" best practice page. The uWSGI documentation states that the project is in maintenance mode, receiving only bug fixes and updates for new language APIs, so factor that into your own platform lifecycle planning.

Binding and exposure

The documentation's first best practice is never to expose a socket speaking the uwsgi protocol to the public network, because that channel allows dynamic loading of applications, which amounts to arbitrary code execution. It gives the example that --socket :1234 listens on every interface, while --socket localhost:1234 limits it to loopback. Bind explicitly to loopback or a Unix socket. For Unix sockets, use chmod-socket and chown-socket so only the web server can write to them; the documentation notes that sockets are ordinary file system objects with permissions. vacuum removes generated sockets and files on exit.

The documentation also explains that http and http-socket are different: --http starts an additional router process in front of the workers, while --http-socket makes the workers speak HTTP natively. Its guidance is to use --http if exposing uWSGI directly and --http-socket when proxying behind a web server.

Process identity

The documentation is direct: do not run uWSGI instances as root. You can start as root, but drop privileges with the uid and gid options. Further containment options include chroot and cap for setting process capabilities. Treat the account named in uid as a service identity with an owner and a review date.

Limits and timeouts

  • harakiri sets the harakiri request timeout. Set it so that a request which hangs cannot hold a worker indefinitely, and check its exact behaviour in the documentation for your version.
  • limit-post limits the request body size, and buffer-size sets the internal buffer for request headers. The documentation gives the default header buffer as 4096 bytes, adjustable up to 65535.
  • max-requests reloads workers after a number of requests, and reload-on-rss reloads a worker whose resident memory passes a threshold. limit-as limits process address space.
  • listen sets the socket listen queue size.
  • post-buffering reads request bodies for the application; the documentation notes that an application which does not consume a request body can clobber the socket with the web server.

Configuration safety

uWSGI accepts unknown options in config files as placeholders, which the documentation warns can hide typos. --strict rejects anything that is not a valid option, so a mistyped security setting fails loudly instead of being ignored. need-app makes uWSGI exit if no application can be loaded, rather than running an empty server. master enables the master process, which several other options depend on.

Development features and control interfaces

The documentation says code auto-reloading features, such as the Python --py-autoreload option, must be used only in development. The stats option enables a stats server on a given address; bind it to loopback or a protected Unix socket, because it reveals internal worker state. For signal handling, the documentation notes that before uWSGI 2.1 SIGTERM triggered a reload rather than a shutdown, and lists die-on-term as no longer needed in later versions; check which behaviour your version has so that orchestrators stop it cleanly.

Plugins and packaging

Distribution packages of uWSGI tend to be modular, with language support loaded through the plugins option. Load only the plugins you need. The documentation also warns against building plugins with a different build configuration from the main binary.

Service identities and secrets

Whichever server you run, the worker processes act as a non-human identity on the host and, usually, against databases, queues and cloud APIs. Harden that identity the same way you would any service account:

  • Create a dedicated operating system account per application, with no login shell and no sudo rights.
  • Give it read access to the code and write access only to the directories it truly needs, such as an upload or cache directory. It should not be able to modify its own code.
  • Do not put database passwords or API keys on the command line, where any local user can see them in the process list. Load them from a secrets manager at start-up or from a file readable only by the service account. Our guide on Environment Variables vs Secrets Manager covers the trade-offs.
  • Restrict who can read the server config file and any environment files, since both often hold credentials.
  • Rotate application credentials on a schedule and when staff with host access leave.

Running under systemd and containers

Most production deployments start the application server from systemd or a container runtime, and both can add useful containment on top of the server's own settings. Under systemd, run the unit as the service account rather than relying only on the server's privilege drop, and use the sandboxing directives your distribution supports to make the file system read only except for the paths the application writes to. In containers, run as a non-root user in the image, mount the application code read only, set memory and CPU limits so a runaway worker cannot starve the host, and expose only the port the proxy needs on an internal network. Our Linux Server Hardening Guide covers the host controls in more depth.

Logging and monitoring

Application server logs are often the only record of which requests reached your code. Capture access logs with the real client address passed by the proxy, error logs with tracebacks kept on the server rather than sent to clients, and worker restarts caused by timeouts or memory limits. Repeated timeouts or memory recycling can indicate a denial of service attempt, a memory leak or an attacker probing an expensive endpoint. Forward logs to central storage so an attacker with access to the host cannot quietly delete them. If you expose metrics or stats endpoints, put them on a separate internal address with authentication or network restriction.

Patching and lifecycle

The application server, its Python runtime and your framework all receive security fixes. Pin versions in your dependency files, track advisories for each one and rebuild images when fixes ship. Watch for end of life Python versions too; our Python End of Life Versions page lists the dates. When you upgrade the application server, read the changelog for changes to parser strictness and defaults, because a stricter parser can reject requests that a lax one accepted, and an option you rely on may be deprecated.

Common failure patterns

  • Binding to 0.0.0.0 on a host with a public address, so the application server is reachable around the proxy.
  • Exposing a uwsgi protocol socket on a network that untrusted clients can reach.
  • Setting forwarded header trust to a wildcard while the server is also directly reachable, letting clients forge the scheme or a remote user.
  • Starting as root and never setting the worker user and group, so application code runs with full privileges.
  • Leaving reloaders or debug features on in production, which can leak tracebacks and slow the server.
  • Disabling timeouts or raising request size limits to unlimited to fix one slow endpoint.
  • Passing secrets as command line arguments, visible to any local user in the process list.
  • Leaving a stats or control socket on a reachable address.

Practitioner checklist

  • Bind explicitly to loopback or a Unix socket with restrictive permissions, behind a reverse proxy.
  • For Gunicorn, set forwarded_allow_ips and proxy_allow_ips to your proxy addresses and keep loose parsing options off. For uWSGI, keep uwsgi protocol sockets off untrusted networks.
  • Run workers as a dedicated unprivileged service account with minimal file access (Gunicorn user/group; uWSGI uid/gid).
  • Keep request size limits and worker timeouts on, and enable periodic worker recycling.
  • Disable reloaders and debug features in production, and keep control and stats interfaces local.
  • Enable strict config checking where available (uWSGI --strict) and fail if the app does not load.
  • Load secrets from a secrets manager or protected file, never from the command line.
  • Log access with the real client IP and ship logs off the host.
  • Pin and patch the server, Python and framework versions, and review changelogs before upgrades.

Standards and references

Related NHI Mgmt Group resources: Linux Server Hardening Guide · NGINX Security Hardening Guide · Python Security Guide · HTTP Request Smuggling Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.