1. Mô hình triển khai chuẩn cho ứng dụng Node.js sản xuất (Production)
Trong môi trường Production, ứng dụng Node.js không nên chạy trực tiếp với lệnh node app.js vì nếu máy chủ khởi động lại hoặc code gặp lỗi unhandled exception, tiến trình sẽ bị chết. Mô hình chuẩn mực gồm:
- Node.js Engine: Môi trường thực thi JavaScript phía máy chủ.
- PM2 Process Manager: Quản lý tiến trình chạy ngầm, tự động khởi động lại khi crash hoặc khi reboot VPS, hỗ trợ cân bằng tải Cluster Mode.
- Nginx Reverse Proxy: Đứng ở cổng 80/443 tiếp nhận mọi yêu cầu từ người dùng, nén dữ liệu Gzip, cache file tĩnh (CSS/JS/Ảnh) và chuyển tiếp truy vấn vào cổng nội bộ của Node.js (ví dụ cổng 5050).
2. Các bước cài đặt chi tiết trên Ubuntu 22.04 / 24.04 LTS
Bước 1: Cài đặt Node.js LTS qua NodeSource
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v && npm -v
Bước 2: Cài đặt và khởi chạy ứng dụng với PM2
sudo npm install -g pm2
cd /var/www/my-website
npm install --production
pm2 start app.js --name "my-app"
pm2 save
pm2 startup
Bước 3: Cấu hình Nginx làm Reverse Proxy
server {
listen 80;
server_name tenmiencuaban.vn www.tenmiencuaban.vn;
location / {
proxy_pass http://127.0.0.1:5050;
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;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Sau khi lưu file, kiểm tra cú pháp bằng sudo nginx -t và khởi động lại dịch vụ bằng sudo systemctl reload nginx.