Deploying a FastAPI project into a custom VPS

I have recently started developing with FastAPI and I would like to host my side projects on a custom VPS.

To implement this approach, the following must be installed:

  • FastAPI project
  • Custom Linux VPS
  • Nginx
  • Python
  • A custom domain (in this example: yourdomain.com) pointing to your VPS

The project:

server.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

On your VPS, create your project and a custom virtual environment:

cd myproject/
python3 -m venv venv
source venv/bin/activate
pip install fastapi "uvicorn[standard]" gunicorn

Create the Systemd Service:

/etc/systemd/system/superfastapi.service
[Unit]
Description=My Super FastAPI App
After=network.target

[Service]
User=yourusername
Group=www-data
WorkingDirectory=/path/to/myproject
Environment="PATH=/path/to/myproject/venv/bin"
ExecStart=/path/to/myproject/venv/bin/gunicorn -k uvicorn.workers.UvicornWorker server:app --bind 0.0.0.0:8000

[Install]
WantedBy=multi-user.target

Start the service:

sudo systemctl daemon-reload
sudo systemctl start superfastapi
sudo systemctl enable superfastapi

Create the Nginx vhost file:

/etc/nginx/sites-available/superfastapi
server {
    listen 80;
    server_name yourdomain.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;
    }
}

Enable it:

sudo ln -s /etc/nginx/sites-available/superfastapi /etc/nginx/sites-enabled/

Check the Nginx config:

sudo nginx -t

Restart Nginx:

sudo service nginx restart

Add SSL with Certbot:

sudo apt install python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

Happy coding!