In this article, we'll walk through how to set up a FastAPI project on an Ubuntu server, configure it with Gunicorn for production-ready performance, and use NGINX as a reverse proxy. This setup will ensure that your FastAPI application runs efficiently and securely in a production environment.
Table of Contents:
- Prerequisites
- Setting Up the Ubuntu Server
- Installing FastAPI and Gunicorn
- Writing a Simple FastAPI Application
- Configuring Gunicorn to Serve FastAPI
- Setting Up NGINX as a Reverse Proxy
- Securing the Application with SSL (Optional)
- Conclusion
1. Prerequisites
Before starting, ensure that:
- You have an Ubuntu server (18.04, 20.04, or later).
- You have root access (or
sudo
privileges) on the server. - You have Python 3.7+ installed.
- You have NGINX installed on your server.
You will also need to install pip
for Python package management, which is typically pre-installed on most Ubuntu servers.
2. Setting Up the Ubuntu Server
If you're working with a fresh Ubuntu installation, start by updating the system and installing necessary packages:
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-dev build-essential nginx
-
python3-pip
is for installing Python packages. -
python3-dev
andbuild-essential
are required for compiling Python extensions. -
nginx
will serve as the reverse proxy.
Next, let's install and set up venv
(virtual environment) for our Python project:
sudo apt install python3-venv
3. Installing FastAPI and Gunicorn
Create a Virtual Environment:
mkdir ~/my_fastapi_project
cd ~/my_fastapi_project
python3 -m venv venv
source venv/bin/activate
This will create a virtual environment and activate it. With the virtual environment active, we can now install FastAPI and Gunicorn:
pip install fastapi gunicorn
- FastAPI is the framework we'll use to build our API.
- Gunicorn is a WSGI HTTP server that will serve the FastAPI application.
4. Writing a Simple FastAPI Application
Now let's create a simple FastAPI application. Inside your project folder (~/my_fastapi_project
), create a file called main.py
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
This is a basic FastAPI application with a single route /
that returns a JSON response with a message.
5. Configuring Gunicorn to Serve FastAPI
We will use Gunicorn to serve our FastAPI application. To do this, create a Gunicorn configuration file or run it directly from the command line.
Run the following command to start Gunicorn:
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
Explanation:
-
-w 4
: This sets the number of worker processes to 4. -
-k uvicorn.workers.UvicornWorker
: This tells Gunicorn to use Uvicorn, which is an ASGI server needed for FastAPI. -
main:app
: This is the location of the FastAPI application object (in this case, it'sapp
insidemain.py
).
You should see output indicating that Gunicorn is running and listening on port 8000 by default.
6. Setting Up NGINX as a Reverse Proxy
To ensure your FastAPI app can be accessed on port 80 (standard HTTP port), we'll configure NGINX as a reverse proxy to forward requests from port 80 to the Gunicorn server running on port 8000.
First, create a new NGINX configuration file for your project:
sudo nano /etc/nginx/sites-available/my_fastapi_project
Paste the following configuration:
server {
listen 80;
server_name your_domain_or_ip;
location / {
proxy_pass http://127.0.0.1:8000;
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;
}
}
Make sure to replace your_domain_or_ip
with your server’s domain name or IP address.
Now, create a symbolic link in the sites-enabled
directory to enable this site:
sudo ln -s /etc/nginx/sites-available/my_fastapi_project /etc/nginx/sites-enabled
Test the NGINX configuration to ensure there are no syntax errors:
sudo nginx -t
If everything is fine, reload NGINX to apply the changes:
sudo systemctl reload nginx
NGINX is now configured as a reverse proxy for your FastAPI application!
7. Securing the Application with SSL (Optional)
If you're deploying in a production environment, it’s crucial to secure your site with HTTPS. You can use Let's Encrypt for a free SSL certificate.
Install Certbot:
sudo apt install certbot python3-certbot-nginx
Obtain the SSL certificate:
sudo certbot --nginx -d your_domain.com
Certbot will automatically obtain and configure SSL for your NGINX server. You’ll now have HTTPS enabled.
Automatic SSL Renewal:
Let's Encrypt certificates are valid for 90 days, so setting up automatic renewal is essential. Certbot automatically sets up a cron job for renewal, but you can manually check with:
sudo certbot renew --dry-run
8. Conclusion
In this tutorial, we successfully set up a FastAPI application on an Ubuntu server, served it with Gunicorn, and configured NGINX as a reverse proxy. We also added an optional SSL certificate for secure HTTPS connections.
This setup provides a strong foundation for deploying FastAPI applications in production, with NGINX ensuring that the server is scalable, secure, and capable of handling a large number of requests.
Future Considerations:
- Scaling: You can scale your application by adding more Gunicorn workers or running multiple instances behind a load balancer.
- Logging: Set up proper logging to monitor your application’s health and performance.
- Error Handling: Improve error handling and add custom exception handlers in FastAPI.
By using FastAPI, Gunicorn, and NGINX together, you've created a highly performant, production-ready web service that can handle high traffic loads efficiently.
If you found this guide helpful, feel free to leave a comment below. Happy coding!
Top comments (0)