Node.js Deployment & PM2
From npm start to a production-grade Node.js process that never sleeps.
What you'll learn in this chapter
- Why running
node server.jsis never enough for production - How PM2 acts as your automated process guardian
- Installing and managing multiple Node.js versions with nvm
- Cluster mode β using every CPU core your server has
- The
ecosystem.config.jsfile for repeatable deployments - Zero-downtime deployments with
pm2 reload - Nginx as a reverse proxy with free SSL from Certbot
- Dockerising a Node.js app with
pm2-runtime - The essential
/healthendpoint every production app must have
The Night Watchman Analogy
Picture a small hotel. At night, they hire a security guard to watch the lobby. The guard's one job is to be present β if anything goes wrong, they handle it. Now imagine the hotel owner saves money by just leaving a note on the door that says "the lobby is watched." There is no actual guard. If a thief walks in, nothing happens.
Running node server.js in a terminal is exactly like that note. Your Node.js
process starts, it serves requests β and if it crashes, it is gone. Completely gone. No
automatic restart. No notification. Users start getting connection errors and you are asleep.
Worse: if the server reboots (for a kernel update, a power flicker, anything), your process
is never started again. The "lobby" is permanently unwatched.
PM2 (Process Manager 2) is your automated night watchman service. Not a single guard, but an entire security company running on your server. PM2 starts your Node.js app, watches it, and restarts it within milliseconds if it crashes. When the server reboots, PM2 comes back up and starts all registered processes automatically. It also runs multiple copies of your app in cluster mode β one process per CPU core β so a 16-core server is actually running 16 simultaneous Node.js instances all sharing the same port through the operating system's load-balancer.
node server.js = a sticky note on the lobby door. If anything goes wrong,
nothing happens.
pm2 start server.js = a 24/7 professional security service. Crash? Restart
in 200ms. Server reboot? Back up in 30 seconds. CPU overloaded? Spread the load across
every core. Logs? All captured and rotating automatically.
The Node.js Production Stack
Before diving into commands, let us understand the full picture. A production Node.js deployment is not just one process β it is a layered system where each layer has a specific job:
Internet traffic
β
βΌ
βββββββββββββββββββββββββββββββββββ
β Nginx (port 80 / 443) β β SSL termination, static files,
β Reverse Proxy β rate limiting, compression
βββββββββββββββββ¬ββββββββββββββββββ
β proxy_pass β localhost:3000
βΌ
βββββββββββββββββββββββββββββββββββ
β PM2 Cluster β β Process manager: restart on crash,
β Worker 0 Worker 1 Worker 2 β spread load across CPU cores
β Worker 3 Worker 4 Worker 5 β
βββββββββββββββββ¬ββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββ
β Node.js Runtime (v20 LTS) β β Your application code
β Your Express / Fastify / NestJSβ
βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββ
β Environment Variables β β Secrets, config (never hardcoded)
β /etc/myapp.env β
βββββββββββββββββββββββββββββββββββ
Each layer has a clear responsibility:
- Node.js runtime β the JavaScript engine (V8) that executes your code
- PM2 β keeps the process alive, enables cluster mode, handles logs
- Nginx β faces the internet, handles SSL, forwards to PM2-managed processes
- Environment variables β configuration that changes per environment, never hardcoded
- Health check endpoint β
/healthfor load balancers and monitoring tools
Setting Up Node.js on a Linux Server
The first decision is how to install Node.js. Most Linux package managers have Node.js, but they are often several major versions behind. The correct approach for production servers is nvm (Node Version Manager) β it lets you install any version, switch between them, and pin a default. This is how professional teams manage Node.js versions across dozens of servers and developers.
# Install nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# Reload your shell profile so nvm is available
source ~/.bashrc
# Install Node.js 20 (current LTS as of 2024)
nvm install 20
nvm use 20
# Set as the default version for new shells
nvm alias default 20
# Verify installation
node --version # v20.x.x
npm --version # 10.x.x
# List all installed Node versions
nvm ls
# Install a second version alongside the first
nvm install 18
nvm use 18 # switch to v18 in this shell
nvm use default # switch back to the default (v20)
Always use an LTS (Long-Term Support) version in production. LTS releases receive security patches for 30 months. "Current" releases are for trying new features and only receive support for 6 months. As of 2025, Node.js 20 and 22 are both LTS. Node.js 18 is in maintenance mode (still patched, but approaching end-of-life).
PM2 β Your Process Manager
PM2 is a production process manager for Node.js applications. It is a single npm package that
transforms a fragile node server.js command into a managed, self-healing,
multi-process service. Install it globally so it is available as a system-level command:
# Install PM2 globally
npm install -g pm2
# Start your app with a name (the name is used in all subsequent commands)
pm2 start server.js --name "my-api"
# Start with an explicit interpreter path (safest when using nvm)
pm2 start server.js --name "my-api" --interpreter $(which node)
# Cluster mode β use ALL available CPU cores (max = number of cores)
pm2 start server.js --name "my-api" -i max
# Or specify an exact number of workers
pm2 start server.js --name "my-api" -i 4
## VIEWING PROCESSES AND LOGS ββββββββββββββββββββββββββββββββββββββ
# List all running PM2 processes (shows PID, status, CPU, memory)
pm2 list
# Stream live logs for a specific app
pm2 logs my-api
# Show the last 200 lines then continue streaming
pm2 logs my-api --lines 200
# Monitor CPU and memory usage in a real-time dashboard
pm2 monit
# Get detailed information about a single process
pm2 show my-api
## CONTROLLING PROCESSES ββββββββββββββββββββββββββββββββββββββββββ
# Restart (kills the process and starts fresh β brief downtime)
pm2 restart my-api
# Reload (graceful β zero downtime for cluster mode)
pm2 reload my-api
# Stop (process stays in the PM2 list but does not run)
pm2 stop my-api
# Remove from PM2's list entirely
pm2 delete my-api
# Restart all processes at once
pm2 restart all
## SURVIVING REBOOTS ββββββββββββββββββββββββββββββββββββββββββββββ
# Save current process list to disk
pm2 save
# Generate and install a startup script for your OS
# (systemd on Ubuntu/Debian, launchd on macOS, etc.)
pm2 startup
# PM2 will print a command β run exactly that command. Example:
sudo env PATH=$PATH:/home/ubuntu/.nvm/versions/node/v20.0.0/bin \
/home/ubuntu/.nvm/versions/node/v20.0.0/lib/node_modules/pm2/bin/pm2 \
startup systemd -u ubuntu --hp /home/ubuntu
Every time you add, remove, or change a process, run pm2 save to update
the saved process list. Otherwise, a server reboot will restore the old list β not the
current one. Think of it like "ctrl+S" for your PM2 configuration.
The ecosystem.config.js β Your PM2 Configuration File
Typing long PM2 commands with many flags is error-prone and hard to version-control.
The professional solution is an ecosystem.config.js file committed to your
repository alongside your code. This file defines every app, its configuration, its
environment variables, and its logging setup β all in one place.
// ecosystem.config.js
module.exports = {
apps: [
{
name: "my-api",
script: "dist/server.js", // compiled TypeScript output
instances: "max", // one per CPU core
exec_mode: "cluster", // enable cluster mode
watch: false, // never watch files in production
max_memory_restart: "500M", // restart if RAM exceeds 500MB
env: {
NODE_ENV: "production",
PORT: 3000,
},
// Logging
error_file: "/var/log/myapp/error.log",
out_file: "/var/log/myapp/out.log",
merge_logs: true, // combine logs from all cluster workers
log_date_format: "YYYY-MM-DD HH:mm:ss",
// Advanced
wait_ready: true, // wait for app to send 'ready' signal
listen_timeout: 10000, // ms to wait for ready signal
kill_timeout: 5000, // ms to wait before force-killing
}
]
};
Once you have an ecosystem file, all PM2 commands accept it instead of a process name:
# Start using the config file
pm2 start ecosystem.config.js
# Restart using the config file (picks up any config changes)
pm2 restart ecosystem.config.js
# Reload with zero downtime
pm2 reload ecosystem.config.js
# Save and enable startup
pm2 save
PM2 has two execution modes. Fork mode (default) starts a single Node.js process β one CPU core, simple, no shared state issues. Cluster mode uses Node.js's built-in cluster module to spawn multiple worker processes, all listening on the same port. The operating system distributes incoming connections across workers using round-robin. A server with 8 CPU cores running cluster mode effectively has 8 times the throughput capacity. Use cluster mode for HTTP servers; use fork mode for background workers or scripts that shouldn't be load-balanced.
Zero-Downtime Deployments with PM2
One of the most powerful features of PM2 cluster mode is zero-downtime deployment. When you
run pm2 reload, PM2 restarts workers one at a time β spinning up a new worker
and only then killing the old one. While the new worker is starting, the old worker is still
serving traffic. Users never see a gap in service.
Here is a complete deployment script that you would run on your server (or trigger from a CI/CD pipeline) to ship new code with no downtime:
#!/bin/bash
# deploy.sh β pull, build, and reload with zero downtime
set -e # exit immediately if any command fails
APP_DIR="/var/www/my-api"
cd $APP_DIR
# 1. Pull the latest code from Git
git pull origin main
# 2. Install any new dependencies (ci = reproducible, uses package-lock.json)
npm ci --only=production
# 3. Build TypeScript if applicable
npm run build
# 4. Reload all workers gracefully β zero downtime
pm2 reload ecosystem.config.js
# 5. Save updated process list
pm2 save
echo "Deployment complete at $(date)"
In production deployments, always use npm ci instead of
npm install. The ci command installs exact versions from
package-lock.json, deletes and recreates node_modules, and
fails if the lockfile is out of sync. This gives you reproducible builds β
the same packages every time, no surprise version bumps.
Nginx as Reverse Proxy
A fundamental rule of production Node.js: never expose your Node.js process directly on port 80 or 443. Always put Nginx (or another reverse proxy) in front. Why? Because Nginx handles SSL termination (decrypts HTTPS), serves static files at full disk speed without touching Node.js, applies rate limiting, manages keep-alive connections efficiently, and can route traffic to multiple backend services.
Here is a complete Nginx configuration for a Node.js API, with HTTP-to-HTTPS redirect and correct proxy headers:
# /etc/nginx/sites-available/my-api.conf
# Redirect all HTTP to HTTPS
server {
listen 80;
server_name api.myapp.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name api.myapp.com;
# SSL certificates (from Certbot / Let's Encrypt)
ssl_certificate /etc/letsencrypt/live/api.myapp.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.myapp.com/privkey.pem;
# Security headers
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
# Required for WebSocket support
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
# Forward correct client information
proxy_set_header Host $host;
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;
proxy_cache_bypass $http_upgrade;
}
}
Enable the site and get a free SSL certificate with Certbot:
# Install Nginx and Certbot
sudo apt update
sudo apt install nginx certbot python3-certbot-nginx
# Enable your site config
sudo ln -s /etc/nginx/sites-available/my-api.conf /etc/nginx/sites-enabled/
sudo nginx -t # test config syntax
sudo systemctl reload nginx
# Obtain and install a free Let's Encrypt SSL certificate
sudo certbot --nginx -d api.myapp.com
# Enable auto-renewal (runs twice daily to renew before expiry)
sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer
# Test that renewal works (dry run β no actual certificate changes)
sudo certbot renew --dry-run
Environment Variables β Never Hardcode Secrets
One of the most common and dangerous mistakes junior developers make is committing database passwords, API keys, and JWT secrets directly into code or config files in the repository. These end up in Git history forever, even if you delete the file later. The correct approach is environment variables β values that exist in the operating system environment and are injected into your process at startup.
# Create an environment file β outside the web root, restricted permissions
sudo mkdir -p /etc/myapp
sudo nano /etc/myapp/app.env
# Contents of /etc/myapp/app.env:
# NODE_ENV=production
# DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
# REDIS_URL=redis://localhost:6379
# JWT_SECRET=a-very-long-random-secret-string-here
# PORT=3000
# Restrict permissions so only root can read it
sudo chmod 600 /etc/myapp/app.env
sudo chown root:root /etc/myapp/app.env
# In ecosystem.config.js, reference it:
# env_file: "/etc/myapp/app.env"
In your Node.js application, access environment variables through process.env:
// config.js β centralise all env var access
const config = {
port: parseInt(process.env.PORT) || 3000,
databaseUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
nodeEnv: process.env.NODE_ENV || 'development',
isProduction: process.env.NODE_ENV === 'production',
};
// Validate required variables at startup
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required environment variable: ${key}`);
process.exit(1); // fail loudly at startup, not during a request
}
}
module.exports = config;
Node.js in Docker with PM2-Runtime
Many teams run Node.js inside Docker containers β either on bare metal with Docker Compose,
or inside Kubernetes. PM2 is still useful here because it provides cluster mode and graceful
reloading inside the container. The key difference is that inside Docker, you must use
pm2-runtime instead of pm2 start. Regular pm2 start
daemonizes (goes to the background), which causes the container to exit immediately.
pm2-runtime stays in the foreground as PID 1, which is what Docker expects.
# Dockerfile for a Node.js + PM2 production container
FROM node:20-alpine
# Install PM2 globally
RUN npm install -g pm2
WORKDIR /app
# Install dependencies first (Docker layer caching β only re-runs if package files change)
COPY package*.json ./
RUN npm ci --only=production
# Copy compiled code
COPY dist/ ./dist/
COPY ecosystem.config.js .
EXPOSE 3000
# pm2-runtime stays in the foreground (required for Docker PID 1)
CMD ["pm2-runtime", "ecosystem.config.js"]
node:20-alpine is a Node.js image based on Alpine Linux, a minimal Linux
distribution designed for containers. A regular node:20 image is around
1GB. The Alpine variant is around 130MB. For a production Docker image that gets built
and pushed dozens of times per day, this difference in size matters enormously β faster
pushes, faster pulls, less storage cost.
The Health Check Endpoint
Every production Node.js application should expose a /health endpoint. This
is a simple HTTP route that returns a JSON object with the application's status. Load
balancers use it to know whether to send traffic to a given instance. Kubernetes liveness
and readiness probes use it. Your monitoring system uses it to detect outages before users do.
A good health check does more than just return 200. It checks whether the database is reachable, whether background queues are running, and reports key process metrics:
// health.js β production-ready health check endpoint
const db = require('./db');
app.get('/health', async (req, res) => {
const checks = {};
let healthy = true;
// Check database connectivity
try {
await db.query('SELECT 1');
checks.database = 'ok';
} catch (err) {
checks.database = 'error';
healthy = false;
}
const status = {
status: healthy ? 'ok' : 'degraded',
uptime: process.uptime(), // seconds since process start
timestamp: new Date().toISOString(),
version: process.env.npm_package_version,
memory: process.memoryUsage(), // heap usage stats
checks,
};
res.status(healthy ? 200 : 503).json(status);
});
// Kubernetes readiness probe β only mark ready after DB is warm
app.get('/ready', (req, res) => {
res.json({ ready: true });
});
PM2 Log Management
Without log management, PM2 log files grow forever and eventually fill your disk. PM2 has
a module system that includes pm2-logrotate β it compresses and rotates log
files automatically:
# Install the log rotation module
pm2 install pm2-logrotate
# Configure rotation settings
pm2 set pm2-logrotate:max_size 100M # rotate when file hits 100MB
pm2 set pm2-logrotate:retain 10 # keep 10 rotated files
pm2 set pm2-logrotate:compress true # gzip rotated files
pm2 set pm2-logrotate:rotateInterval '0 0 * * *' # rotate daily at midnight
# Flush (clear) all current logs
pm2 flush
# Show PM2 module status
pm2 list
For serious production deployments, don't just store logs on disk β ship them to a centralised logging service. Tools like Datadog, Papertrail, or an ELK stack (Elasticsearch + Logstash + Kibana) let you search across all your server logs from a single dashboard, set up alerts, and retain logs for compliance. Chapter 19 covers this in depth.
Complete PM2 Cheat Sheet
PM2 QUICK REFERENCE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ STARTING & STOPPING pm2 start server.js --name "api" Start a process pm2 start server.js -i max Start in cluster mode pm2 start ecosystem.config.js Start from config file pm2 stop api Stop (keep in list) pm2 delete api Remove from PM2 list pm2 stop all Stop everything RESTARTING (with / without downtime) pm2 restart api Hard restart (brief downtime) pm2 reload api Graceful reload (zero downtime, cluster only) pm2 reload ecosystem.config.js Graceful reload from config MONITORING pm2 list Show all processes pm2 show api Detailed info about one process pm2 monit Live CPU/memory dashboard pm2 logs api Stream logs pm2 logs api --lines 200 Last 200 lines then stream PERSISTENCE pm2 save Save current process list pm2 startup Generate OS startup script pm2 resurrect Restore saved process list UPDATES npm install -g pm2@latest Update PM2 pm2 update Reload PM2 daemon with new version ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Chapter Summary
node server.jshas no crash recovery, no auto-restart, no multi-core support β it is not suitable for production.- PM2 is the industry-standard process manager: it restarts crashed processes, survives server reboots, and runs multiple workers in cluster mode.
- Use nvm to manage Node.js versions β it allows multiple versions to coexist and switch easily.
- The ecosystem.config.js file is the production-grade way to configure PM2 β version-controllable and repeatable.
- Cluster mode spawns one worker per CPU core, multiplying your throughput without any code changes.
pm2 reloadperforms a zero-downtime restart in cluster mode β workers are replaced one at a time.- Nginx should always sit in front of Node.js to handle SSL, static files, and act as a buffer against direct exposure to the internet.
- Use environment variables for all secrets and configuration β never hardcode them in source code.
- A
/healthendpoint is essential for load balancers, Kubernetes probes, and monitoring systems. - Use
pm2-runtime(notpm2 start) inside Docker containers to keep the process in the foreground.