#5 of 11Deploying Node.js & Next.js with PM2 Process Manager
IntermediateDeployment⏱️ 11 min

Deploying Node.js & Next.js with PM2 Process Manager

Node.js နှင့် Next.js အက်ပ်များကို PM2 ဖြင့် Production တင်နည်း

Manage Node.js, Express, and Next.js applications in production with PM2. Configure cluster mode, auto-restart on crashes, and system reboots.

Node.js အက်ပ်များ crash ဖြစ်သွားပါက အလိုအလျောက် ပြန်ပွင့်စေမည့် PM2၊ CPU cores အားလုံးကို အသုံးချမည့် Cluster Mode နှင့် Ecosystem file ရေးသားပုံ။

1. Why use PM2 in Production? (PM2 ကို ဘာကြောင့် သုံးရသလဲ)

Node command တိုက်ရိုက် run ခြင်းနှင့် PM2 ကွာခြားချက်

စမ်းသပ်ချိန်တွင် `node server.js` ဟု terminal တွင် run လေ့ရှိသော်လည်း terminal window ပိတ်လိုက်ပါက သို့မဟုတ် uncaught error ကြောင့် crash ဖြစ်သွားပါက ဝဘ်ဆိုက် ရပ်တန့်သွားမည် ဖြစ်ပါသည်။

PM2 (Process Manager 2) သည် background daemon အဖြစ် အမြဲတမ်း run ပေးထားပြီး error ဖြစ်ပါက မီလီစက္ကန့်ပိုင်းအတွင်း အလိုအလျောက် restart ပြုလုပ်ပေးကာ server ပြန်ပွင့်ချိန်တွင်လည်း auto-start ဖြစ်စေပါသည်။

2. Essential PM2 Commands & Ecosystem Config

လက်တွေ့သုံး PM2 Command များနှင့် Ecosystem ဖိုင်

Project ၏ root folder တွင် `ecosystem.config.js` ဖိုင်ကို ရေးသားထားခြင်းဖြင့် Environment variables များ (DB URLs, Ports, Secret Keys) ကို စနစ်တကျ ထိန်းချုပ်နိုင်ပါသည်။

ecosystem.config.cjs
javascript
1 $ module.exports = {
2 $ apps: [
3 $ {
4 $ name: 'my-node-app',
5 $ script: './dist/index.js',
6 $ instances: 'max', // Cluster mode: use all available CPU cores
7 $ exec_mode: 'cluster',
8 $ autorestart: true,
9 $ watch: false,
10 $ max_memory_restart: '500M',
11 $ env_production: {
12 $ NODE_ENV: 'production',
13 $ PORT: 3000
14 $ }
15 $ }
16 $ ]
17 $ };
💡Command ရှင်းလင်းချက် (ဖတ်ရှုရန် နှိပ်ပါ)

Cluster mode ဖြင့် CPU core အားလုံးပေါ်တွင် load balancing ပြုလုပ်ပေးပြီး memory 500MB ကျော်ပါက memory leak မဖြစ်အောင် အလိုအလျောက် recycle restart ပြုလုပ်ပေးမည် ဖြစ်ပါသည်။

PM2 Terminal Commands
bash
1 $ # Install PM2 globally
2 $ sudo npm install -g pm2
3 $
4 $ # Start app using ecosystem config
5 $ pm2 start ecosystem.config.cjs --env production
6 $
7 $ # View real-time logs and monitoring
8 $ pm2 logs
9 $ pm2 monit
10 $
11 $ # Save PM2 state to resurrect on server reboot
12 $ pm2 save
13 $ pm2 startup
💡Command ရှင်းလင်းချက် (ဖတ်ရှုရန် နှိပ်ပါ)

pm2 startup command သည် Linux systemd service ထဲသို့ PM2 ကို ထည့်သွင်းပေးပြီး ဆာဗာ reboot ဖြစ်သွားသည့်တိုင် အက်ပ်များကို အလိုအလျောက် ပြန်လည် run ပေးပါသည်။

Knowledge Check

Which PM2 command saves the list of running processes so they automatically restore after a VPS reboot?

VPS Server ပြန်လည် reboot ဖြစ်သွားသည့်အခါ လက်ရှိ run နေသော PM2 app များကို မပျောက်ပျက်စေဘဲ အလိုအလျောက် ပြန်ပွင့်စေရန် မည်သည့် command ဖြင့် မှတ်သားရသလဲ?