
FastAPI is a modern Python web framework for building high-performance APIs and web applications. It supports asynchronous programming using async and await, enabling efficient handling of many simultaneous client connections. Built on the ASGI (Asynchronous Server Gateway Interface) standard, FastAPI is ideal for real-time applications and remains compatible with WSGI for traditional deployments. It also offers automatic, interactive API documentation through Swagger UI, making development and testing easier and faster.
This article explains how to deploy FastAPI applications using Gunicorn as the application server and Nginx as a reverse proxy on an Ubuntu 20.04 server.
Prerequisites
- Have access to an Ubuntu 24.04 instance as a non-root sudo user
- Set up a domain A record pointing to the instance's IP address. For example,
fastapi.example.com
.
Setup FastAPI Application
In this section, you will create a FastAPI application inside a virtual environment. You will set up the project directory, install necessary dependencies, and test the application using the uvicorn ASGI server. Follow the steps below to setup the FastAPI application.
Navigate to your home directory.
console$ cd ~
Create a new directory for your FastAPI project.
console$ mkdir fastapi_demo
Navigate into the project directory.
console$ cd fastapi_demo
Update the APT package index.
console$ sudo apt update
Install the
python3-venv
package.console$ sudo apt install -y python3-venv
Create a Python virtual environment named
env
.console$ python3 -m venv venv
Activate the virtual environment.
console$ source venv/bin/activate
Install the
fastapi
package with all optional dependencies.console$ pip install fastapi[all] wheel
Add the following FastAPI application code into the file.
pythonfrom fastapi import FastAPI app = FastAPI() @app.get("/") async def home(): return {"message": "Hello World"}
Save and close the file by pressing Ctrl + X, then Enter.
Create a temporary web server using
uvicorn
.console$ uvicorn app:app
Open a new terminal session and run the following command.
console$ curl http://localhost:8000
Your output should be similar to the one below:
{"message": "Hello World"}
Deploy FastAPI using Gunicorn
Gunicorn is a Python WSGI HTTP server for UNIX systems. It simplifies the management of FastAPI applications and supports ASGI via Uvicorn worker classes. Follow the steps below to deploy your FastAPI application using Gunicorn.
Install the
gunicorn
Python package.console$ pip install gunicorn
Start a temporary Gunicorn server with the Uvicorn worker.
console$ gunicorn app:app -k uvicorn.workers.UvicornWorker
Open a new session and test the Gunicorn deployment using
curl
.console$ curl http://localhost:8000
Your output should be similar to the one below:
{"message": "Hello World"}
Create a Gunicorn configuration file named gunicorn_conf.py.
console$ nano gunicorn_conf.py
Add the following code into the file.
pythonfrom multiprocessing import cpu_count # Socket path bind = 'unix:/home/linuxuser/fastapi_demo/gunicorn.sock' # Worker options workers = cpu_count() + 1 worker_class = 'uvicorn.workers.UvicornWorker' # Logging options loglevel = 'debug' accesslog = '/home/linuxuser/fastapi_demo/access_log' errorlog = '/home/linuxuser/fastapi_demo/error_log'
Save and close the file by pressing Ctrl + X, then Enter. Replace the paths of the variables if they are different in your case.
Create and open the systemd unit file for the FastAPI Gunicorn service.
console$ sudo nano /etc/systemd/system/fastapi_demo.service
Add the following systemd service configuration to the file.
ini[Unit] Description=Gunicorn Daemon for FastAPI Demo Application After=network.target [Service] User=linuxuser Group=www-data WorkingDirectory=/home/linuxuser/fastapi_demo ExecStart=/home/linuxuser/fastapi_demo/venv/bin/gunicorn -c /home/linuxuser/fastapi_demo/gunicorn_conf.py app:app [Install] WantedBy=multi-user.target
Save and close the file by pressing Ctrl + X, then Enter.
Reload the systemd daemon.
console$ sudo systemctl daemon-reload
Start and enable the FastAPI Gunicorn service.
console$ sudo systemctl enable --now fastapi_demo
Your output should be similar to the one below:
Created symlink /etc/systemd/system/multi-user.target.wants/fastapi_demo.service → /etc/systemd/system/fastapi_demo.service.
View the status of newly created service.
console$ sudo systemctl status fastapi_demo
Test the response from the socket file using
curl
.console$ curl --unix-socket /home/linuxuser/fastapi_demo/gunicorn.sock http://localhost
Your output should be similar to the one below:
{"message":"Hello World"}
Setup Nginx as Reverse Proxy
In this section, you will configure Nginx as a reverse proxy for your FastAPI application. Nginx is a lightweight, high-performance web server commonly used to forward client requests to application servers like Gunicorn. It allows you to serve your application on standard HTTP and HTTPS ports (80 and 443), improves request handling and performance, and supports SSL termination for secure connections.
Install the Nginx Web Server.
console$ sudo apt install -y nginx
Create a virtual host configuration.
console$ sudo nano /etc/nginx/sites-available/fastapi_demo
Add the following configuration. Replace fastapi.example.com with your actual domain name.
iniserver { listen 80; server_name fastapi.example.com; location / { proxy_pass http://unix:/home/linuxuser/fastapi_demo/gunicorn.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; # Optional: Handle WebSocket connections proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # Timeout settings proxy_connect_timeout 60s; proxy_read_timeout 120s; } }
Save and close the file with Ctrl + X, then Enter.
Create a symbolic link to the sites-enabled/ directory to activate the vhost.
console$ sudo ln -s /etc/nginx/sites-available/fastapi_demo /etc/nginx/sites-enabled/
Check the Nginx configuration syntax for any errors.
console$ sudo nginx -t
Your output should be similar to the one below:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload the Nginx service to apply the new configuration.
console$ sudo systemctl reload nginx
Allow HTTP and HTTPS traffic through the firewall.
console$ sudo ufw allow 'Nginx Full'
Verify the firewall status to confirm the rules are applied.
console$ sudo ufw status
Secure Nginx with an SSL Certificate
To encrypt traffic and protect user data, you can secure your FastAPI application with HTTPS using a free SSL certificate from Let’s Encrypt. This section shows you how to configure SSL for your Nginx reverse proxy using Certbot.
Install Certbot and the Nginx plugin
console$ sudo apt install -y certbot python3-certbot-nginx
Request and install an SSL certificate.
console$ sudo certbot --nginx -d fastapi.example.com
Certbot will automatically update your Nginx configuration. When prompted, enter your email address and agree to the terms of service.
Visit the following link in a browser to confirm SSL is working.
https://fastapi.example.com
Test automatic certificate renewal.
console$ sudo certbot renew --dry-run
If no errors appear, your SSL certificate will renew automatically every 90 days.
Conclusion
You have deployed a FastAPI application with Gunicorn and Nginx on a production ready Ubuntu server. This setup uses a Unix socket for efficient communication between Gunicorn and Nginx, and leverages systemd to manage the application as a background service. By securing Nginx with a free SSL certificate from Let’s Encrypt, you’ve ensured that all client traffic is encrypted over HTTPS. This configuration provides a robust, scalable, and secure environment for running FastAPI applications in production. For more information related to FastAPI, visit the official FastAPI website.
No comments yet.