- Prerequisites: #prerequisites
- Installation: #installation
- Setting Up FastAPI Application: #setting-up-fastapi-application
- Running FastAPI with Gunicorn: #running-fastapi-with-gunicorn
- Managing with PM2: #managing-with-pm2
- Configuring Nginx as a Reverse Proxy: #configuring-nginx-as-a-reverse-proxy
- Testing the Deployment: #testing-the-deployment
- Additional Notes: #additional-notes
- An Ubuntu server with SSH access
- Python 3.6 or newer installed
- A non-root user with sudo privileges
-
Update Package Lists:
sudo apt update
-
Install Python Dependencies:
sudo apt install python3-pip python3-venv nginx
-
Create a Virtual Environment (Recommended):
python3 -m venv venv source venv/bin/activate
-
Install FastAPI, Uvicorn, and Gunicorn:
pip install fastapi uvicorn[standard] gunicorn
-
Install PM2 (Process Manager):
sudo npm install -g pm2
-
Create a Project Directory:
mkdir my_fastapi_app cd my_fastapi_app
-
Create a Main File (main.py):
from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello World!"}
-
Start the Application:
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
-
Start with PM2:
pm2 start "gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app" --name my_fastapi_app
-
Manage PM2 Processes:
- List processes:
pm2 list
- Stop a process:
pm2 stop my_fastapi_app
- Restart a process:
pm2 restart my_fastapi_app
- List processes:
-
Create Nginx Configuration File:
sudo nano /etc/nginx/sites-available/my_fastapi_app.conf
-
Paste the Following Configuration:
server { listen 80; server_name your_domain_or_IP; location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
-
Enable the Configuration:
sudo ln -s /etc/nginx/sites-available/my_fastapi_app.conf /etc/nginx/sites-enabled/
-
Test Nginx Configuration:
sudo nginx -t
-
Restart Nginx:
sudo service nginx restart
- Access your server's IP address or domain name in a web browser. You should see the "Hello World!" message from your FastAPI app.
**##