How To Deploy FastAPI With Nginx And PM2

In this tutorial, I will show you how to deploy a FastAPI application with Nginx and PM2.

First, launch a compute instance with a cloud platform of your choice. I will be using Ubuntu version 20.04 along with the default python version 3.8 and default ubuntu user.

Update packages.

sudo apt-get update

Install nodejs.

curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

Install pip, venv, and nginx.

sudo apt-get -y install python3-pip python3-venv nginx

If you go to your IP address, you should see the welcome to nginx page.

Create a directory for the app.

mkdir hello_world
cd hello_world

Create and activate the virtualenv.

python3 -m venv venv
. venv/bin/activate

Install fastapi, uvicorn, and gunicorn.

pip install fastapi "uvicorn[standard]" gunicorn

Create the main.py file.

nano main.py

Paste the following code and save the file.

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}

Install pm2.

sudo npm install -g pm2

Start pm2.

pm2 start "gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app" --name hello_world

Verify that fastapi is running.

curl localhost:8000

Configure nginx.

cd /etc/nginx/conf.d/
sudo nano default.conf

Create a default.conf. Make sure to replace the IP address.

server {
  listen 80;
  server_name 123.456.789.10 example.com;
  location / {
    proxy_pass http://localhost:8000;
  }
}

Restart nginx.

sudo service nginx restart

Go to the IP in your browser. You should see hello world.