Node server deployment
Hero subtitle
Beyond npm start
Category: devops
Your Express app works on localhost. Here's how to make it work everywhere else without the midnight panic calls.
Every Node tutorial ends with npm start. That's where your real problems begin.
We've kept Node servers running for years without 3am panic calls. Here's how.
PM2: your process manager that actually manages
Forget nodemon in production. PM2 is what you want:
npm install -g pm2
pm2 start app.js --name "my-api"
pm2 startup
pm2 save
But the real power is in ecosystem.config.js:
module.exports = {
apps: [{
name: 'my-api',
script: './app.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true,
max_restarts: 10,
min_uptime: '10s'
}]
}
Clustering: free performance
Node is single-threaded, but your server doesn't have to be. PM2's cluster mode spawns one process per CPU core.
instances: 'max' uses all available cores. Start with that.
Gotcha: Shared state breaks in cluster mode. Use Redis for sessions, not memory.
Environment variables: do it right
Create .env.production:
NODE_ENV=production
PORT=3000
DB_URL=postgresql://...
JWT_SECRET=your-super-secret-key
REDIS_URL=redis://...
Load them with dotenv, but only in development:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
In production, set env vars in your deployment system, not .env files.
Health checks that matter
Every production server needs health endpoints:
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memory: process.memoryUsage()
})
})
app.get('/readiness', async (req, res) => {
try {
// Check database connection
await db.raw('SELECT 1')
res.json({ status: 'ready' })
} catch (error) {
res.status(503).json({ status: 'not ready' })
}
})
Logging: your future self will thank you
console.log is not logging. Use Winston or Pino:
const winston = require('winston')
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
})
// In development, also log to console
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}))
}
Memory leaks, the silent killer
Node servers crash from memory leaks, not traffic spikes. Monitor memory usage:
// Add to your health endpoint
app.get('/health', (req, res) => {
const usage = process.memoryUsage()
const mb = (bytes) => Math.round(bytes / 1024 / 1024)
res.json({
status: 'OK',
memory: {
rss: `${mb(usage.rss)} MB`,
heapUsed: `${mb(usage.heapUsed)} MB`,
heapTotal: `${mb(usage.heapTotal)} MB`
}
})
})
The Docker way
If you're containerizing (and you should be):
FROM node:18-alpine
WORKDIR /app
# Copy package files first (better caching)
COPY package*.json ./
RUN npm ci --only=production
# Then copy app code
COPY . .
# Don't run as root
USER node
CMD ["npm", "start"]
What breaks in production (and how to fix It)
From our war stories:
File uploads fill disk space. Set size limits and clean up temp files.
Database connections timeout. Use connection pooling and handle reconnection.
CORS breaks your frontend. Configure it properly from the start.
SSL certificates expire. Use Let's Encrypt with auto-renewal.
Dependencies have security issues. Run
npm auditregularly.
Deploy Node servers that stay running. Your sleep schedule depends on it.