Khi đưa ứng dụng web vào môi trường sản xuất (Production), việc giữ cho tiến trình luôn chạy liên tục, tự động restart khi gặp lỗi crash và tự khởi động lại khi reboot VPS là điều tối quan trọng.
1. Triển khai ứng dụng Node.js với PM2
Cài đặt PM2 toàn cục thông qua npm:
sudo npm install -g pm2
Khởi chạy ứng dụng với chế độ Cluster mode tận dụng toàn bộ số nhân CPU:
pm2 start server.js -i max --name "my-app"
Lưu trạng thái và đăng ký Systemd để tự động bật khi reboot VPS:
pm2 startup systemd
# Thực thi dòng lệnh mà PM2 gợi ý, sau đó:
pm2 save
2. Triển khai Python FastAPI với Gunicorn/Uvicorn & Systemd
Tạo service systemd tại /etc/systemd/system/fastapi.service:
[Unit]
Description=FastAPI Production Service
After=network.target
[Service]
User=root
WorkingDirectory=/var/www/fastapi-app
ExecStart=/var/www/fastapi-app/venv/bin/gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000
Restart=always
[Install]
WantedBy=multi-user.target
Kích hoạt và chạy service:
sudo systemctl daemon-reload
sudo systemctl enable --now fastapi
sudo systemctl status fastapi