Python in production with Gunicorn and Uvicorn
Virtual environment and installation
-
python3 -m venv /home/deploy/app/.venvCreates a virtual environment for the project: a directory with its own Python interpreter and packages. Create a separate environment for each application on the server, so updating a package in one application doesn't affect another application or the system Python.
-
/home/deploy/app/.venv/bin/python -m pip install -r requirements.txtInstalls the project's packages inside the environment, using the full path to its interpreter, so you don't need to activate the environment. Don't run sudo pip: it changes the system Python and can break the distribution's own tools.
-
/home/deploy/app/.venv/bin/python -m pip install gunicornInstalls Gunicorn in the project's environment, for a WSGI application such as Flask or Django. Gunicorn has no other package dependencies.
-
/home/deploy/app/.venv/bin/python -m pip install uvicorn uvicorn-worker gunicornInstalls Uvicorn, Gunicorn, and the uvicorn-worker package that connects them, for an ASGI application such as FastAPI or Django in async mode. Add the packages to the requirements.txt file, so they're installed on the next server too.
-
/home/deploy/app/.venv/bin/gunicorn --helpEvery command installed in the environment lives in its bin directory and runs with the environment's interpreter, even without activating it. This is the path you write in a systemd service file and in a crontab entry.
Running with Gunicorn
-
gunicorn myproject.wsgiRuns a Django project through the myproject/wsgi.py file. With no other options, Gunicorn listens on 127.0.0.1:8000 with a single worker. Run it from the directory that contains manage.py.
-
gunicorn -w 4 'hello:app'Runs a Flask application using the module:variable pattern: the hello module and the app variable. The -w option sets the number of workers, separate processes that each handle requests.
-
gunicorn -w 4 'hello:create_app()'Runs an application built by a function (an app factory): Gunicorn calls the function and uses the application it returns.
-
gunicorn -w 5 -b 127.0.0.1:8000 myproject.wsgiThe Gunicorn documentation suggests (2 x number of CPU cores) + 1 as a starting point, which is 5 workers on a 2-core server in the example, and then tuning by load. Usually 4 to 12 workers are enough even for heavy traffic, and too many workers waste memory.
-
gunicorn -b unix:/run/myapp/gunicorn.sock myproject.wsgiListens on a local socket file instead of a port, and Nginx on the same server connects to it. The user that runs Gunicorn needs write access to the directory, for example a directory systemd creates with RuntimeDirectory.
-
gunicorn --timeout 60 myproject.wsgiA worker that doesn't report that it's alive for the set number of seconds is killed and restarted. The default is 30. With sync workers, keep the value low, and move long tasks to background processing.
-
gunicorn --max-requests 1000 --max-requests-jitter 50 myproject.wsgiRestarts each worker after 1,000 requests, plus a random number up to 50, so the workers don't all restart at the same moment. This keeps a memory leak in the code from building up over time.
-
gunicorn -k gthread --threads 4 -w 3 myproject.wsgiA gthread worker runs several threads in each process. The threads share memory, so memory use is lower than when you add workers. The default worker type is sync.
-
gunicorn --preload myproject.wsgiLoads the application once before the workers are created, which saves memory and speeds up startup. With this option, new code is picked up only on a full restart of the service.
-
gunicorn --access-logfile - --error-logfile - myproject.wsgiWrites the access log and the error log to the process output, and under systemd they're kept in the journal. The access log is off by default.
-
gunicorn --check-config myproject.wsgiChecks the configuration and exits. A quick way to make sure the application loads without errors before a restart.
-
gunicorn --print-config myproject.wsgiShows the final configuration after merging the file, the environment variables, and the command line.
The gunicorn.conf.py file
-
bind = "unix:/run/myapp/gunicorn.sock" workers = 5 timeout = 30 max_requests = 1000 max_requests_jitter = 50 accesslog = "-" errorlog = "-"A configuration file written in Python. By default, Gunicorn reads gunicorn.conf.py from the working directory, and runs it on every start and every reload. Some setting names differ from the command line options, for example accesslog instead of --access-logfile.
-
gunicorn -c /home/deploy/app/gunicorn.conf.py myproject.wsgiStarts with a configuration file at an explicit path. An option on the command line overrides the same setting in the file.
-
GUNICORN_CMD_ARGS="--bind=127.0.0.1:8000 --workers=3" gunicorn myproject.wsgiPasses options in an environment variable. They override the file, and the command line overrides both.
Running with Uvicorn
-
uvicorn main:app --host 127.0.0.1 --port 8000Runs an ASGI application, such as FastAPI, from the main.py file and the app variable. These are also the default values: the local address only and port 8000.
-
python -m uvicorn myproject.asgi:applicationRuns a Django project through the myproject/asgi.py file. Run it from the directory that contains manage.py.
-
uvicorn main:app --workers 4Runs several processes, and Uvicorn restarts a process that crashes. Without the option, the value comes from the WEB_CONCURRENCY variable, and when it isn't set, a single process runs. Don't combine it with --reload, which is meant for development only.
-
uvicorn main:app --uds /run/myapp/uvicorn.sockListens on a local socket file instead of a port, and Nginx on the same server connects to it.
-
uvicorn main:app --proxy-headers --forwarded-allow-ips 127.0.0.1Behind Nginx, the application gets the visitor's IP address and the protocol (http or https) from the X-Forwarded-For and X-Forwarded-Proto headers. The option is on by default, and Uvicorn trusts the headers only when the request comes from an address on the list, which defaults to 127.0.0.1 and ::1. The value * trusts any address and lets anyone forge the visitor's IP address.
-
uvicorn main:app --env-file /etc/myapp/envLoads environment variables for the application from a file. Settings for Uvicorn itself, with the UVICORN_ prefix, aren't read from this file.
-
uvicorn main:app --limit-max-requests 1000Restarts a process after the set number of requests, like max_requests in Gunicorn.
-
uvicorn main:app --root-path /apiSets the base path for an application served under a subpath, for example example.com/api, when Nginx strips the path before passing the request on.
-
uvicorn main:app --log-level warning --no-access-logCuts down the log output: warnings and errors only, without a line for every request. A good fit when Nginx already keeps an access log.
Gunicorn with Uvicorn workers
-
gunicorn main:app -w 4 -k uvicorn_worker.UvicornWorkerGunicorn manages the processes, and each worker runs Uvicorn, which runs the ASGI application. The combination gives Uvicorn the process management of Gunicorn: restarting a stuck worker, timeout, and max_requests. Requires the uvicorn-worker package.
-
python -m gunicorn myproject.asgi:application -k uvicorn_worker.UvicornWorkerThe same combination for a Django project in ASGI mode, as shown in the Django documentation.
-
uvicorn.workers.UvicornWorkerThe old class, which appears in many tutorials. According to the Uvicorn documentation, the uvicorn.workers module is deprecated and will be removed in a future version. Use uvicorn_worker.UvicornWorker instead.
-
gunicorn main:app -k asgi -w 4Recent versions of Gunicorn also include a built-in asgi worker, which runs ASGI applications such as FastAPI and Starlette without Uvicorn, including WebSockets.
systemd service
-
[Unit] Description=Gunicorn for myapp After=network.target [Service] Type=notify NotifyAccess=main User=deploy Group=deploy RuntimeDirectory=myapp WorkingDirectory=/home/deploy/app EnvironmentFile=/etc/myapp/env ExecStart=/home/deploy/app/.venv/bin/gunicorn -c /home/deploy/app/gunicorn.conf.py myproject.wsgi ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=5 PrivateTmp=true Restart=on-failure [Install] WantedBy=multi-user.targetA systemd unit in the /etc/systemd/system/myapp.service file. The application runs as a regular user, not as root, ExecStart points to the full path of Gunicorn inside the virtual environment, and RuntimeDirectory creates the /run/myapp directory for the socket file. Restart=on-failure restarts the service after a crash.
-
ExecStart=/home/deploy/app/.venv/bin/uvicorn main:app --uds /run/myapp/uvicorn.sock --workers 4The ExecStart line for an application that runs directly with Uvicorn. In such a service, use Type=simple instead of Type=notify.
-
sudo systemctl daemon-reload && sudo systemctl enable --now myappLoads the unit file, sets the application to start automatically when the server boots, and starts it right away.
-
sudo systemctl reload myappSends Gunicorn the HUP signal: it reloads the configuration, starts new workers with the new code, and shuts down the old ones after they finish the requests they're handling. With --preload, new code is picked up only on a restart.
-
sudo systemctl restart myappStops the service and starts it again. Needed after a change to the unit file, together with daemon-reload.
-
sudo journalctl -u myapp -fShows the application's log in real time, including load errors and tracebacks. Press Ctrl+C to exit.
-
[Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock SocketUser=nginx SocketGroup=nginx SocketMode=0660 [Install] WantedBy=sockets.targetWith socket activation, systemd creates the socket file and hands it to Gunicorn, so requests wait even while the service restarts. The gunicorn.socket file works together with gunicorn.service, where you add the line Requires=gunicorn.socket to the [Unit] section. The nginx user fits RHEL-based distributions, and on Debian and Ubuntu, the user is www-data.
-
sudo systemctl enable --now gunicorn.socketStarts the socket and sets it to start when the server boots. The service itself starts on the first request.
Nginx as a reverse proxy
-
upstream app_server { server unix:/run/myapp/gunicorn.sock fail_timeout=0; }Sets the application as the Nginx upstream through the socket file. With fail_timeout=0, Nginx keeps trying to connect even after a failure, for example during a restart. For an application that listens on a port, write server 127.0.0.1:8000.
-
location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass http://app_server; }Nginx receives requests from the internet and passes them to the application along with the domain name, the visitor's IP address, and the protocol. Nginx also buffers requests from slow clients, which matters most for sync workers, since otherwise they're tied up for the whole transfer.
-
location /static/ { alias /home/deploy/app/staticfiles/; }Nginx serves the static files directly from disk, without going through Python. In a Django project, you collect them into the directory set in STATIC_ROOT with python manage.py collectstatic.
-
map $http_upgrade $connection_upgrade { default upgrade; '' close; }A setting in the http block that sets the Connection header based on the upgrade request. Required for an ASGI application with WebSockets, together with the setting in the next command.
-
location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; }A location block for an ASGI application: it passes WebSocket upgrade requests, and proxy_buffering off lets streamed responses reach the visitor as they're sent. When Gunicorn runs the application, the documentation recommends an async worker in this setup.
-
client_max_body_size 20m;The maximum request size, for example for a file upload. Nginx blocks a larger request with a 413 error.
-
sudo nginx -t && sudo systemctl reload nginxChecks the configuration syntax, and reloads the configuration only when the check passes, without dropping connections.
Environment variables and production settings
-
EnvironmentFile=/etc/myapp/envLoads environment variables for the service from a file, in KEY=value lines, for example the database password and the secret key. Keep the file outside the project directory and outside any directory Nginx serves, and don't commit it to the code repository.
-
sudo chown root:root /etc/myapp/env && sudo chmod 600 /etc/myapp/envOnly root can read the file. systemd reads it before it switches the service to the user in the User line, so the application gets the variables without access to the file itself.
-
DEBUG = False ALLOWED_HOSTS = ["example.com", "www.example.com"]In Django, never run a production server with DEBUG on: the detailed error page exposes code and settings. When DEBUG is off, you must list the site's domains in ALLOWED_HOSTS.
-
python manage.py check --deployChecks the settings of a Django project against the production checklist, and shows warnings about missing or insecure settings.
-
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")Behind Nginx with HTTPS, Django recognizes a secure request by the X-Forwarded-Proto header. Set this only when Nginx sets the header itself, as in the configuration on this page.
-
from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix( app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 )In Flask behind Nginx: the application gets the visitor's IP address, the protocol, and the domain from the X-Forwarded headers. The number 1 is the number of servers in front of the application that set each header, and you use ProxyFix only when such a proxy actually exists.
Common problems
-
sudo systemctl status myappWhen Nginx returns 502 Bad Gateway, first check that the service is running. When it isn't, the last lines of the log show the reason, for example an error in the code or the configuration.
-
sudo -u nginx curl --unix-socket /run/myapp/gunicorn.sock http://localhost/Sends a request to the application through the socket file, with the permissions of the Nginx user. A valid response means the application works and Nginx is allowed to connect. On Debian and Ubuntu, the user is www-data.
-
namei -l /run/myapp/gunicorn.sockThe error connect() to unix:... failed (13: Permission denied) in the Nginx log means it has no permission for the socket file or for one of the directories on the way to it. The command shows the permissions of every directory in the path.
-
sudo tail -f /var/log/nginx/error.logThe Nginx error log shows why the proxy failed: connect() failed when the application isn't listening, or upstream timed out when the application didn't respond in time.
-
gunicorn --timeout 120 myproject.wsgiThe [CRITICAL] WORKER TIMEOUT message in the log means a worker didn't respond within the time set in timeout, so it was restarted. Raise the value only for requests that really take long, and move heavy tasks to background processing.
-
sudo dmesg -T | grep -i 'out of memory'The message Worker (pid:...) was sent SIGKILL! Perhaps out of memory? in the Gunicorn log, together with 502 errors, usually points to a memory shortage: the operating system killed the process. The command shows whether this happened and which process was killed. Reduce the number of workers or add memory.
-
sudo ss -ltnp 'sport = :8000'The Address already in use error, or Connection in use in Gunicorn, means another process is already listening on the port. The command shows which process listens on port 8000, usually a previous copy of the application that's still running.
-
/home/deploy/app/.venv/bin/python -m pip show gunicornThe ModuleNotFoundError: No module named ... error usually means the service runs with a different Python than the virtual environment's, for example the system gunicorn. The command checks that Gunicorn is installed in the environment, and ExecStart should point to its path.
-
gunicorn --chdir /home/deploy/app myproject.wsgiWhen the ModuleNotFoundError refers to a module of the project itself, Gunicorn isn't running from the project directory. The --chdir option, or WorkingDirectory in the service file, sets the directory.
-
namei -l /home/deploy/app/staticfiles/Static files that return 404 or 403: check that the path in alias is correct, that you ran collectstatic, and that the Nginx user can traverse every directory in the path. A home directory with 700 permissions blocks it.
No matching commands.
A Python application server receives HTTP requests and passes them to the application code through a defined interface. WSGI is the older, synchronous interface: each worker handles one request at a time, and it suits Flask and Django. ASGI is the asynchronous interface, which also supports WebSockets and long-lived connections, and it suits FastAPI, Starlette, and async Django code. For a WSGI application, use Gunicorn. For an ASGI application, use Uvicorn, or Gunicorn with Uvicorn workers, which gives an ASGI application the process management of Gunicorn. The older uWSGI server is described in its own documentation as a project in maintenance mode, which means it only gets bug fixes and updates for the APIs of new language versions.
Install the application server inside the project's virtual environment, not with sudo pip. The commands for creating the environment and installing packages are on the pip and venv commands page. Run the application as a systemd service under a regular user. The commands for managing the service are on the systemctl commands page.
The application server listens only on 127.0.0.1 or on a local socket file, and Nginx in front of it receives requests on ports 80 and 443, handles the SSL certificate, and serves the static files. More settings are on the Nginx cheat sheet, and an Apache alternative is on the Apache cheat sheet. When Nginx returns 502 or 504, the full checks are on the 500, 502, 503, and 504 server errors page. For the application's database and cache, see PostgreSQL commands and Redis commands, and to run it in a container, see Docker commands. The user names, paths, and applications on this page are examples, so replace them with your project's values.
On a Python VPS, the environment comes ready: Python, pip, and venv are installed and configured, and you get full root access over SSH, so you install Gunicorn or Uvicorn in the virtual environment and start your application right away. On a Linux VPS, you connect over SSH with full root access and set up everything on this page, from the systemd service to the reverse proxy.
Python in production FAQ
What's the difference between Gunicorn and Uvicorn?
Gunicorn is a mature WSGI server that manages several workers and restarts a worker that gets stuck. It suits Flask and Django applications. Uvicorn is built for ASGI, which suits asynchronous applications such as FastAPI and also supports WebSockets. You can also combine the two: Gunicorn manages the processes, and each worker runs Uvicorn, using the uvicorn-worker package.
How many workers should I set in Gunicorn?
The Gunicorn documentation suggests starting from (2 x number of CPU cores) + 1, for example 5 workers on a 2-core server, and tuning by the actual load. Each worker is a separate process with its own memory, so check memory use too. Usually 4 to 12 workers are enough even for heavy traffic.
Can I run Django, Flask, and FastAPI applications on a VPS?
Yes. A Python VPS comes with Python, pip, and venv preinstalled, and you get full root access over SSH. You create a virtual environment for each application, install Gunicorn or Uvicorn in it, run the application as a systemd service, and set up Nginx in front of it. All the settings stay fully under your control, and several applications can run on the same server, each in its own environment.
How do I update the code of a Python application without downtime?
After you upload the new code, run sudo systemctl reload with the service name. Gunicorn receives the HUP signal, starts new workers with the updated code, and shuts down the old ones only after they finish the requests they're handling, so visitors don't get errors. When the application runs with the --preload option, new code is picked up only on a full restart of the service.
What does the WORKER TIMEOUT message in the Gunicorn log mean?
The message means a worker didn't respond within the time set in the timeout setting, which defaults to 30 seconds, so Gunicorn restarted it. When some requests are expected to take a long time, raise the value, for example --timeout 120. Move especially heavy tasks to background processing, so the visitor gets a fast response.