How to Deploy FastAPI Applications with Gunicorn and Nginx

Published on 15 April 2024

FastAPI, a Python framework renowned for its simplicity and speed, has become a potent tool for creating APIs. But a stable configuration is needed before deploying FastAPI apps in a production environment. Using Nginx as a reverse proxy and Gunicorn as the WSGI server, we will demonstrate how to install a FastAPI application in this tutorial. Let’s Encrypt will also be used to secure the deployment with an SSL certificate.

Step 1: Setting up the FastAPI Application

First things first, make sure you are in the project directory of the FastAPI application. To separate the dependencies for your project, create a virtual environment here. Now that this virtual environment is up and running, use pip to install the required dependencies. After installation, launch your FastAPI application with uvicorn to make sure it functions properly locally.First, navigate to your project directory:

cd /home/demo/fastapi_demo

Create a virtual environment using python commands and activate it :

python3 -m venv venv
source venv/bin/activate

Install the project dependencies using the PIP command:

pip install -r requirements.txt

Test the deployment locally using the uvicorn command:

uvicorn main:app

Step 2: Deploying FastAPI with Gunicorn

Next, use pip to install Gunicorn in your virtual environment in preparation for production deployment. To verify compatibility and functionality, use Gunicorn to test the deployment of your FastAPI application after it has been installed.

pip install gunicorn

Test the deployment with Gunicorn:
gunicorn main:app -k uvicorn.workers.UvicornWorker

Step 3: Creating a Systemd Service for Gunicorn

Make sure your FastAPI application is consistently running by setting up a Systemd service for Gunicorn to simplify management. To get started, set up the parameters for Gunicorn in a separate file. These include the socket path, worker options, and logging preferences. Next, in order to administer the Gunicorn service, create a Systemd unit file. After the service has been configured, activate it and check its status to make sure the deployment went well. Create a configuration file for Gunicorn:

nano gunicorn_conf.py

Paste the following configuration:

from multiprocessing import cpu_count

bind = 'unix:/home/demo/fastapi_demo/gunicorn.sock'
workers = cpu_count() + 1
worker_class = 'uvicorn.workers.UvicornWorker'
loglevel = 'debug'
accesslog = '/home/demo/fastapi_demo/access_log'
errorlog = '/home/demo/fastapi_demo/error_log'

Create and edit a systemd unit file:
sudo nano /etc/systemd/system/fastapi_demo.service

Paste the following configuration:

[Unit]
Description=Gunicorn Daemon for FastAPI Demo Application
After=network.target

[Service]
User=demo
Group=www-data
WorkingDirectory=/home/demo/fastapi_demo
ExecStart=/home/demo/fastapi_demo/venv/bin/gunicorn -c gunicorn_conf.py app:app

[Install]
WantedBy=multi-user.target

Start and enable the service and Verify the status:
sudo systemctl start fastapi_demo
sudo systemctl enable fastapi_demo
sudo systemctl status fastapi_demo

Step 4: Setting up Nginx as a Reverse Proxy

In order to effectively handle incoming requests to your FastAPI application, integrate Nginx as a reverse proxy now. Installing Nginx via your package manager should be the first step. Next, in Nginx’s configuration directory, create a virtual host configuration unique to your FastAPI application. Once the virtual host is configured, load Nginx again and activate it to make the changes take effect. This will route incoming traffic to your FastAPI application.

sudo apt update
sudo apt install nginx

Create a virtual host configuration:

sudo nano /etc/nginx/sites-available/fastapi_demo

Paste the following configuration (replace your_domain with your actual domain):

server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        proxy_pass http://unix:/home/demo/fastapi_demo/gunicorn.sock;
    }
}

Activate the virtual host configuration:
sudo ln -s /etc/nginx/sites-available/fastapi_demo /etc/nginx/sites-enabled/

Test and reload the Nginx configuration:

sudo nginx -t
sudo systemctl reload nginx

Step 5: Securing Nginx with an SSL Certificate

Using an SSL certificate to secure Nginx will improve deployment security. To get and install a certificate for your domain, use Certbot, an SSL certificate management tool. Proceed with the instructions to verify and set up the certificate, guaranteeing secure communication between users and your FastAPI programme. Install Certbot:

sudo apt install -y certbot python3-certbot-nginx

Install a certificate on Nginx:

sudo certbot --nginx -d your_domain -d www.your_domain

Step 6: Verifying Accessibility and Auto-Renewal

You can verify if the SSL Certificate is configured properly by opening the link in your web browser

Ensure auto-renewal works by running:

sudo certbot renew --dry-run

Conclusion:

By following these procedures, you have effectively used Nginx and Gunicorn to launch a FastAPI application, secured it with an SSL certificate, and enabled certificate auto-renewal. Your FastAPI apps will run in a stable and safe environment thanks to this configuration.