sudo apt update && sudo apt install python3-venv nginx -y
mkdir ~/fastapi_app && cd ~/fastapi_app
python3 -m venv venv
source venv/bin/activate
pip install fastapi[all] gunicornTạo file app.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}Test:
uvicorn app:app --reloadTạo gunicorn_conf.py:
from multiprocessing import cpu_count
bind = "unix:/home/youruser/fastapi_app/gunicorn.sock"
workers = cpu_count() + 1
worker_class = "uvicorn.workers.UvicornWorker"
loglevel = "info"Tạo file dịch vụ systemd /etc/systemd/system/fastapi_app.service:
[Unit]
Description=FastAPI with Gunicorn
After=network.target
[Service]
User=youruser
Group=www-data
WorkingDirectory=/home/youruser/fastapi_app
Environment="PATH=/home/youruser/fastapi_app/venv/bin"
ExecStart=/home/youruser/fastapi_app/venv/bin/gunicorn -c gunicorn_conf.py app:app
[Install]
WantedBy=multi-user.targetKhởi động:
sudo systemctl daemon-reload
sudo systemctl enable fastapi_app
sudo systemctl start fastapi_appTạo file /etc/nginx/sites-available/fastapi_app:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://unix:/home/youruser/fastapi_app/gunicorn.sock;
include proxy_params;
}
}Kích hoạt và restart Nginx:
# Tạo symbolic link
sudo ln -s /etc/nginx/sites-available/fastapi_app /etc/nginx/sites-enabled
# Kiểm tra cấu hình Nginx
sudo nginx -t
# Khởi động lại Nginx để áp dụng thay đổi
sudo systemctl restart nginxLưu ý: domain phải trỏ DNS về VPS(hosting)
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.comKiểm tra tự động gia hạn:
sudo certbot renew --dry-runApp FastAPI chạy qua Gunicorn + Nginx + SSL. Sẵn sàng production.