Skip to content

Instantly share code, notes, and snippets.

@hoanganhcoder
Last active May 26, 2025 20:26
Show Gist options
  • Select an option

  • Save hoanganhcoder/8b7e5c2913d34f39e110e3374be69ecd to your computer and use it in GitHub Desktop.

Select an option

Save hoanganhcoder/8b7e5c2913d34f39e110e3374be69ecd to your computer and use it in GitHub Desktop.
Triển khai FastAPI + Gunicorn + Nginx (Ubuntu 20.04)

Triển khai FastAPI + Gunicorn + Nginx (Ubuntu 20.04)

1. Chuẩn bị môi trường

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] gunicorn

Tạo file app.py:

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

Test:

uvicorn app:app --reload

2. Cấu hình Gunicorn (UvicornWorker)

Tạ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.target

Khởi động:

sudo systemctl daemon-reload
sudo systemctl enable fastapi_app
sudo systemctl start fastapi_app

3. Reverse proxy với Nginx

Tạ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 nginx

4. SSL với Let’s Encrypt

Lưu ý: domain phải trỏ DNS về VPS(hosting)

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

Kiểm tra tự động gia hạn:

sudo certbot renew --dry-run

Done 🎉

App FastAPI chạy qua Gunicorn + Nginx + SSL. Sẵn sàng production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment