Cài đặt pm2 chạy dự án nextjs
Để cài đặt và dùng PM2 để chạy dự án Next.js (production build) trên server (Ubuntu), bạn có thể làm theo các bước chi tiết dưới đây:
✅ 1. Build dự án Next.js
Trước hết, build dự án:
bashCopyEditnpm install # hoặc yarn
npm run build
Dự án phải được build sẵn để chạy ở production.
✅ 2. Cài PM2 toàn cục
bashCopyEditnpm install -g pm2
✅ 3. Chạy dự án Next.js bằng PM2
Cách 1: Chạy trực tiếp next start
next start
Nếu bạn dùng App Router hoặc Pages Router đều được, miễn là đã build:
bashCopyEditpm2 start npm --name "nextjs-app" -- run start
--name
là tên bạn muốn đặt cho process trong PM2.
✅ 4. Lưu trạng thái và khởi động cùng hệ thống (tuỳ chọn)
Để đảm bảo app tự khởi động khi server reboot:
bashCopyEditpm2 save
pm2 startup
Lệnh pm2 startup
sẽ trả về một dòng, bạn cần copy-paste và chạy nó. Ví dụ:
bashCopyEditsudo env PATH=$PATH:/home/ubuntu/.nvm/versions/node/v18.18.0/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu
✅ 5. Quản lý app với PM2
Xem danh sách app:
bashCopyEditpm2 list
Xem log:
bashCopyEditpm2 logs
Dừng app:
bashCopyEditpm2 stop nextjs-app
Restart:
bashCopyEditpm2 restart nextjs-app
Xoá app:
bashCopyEditpm2 delete nextjs-app
✅ 6. (Tuỳ chọn) File cấu hình ecosystem.config.js
ecosystem.config.js
Nếu bạn muốn cấu hình dễ hơn:
bashCopyEditpm2 init
Sau đó sửa file ecosystem.config.js
thành:
jsCopyEditmodule.exports = {
apps: [
{
name: "nextjs-app",
script: "npm",
args: "start",
env: {
NODE_ENV: "production",
},
},
],
};
Chạy app bằng file config:
bashCopyEditpm2 start ecosystem.config.js
Nếu bạn đang dùng Next.js với App Router, cấu trúc app/
, hoặc có SSR thì next start
vẫn hoạt động bình thường sau khi build
.
Cần mình giúp tự động tạo ecosystem.config.js
hoặc cấu hình log/nginx nữa không?
Last updated
Was this helpful?