Getting Started with FastAPI VPS Hosting


NOTE: ProjectFolderName and ProjectName can be kept the same or different

Setting the project folder

Creating Project folder & Changing Current Directory

mkdir ~/ProjectFolderName
cd ~/ProjectFolderName 

Creating & activating Virtual env and installing FastAPI and gunicorn

virtualenv env
source env/bin/activate
pip install fastapi[all] gunicorn

Creating FastAPI app (or just git clone)

nano app.py

Inside The File Add The Below Code

from fastapi import FastAPI
                
app = FastAPI()

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

Save by pressing Ctrl+X Then Y Then Enter


Testing the API with uvicorn

uvicorn --port 8000 app:app

Testing the API with gunicorn

gunicorn -b :8000 -k uvicorn.workers.UvicornWorker app:app

Creating gunicorn configuration file

nano gunicorn_conf.py

Inside The File Add The Below Code

from multiprocessing import cpu_count

# Socket Path
bind = 'unix:/home/UserName/ProjectFolderName/gunicorn.sock'

# Worker Options
workers = cpu_count() + 1
worker_class = 'uvicorn.workers.UvicornWorker'

# Logging Options
loglevel = 'debug'
accesslog = '/home/UserName/ProjectFolderName/access_log'
errorlog = '/home/UserName/ProjectFolderName/error_log'

Save by pressing Ctrl+X Then Y Then Enter




Configuring Gunicorn

Creating and Editing the Service Unit File

sudo nano /etc/systemd/system/ProjectName.service

Inside The File Add The Below Code

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

[Service]
User=UserName
Group=www-data
WorkingDirectory=/home/UserName/ProjectFolderName
ExecStart=/home/UserName/ProjectFolderName/env/bin/gunicorn -c gunicorn_conf.py app:app

[Install]
WantedBy=multi-user.target

Save by pressing Ctrl+X Then Y Then Enter


Starting and Enabling the Service

sudo systemctl daemon-reload
sudo systemctl start ProjectName
sudo systemctl enable ProjectName



Configuring Nginx

Creating and Editing the Nginx Configuration File

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

Inside The File Add The Below Code

server {
    listen 80;
    server_name www.lazythinkers.in;

    location / {
        proxy_pass http://unix:/home/UserName/ProjectFolderName/gunicorn.sock;
        include proxy_params;
    }

    location /static/ {
        alias /home/UserName/ProjectFolderName/static/;
    }
}

Save by pressing Ctrl+X Then Y Then Enter


Creating a Symbolic Link

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

Testing and Restarting Nginx

sudo nginx -t
sudo systemctl restart nginx

The App Should Be Up and Running



Important Notice

Make sure to enable https: on to your domain ( Check Home page for steps )



Conclusion

You now have FastAPI running with Gunicorn behind Nginx. Your FastAPI application should now be accessible through your domain or IP address.