Blueprints · Node.js & Next.js
Production
25 min · Node.js / PM2 / Nginx
Node.js / Express production setup with PM2
Runs the app as a dedicated user under PM2, rotates its logs, and proxies WebSocket upgrades to 127.0.0.1:3000.
Live config
Baked-in protections
- The Node process is not root
- PM2 waits for process.send ready before a reload
- pm2-logrotate caps log size
- Nginx proxies Upgrade and Connection to localhost only
Step 1 · js
User and PM2 ecosystem
/var/www/node/ecosystem.config.js
The app must call process.send("ready") when wait_ready is true.
module.exports = {
apps: [
{
name: "app",
cwd: "/var/www/node",
script: "server.js",
exec_mode: "cluster",
instances: 2,
wait_ready: true,
listen_timeout: 10000,
kill_timeout: 5000,
env: {
NODE_ENV: "production",
PORT: "3000",
},
},
],
};
Step 2 · nginx
Nginx WebSocket proxy
/etc/nginx/sites-available/app.example.com.conf
The upstream is 127.0.0.1 only.
server {
listen 80;
server_name app.example.com;
server_tokens off;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Step 3 · bash
Install PM2 for the app user
/root/portgate-blueprints/pm2-enable.sh
pm2 startup is printed for the app user. Run the line it prints if you want reboot persistence.
#!/bin/sh
set -eu
id "nodeapp" >/dev/null 2>&1 || useradd --system --create-home --shell /usr/sbin/nologin "nodeapp"
install -d -m 755 -o "nodeapp" -g "nodeapp" "/var/www/node"
command -v node >/dev/null 2>&1 || { echo "Install Node.js before this step." >&2; exit 1; }
npm install -g pm2 pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
sudo -u "nodeapp" pm2 start "/var/www/node/ecosystem.config.js" || true
ln -sfn "/etc/nginx/sites-available/app.example.com.conf" /etc/nginx/sites-enabled/app.example.com.conf
nginx -t
systemctl reload nginx