I. Why Deploy FastAPI?¶
FastAPI is a high-performance Python web framework ideal for building API services. However, after development, you need to deploy the code to a cloud server to allow other devices (such as mobile phones, front-end projects, or other servers) to access your API. This article will guide you through the entire deployment process from local debugging to cloud server deployment.
II. Local Development Environment Setup¶
1. Install FastAPI and Uvicorn¶
First, install FastAPI and Uvicorn (FastAPI requires an ASGI server, and Uvicorn is the most common choice) on your local machine:
pip install fastapi uvicorn
2. Write Your First FastAPI Endpoint¶
Create a simple main.py file with the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
3. Test Locally¶
Start the service in the terminal with:
uvicorn main:app --reload
main:app: Imports theappobject (FastAPI instance) frommain.py.--reload: Development mode that automatically restarts the server when code changes (remove in production).
Visit http://127.0.0.1:8000 to see {"message": "Hello, FastAPI!"}, confirming successful local development.
III. Cloud Server Preparation¶
1. Purchase a Cloud Server¶
Choose a cloud provider (e.g., Alibaba Cloud, Tencent Cloud, AWS) and buy a Linux server (Ubuntu 20.04 or CentOS 8 recommended). After purchasing, obtain:
- Server IP address (e.g., 120.xx.xx.xx)
- Login username (e.g., ubuntu or root)
- Login password/key (for remote connection)
2. Connect to the Cloud Server Remotely¶
Connect via terminal or tools (e.g., Xshell, FinalShell):
- Linux/Mac Terminal: Use ssh 用户名@服务器IP, e.g., ssh ubuntu@120.xx.xx.xx
- Windows: Recommended tools like PuTTY or FinalShell, input IP and credentials.
IV. Cloud Server Environment Setup¶
1. Install Python Environment¶
FastAPI requires Python 3.7+. Install Python and package manager on the server:
# For Ubuntu/Debian
sudo apt update && sudo apt install python3 python3-pip python3-venv
# For CentOS (install epel-release first)
sudo yum install -y epel-release
sudo yum install -y python3 python3-pip
2. Create Project Directory and Upload Code¶
Assume the project is in /var/www/fastapi_demo on the server:
# Create directory
mkdir -p /var/www/fastapi_demo
cd /var/www/fastapi_demo
# Upload local code (use scp)
# Execute locally (replace paths and server info):
scp /local/path/main.py ubuntu@120.xx.xx.xx:/var/www/fastapi_demo/
scp /local/path/requirements.txt ubuntu@120.xx.xx.xx:/var/www/fastapi_demo/
- requirements.txt: Generate with
pip freeze > requirements.txtlocally, then upload and install.
3. Install Project Dependencies¶
On the server, install dependencies:
cd /var/www/fastapi_demo
pip3 install -r requirements.txt
V. Start FastAPI Service (Production Configuration)¶
For production, use a more stable setup than uvicorn main:app --reload.
1. Use systemd to Manage Services (Auto-restart on Boot)¶
Create a systemd service file:
sudo nano /etc/systemd/system/fastapi.service
Add the following content:
[Unit]
Description=FastAPI Demo Service
After=network.target # Start after network is ready
[Service]
User=ubuntu # Server username (match your login user)
WorkingDirectory=/var/www/fastapi_demo # Project directory
ExecStart=/usr/bin/uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
# --host 0.0.0.0: Allow external access; --port 8000: Service port; --workers 4: 4 workers (adjust based on CPU cores)
Restart=always # Auto-restart on failure
[Install]
WantedBy=multi-user.target # Start on multi-user boot
2. Start and Enable the Service¶
sudo systemctl daemon-reload # Reload service config
sudo systemctl start fastapi # Start the service
sudo systemctl enable fastapi # Enable auto-start on boot
3. Verify Service Status¶
sudo systemctl status fastapi # Should show "active (running)"
VI. Configure Firewall and Security Groups¶
Cloud servers have firewalls; open port 8000:
- Aliyun/Tencent Cloud: In the console, go to “Security Groups” → Add rule: Inbound, Port 8000, Allowed IP 0.0.0.0/0 (restrict to specific IPs in production).
- Linux Firewall:
# For Ubuntu (ufw)
sudo ufw allow 8000/tcp # Allow external access to port 8000
# For CentOS (firewalld)
sudo firewall-cmd --add-port=8000/tcp --permanent
sudo firewall-cmd --reload
VII. Use Nginx as a Reverse Proxy (Production Recommended)¶
Directly exposing Uvicorn is insecure and can’t handle static resources. Use Nginx as a reverse proxy:
1. Install Nginx¶
# Ubuntu
sudo apt install nginx
# CentOS
sudo yum install nginx
2. Configure Nginx Proxy¶
sudo nano /etc/nginx/sites-available/fastapi_demo
Add:
server {
listen 80;
server_name 120.xx.xx.xx; # Replace with your IP/domain
location / {
proxy_pass http://127.0.0.1:8000; # Forward to Uvicorn
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3. Enable Nginx Configuration¶
sudo ln -s /etc/nginx/sites-available/fastapi_demo /etc/nginx/sites-enabled/
sudo nginx -t # Test config for errors
sudo systemctl restart nginx # Restart Nginx
VIII. Configure HTTPS (Optional but Recommended)¶
Use Let’s Encrypt for free SSL certificates:
1. Install Certbot:
sudo apt install certbot python3-certbot-nginx # Ubuntu
# For CentOS, use snap (simpler to use Ubuntu/CentOS 8+)
- Obtain and configure SSL:
sudo certbot --nginx -d 120.xx.xx.xx # Replace with your domain/IP
Certbot auto-modifies Nginx config for HTTPS.
IX. Post-Deployment Maintenance¶
1. View Logs¶
- Uvicorn logs:
journalctl -u fastapi -f(real-time with-f) - Nginx logs:
tail -f /var/log/nginx/access.log(access) anderror.log(errors)
2. Restart Services¶
# Restart Uvicorn
sudo systemctl restart fastapi
# Restart Nginx
sudo systemctl restart nginx
3. Update Code¶
After local changes, re-upload and restart:
# Upload updated code
scp /local/path/main.py ubuntu@120.xx.xx.xx:/var/www/fastapi_demo/
# Restart service
sudo systemctl restart fastapi
X. Advanced: Docker Containerization (Optional)¶
For complex projects, Docker simplifies deployment:
1. Create Dockerfile locally:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
- Build and Run on Server:
docker build -t fastapi_demo .
docker run -d -p 8000:8000 fastapi_demo
XI. Summary¶
The core deployment process is: Local Debugging → Server Setup → Code Upload → Service Startup → Reverse Proxy → Security Hardening. This guide covers basic deployment; extend with databases, containerization, etc., as needed.
For issues, refer to official docs or search keywords like “Ubuntu install Python3” or “Uvicorn production config”. Happy deploying!