Deploying a FastAPI application on a Virtual Private Server (VPS) involves several steps to ensure it runs efficiently, securely, and reliably. This guide will walk you through the process using Gunicorn as an application server and Nginx as a reverse proxy, along with securing your application with HTTPS using Certbot. The instructions are primarily for Ubuntu-based systems.
Prerequisites
Before you begin, ensure you have:
* A FastAPI application ready for deployment, including a requirements.txt file listing all its dependencies.
* A VPS running Ubuntu (or another Debian-based distribution).
* SSH access to your VPS.
* A registered domain name pointing to your VPS's IP address (optional, but highly recommended for HTTPS).
1. Connect to Your VPS and Update System
First, connect to your VPS via SSH and update your system's package list.
ssh your_username@your_vps_ip
sudo apt update && sudo apt upgrade -y
2. Install Python, Pip, and Virtual Environment
Install Python 3, pip (Python's package installer), and the venv module for creating virtual environments.
sudo apt install python3 python3-pip python3-venv -y
3. Clone Your FastAPI Application
Navigate to a suitable directory (e.g., /var/www/) and clone your FastAPI application from your version control system (e.g., Git).
sudo mkdir -p /var/www/your_fastapi_app
cd /var/www/your_fastapi_app
sudo git clone <your_repository_url> .
Note: Replace your_fastapi_app and the Git URL with your project's details.
It's recommended to create a dedicated non-root user for your application for security reasons.
sudo adduser your_app_user
sudo usermod -aG sudo your_app_user
sudo chown -R your_app_user:your_app_user /var/www/your_fastapi_project_name
Then, switch to this new user:
su - your_app_user
cd /var/www/your_fastapi_project_name
4. Set Up a Virtual Environment and Install Dependencies
Create a Python virtual environment for your project and install your application's dependencies, including FastAPI, Gunicorn, and Uvicorn.
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn "uvicorn[standard]" fastapi
If you don't have a requirements.txt file, you can create one using pip freeze > requirements.txt in your local development environment.
5. Test Your FastAPI Application (Locally on VPS)
Before configuring Gunicorn and Nginx, test if your FastAPI application runs correctly using Uvicorn.
uvicorn main:app --host 0.0.0.0 --port 8000
Replace main:app with the actual module and FastAPI app instance name (e.g., your_app_folder.main:app). You should be able to access your application at http://your_vps_ip:8000. Press Ctrl+C to stop the server.
6. Configure Gunicorn
Gunicorn will act as the application server, managing Uvicorn workers to handle requests.
Create a Gunicorn Configuration File (Optional but Recommended)
Create a file named gunicorn_conf.py in your project directory.
nano gunicorn_conf.py
Add the following content:
bind = "127.0.0.1:8000"
workers = 4 # Adjust based on your CPU cores (2-4 workers per core is a common recommendation)
worker_class = "uvicorn.workers.UvicornWorker"
The workers value can be tuned; a common recommendation is (2 * CPU_CORES) + 1.
Test Gunicorn
Run Gunicorn with your FastAPI application to ensure it starts correctly.
gunicorn -c gunicorn_conf.py main:app
Again, replace main:app with your application's entry point.
7. Create a Systemd Service for Gunicorn
To ensure your application starts automatically on boot and can be managed easily, create a systemd service.
sudo nano /etc/systemd/system/your_fastapi_app.service
Add the following content, adjusting paths and names as necessary:
[Unit]
Description=Gunicorn instance to serve your FastAPI app
After=network.target
[Service]
User=your_app_user
Group=your_app_user
WorkingDirectory=/var/www/your_fastapi_project_name
ExecStart=/var/www/your_fastapi_project_name/venv/bin/gunicorn -c /var/www/your_fastapi_project_name/gunicorn_conf.py main:app
Restart=always
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Explanation of fields:
* User and Group: Use a non-root user for security. www-data is common for web servers.
* WorkingDirectory: The absolute path to your FastAPI project directory.
* ExecStart: The command to start Gunicorn, pointing to your virtual environment's gunicorn executable, your configuration file, and your application entry point.
* Restart=always: Ensures the service restarts if it crashes.
Reload systemd, start the service, and enable it to run on boot.
sudo systemctl daemon-reload
sudo systemctl start your_fastapi_app
sudo systemctl enable your_fastapi_app
Check the status and logs to ensure it's running without errors.
sudo systemctl status your_fastapi_app
sudo journalctl -u your_fastapi_app -f
8. Configure Nginx as a Reverse Proxy
Nginx will act as a reverse proxy, forwarding requests from the internet to your Gunicorn application and handling static files and SSL.
Install Nginx
sudo apt install nginx -y
Create an Nginx Configuration File
Create a new Nginx server block configuration file for your application.
sudo nano /etc/nginx/sites-available/your_domain
Add the following content, replacing your_domain.com with your actual domain name and /var/www/your_fastapi_project_name with your project path:
server {
listen 80;
server_name your_domain.com www.your_domain.com;
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;
}
# Optional: Serve static files directly through Nginx
# location /static/ {
# alias /var/www/your_fastapi_project_name/static/;
# }
}
Enable the Nginx Configuration
Create a symbolic link to enable the configuration and test Nginx for syntax errors.
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
sudo nginx -t
If the test is successful, restart Nginx.
sudo systemctl restart nginx
9. Configure Firewall (UFW)
If you have a firewall enabled (e.g., UFW), configure it to allow traffic on ports 80 (HTTP) and 443 (HTTPS).
sudo ufw allow 'Nginx Full'
sudo ufw enable
Confirm with y when prompted.
Check Firewall Status:
sudo ufw status
10. Secure with HTTPS using Certbot (Let's Encrypt)
It's highly recommended to secure your application with HTTPS. Certbot automates the process of obtaining and configuring SSL certificates from Let's Encrypt.
Install Certbot
sudo apt install certbot python3-certbot-nginx -y
Obtain and Install SSL Certificate
sudo certbot --nginx -d your_domain.com -d www.your_domain.com
Follow the prompts. Certbot will automatically modify your Nginx configuration to include SSL settings and set up automatic renewal.
11. Check Your Deployment
Your FastAPI application should now be accessible via your domain name using HTTPS. Open a web browser and navigate to https://your_domain.com.
Troubleshooting Tips
- Check Gunicorn logs:
sudo journalctl -u your_fastapi_app -f - Check Nginx error logs:
sudo tail -f /var/log/nginx/error.log - Check Nginx access logs:
sudo tail -f /var/log/nginx/access.log - Verify Nginx configuration:
sudo nginx -t - Ensure correct file permissions for your project directory and virtual environment.
- Firewall issues: Double-check UFW rules.
By following these steps, you will have a production-ready FastAPI application deployed on your VPS with Nginx, Gunicorn, and HTTPS.