Deployment Basics
npm scripts, health endpoints, process managers, and Docker basics for Node.js
Skills taught: node.npm-scripts, node.health-check, node.process-manager, node.docker-basics
Production-ready Node.js server
{
"name": "my-api",
"version": "1.0.0",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"build": "tsc --noEmit false --outDir dist",
"start:prod": "NODE_ENV=production node dist/index.js",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src --ext .ts,.js"
},
"engines": {
"node": ">=20.0.0",
"npm": ">=9.0.0"
}
}
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const startTime = Date.now();
app.use(express.json());
// ── Health check endpoint ──
// Load balancers, Docker, Kubernetes all use this
app.get('/health', (req, res) => {
res.json({
status: 'ok',
uptime: Math.floor((Date.now() - startTime) / 1000) + 's',
version: process.env.npm_package_version || '?',
env: process.env.NODE_ENV || 'development',
});
});
// ── Ready check (separate from health) ──
// Returns 503 until DB connection is established
let isReady = false;
app.get('/ready', (req, res) => {
if (!isReady) return res.status(503).json({ status: 'not ready' });
res.json({ status: 'ready' });
});
// Your routes here...
app.get('/', (req, res) => res.json({ message: 'Hello World' }));
// ── Start server ──
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT} (${process.env.NODE_ENV})`);
isReady = true; // Mark ready after startup
});
// ── Graceful shutdown ──
function gracefulShutdown(signal) {
console.log(`${signal} received. Shutting down gracefully...`);
server.close(() => {
console.log('HTTP server closed. Exiting.');
process.exit(0);
});
// Force shutdown after 10s if server doesn't close
setTimeout(() => process.exit(1), 10_000);
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
# Build stage — compile TypeScript (omit if using plain JS)
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Runtime stage — lean production image
FROM node:20-alpine AS runtime
WORKDIR /app
# Install only production dependencies
COPY package*.json ./
RUN npm ci --production && npm cache clean --force
# Copy compiled output from build stage
COPY --from=build /app/dist ./dist
# Non-root user for security
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s \
CMD wget -qO- http://localhost:3000/health || exit 1
# exec form — makes Node PID 1 so it receives signals
CMD ["node", "dist/index.js"]
Tip: Always listen on `process.env.PORT || 3000` — never hardcode a port. Every major hosting platform (Railway, Render, Heroku, Fly.io) sets PORT automatically. If you hardcode a port, your app won't start.
Frequently Asked Questions
What's the simplest way to deploy a Node.js app to production?
For the simplest path: use Railway or Render. Connect your GitHub repo, they detect Node.js automatically, run `npm start`, and set PORT for you. Add a /health endpoint and you're done. For more control, use a VPS (DigitalOcean Droplet, Linode) with PM2: `pm2 start npm -- start`, `pm2 startup` (survives reboot), `pm2 save`. For containerized deployments, build a Docker image and push to a registry, then run it anywhere (Railway, Fly.io, Google Cloud Run, AWS ECS).