Deploying Node apps to production
Code that works on your laptop is half the job. In production it must stay up, log what happens, shut down cleanly, scale under load and stay secure. This lesson is a checklist of what changes when real users arrive, ending with a capstone project.
Configuration for production
NODE_ENV=production PORT=8080 DATABASE_URL=… JWT_SECRET=… node src/server.jsNODE_ENV=productionmakes Express and many libraries skip development-only work (detailed error pages, extra checks). Never show stack traces to users in production.- Read every setting from environment variables, and validate them at startup (see the validation lesson).
- Install only what's needed:
npm ci --omit=devinstalls exactly what the lock file says, without dev tools.
Logging
console.log is fine for learning. In production you want structured logs (one JSON object per line) that log platforms (Grafana Loki, Datadog, CloudWatch, Elastic) can search and filter:
Real projects use pino (very fast) or winston, which add levels, timestamps and request IDs. Log events and IDs, never passwords, tokens or full card numbers.
Health checks
Load balancers and container platforms check a URL to decide whether your app is alive and ready for traffic:
Graceful shutdown
When you deploy a new version, the platform sends your process a SIGTERM signal. A well-behaved server stops accepting new requests, lets in-flight requests finish, closes database connections and then exits:
const server = app.listen(port);
function shutdown(signal) {
console.log(`${signal} received, shutting down…`);
server.close(async () => { // stop accepting connections, wait for open requests
await db.close();
process.exit(0);
});
setTimeout(() => process.exit(1), 10_000).unref(); // force exit if it takes too long
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT')); // Ctrl+CCrashes
An uncaught exception leaves the process in an unknown state. Log it and exit, letting the process manager restart a clean process. Don't try to keep running:
process.on('uncaughtException', (err) => {
logger.error('Uncaught exception', { error: err.message, stack: err.stack });
process.exit(1);
});Keeping it running
Something must start your app, restart it when it crashes and start it on boot:
| Option | When |
|---|---|
| Docker container on a platform (Fly.io, Render, Railway, Google Cloud Run, AWS ECS, Kubernetes) | The most common choice today |
PM2 (pm2 start server.js -i max) |
A plain Linux server (VM) |
| systemd service | A plain Linux server, no extra tools |
| Serverless (AWS Lambda, Vercel/Netlify functions) | Spiky traffic, small handlers |
A production Dockerfile
FROM node:26-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
EXPOSE 8080
CMD ["node", "src/server.js"]Copying package*.json and running npm ci before copying the source lets Docker cache the dependency layer, so rebuilding after a code change takes seconds. Running as the node user instead of root limits the damage if the app is compromised. (The Docker track covers images and containers in depth.)
Performance and scaling
- Node uses one CPU core per process. To use a whole machine, run several processes behind a load balancer: several containers,
pm2 -i max, ornode:cluster. - Keep the app stateless: store sessions, uploads and caches in shared services (Redis, a database, object storage), not in memory or local files, so any process can handle any request.
- Cache expensive results (Redis), add database indexes, and paginate large lists.
- Compress responses (most load balancers and CDNs do this for you).
- Measure before optimising:
node --cpu-prof,clinic.js, and application monitoring (OpenTelemetry) show where time actually goes.
Security checklist
helmet()for security headers; strictcorsorigins.- Validate every input (Zod); parameterised SQL queries only.
- Rate-limit authentication and expensive routes.
npm auditand automated dependency updates (Dependabot, Renovate).- Secrets only in environment variables or a secrets manager; never in Git.
- Run as a non-root user; keep Node on a supported LTS version.
- Serve everything over HTTPS (usually terminated at the load balancer or CDN).
🎓 Node.js track complete!
You've learned how Node runs JavaScript, modules and npm, files, async code and the event loop, events and streams, HTTP servers, Express routing and middleware, databases, validation and configuration, authentication with JWT, testing, and running Node in production.
Capstone project: an online bookshop API
Build a production-style REST API with Express:
- Structure:
app.js,server.js,routes/,middleware/,services/,db.js, plus.env.example. - Data: SQLite (
node:sqlite) or PostgreSQL with tables forusers,books,ordersandorder_items, created by a setup script. - Auth: register and log in with bcrypt + JWT;
customerandadminroles. - Endpoints: public
GET /books(search, filter by author, pagination), admin-onlyPOST/PATCH/DELETE /books, customerPOST /orders(in a transaction that checks and reduces stock) andGET /orders/me. - Quality: Zod validation on every body and query, a central error handler, structured logging with request IDs,
/healthz. - Tests:
node --testintegration tests for the happy paths and for 400, 401, 403 and 404 cases. - Ship it: a Dockerfile, graceful shutdown, and a GitHub Actions workflow that runs the tests on every push.
1.What should a server do when it receives SIGTERM?
2.How do you use all 8 CPU cores of a server with Node?
3.Why run npm ci --omit=dev in production images?