Deploying Express
Your API works on localhost. Deploying means running it somewhere reliable: started automatically, restarted on crashes, reachable over HTTPS, configured through the environment, and shut down gracefully during updates. This lesson covers the pieces every deployment needs and a production-ready Dockerfile.
Production checklist
| Item | How |
|---|---|
NODE_ENV=production |
set in the environment |
| install only runtime deps | npm ci --omit=dev |
| config from env, fail fast if missing | a config.js module (see Configuration lesson) |
listen on process.env.PORT and 0.0.0.0 |
platforms assign the port |
| HTTPS | terminate TLS at a reverse proxy / load balancer |
app.set('trust proxy', 1) |
correct req.ip and req.protocol behind that proxy |
| security headers | helmet middleware |
| health check endpoint | GET /health → 200 |
graceful shutdown on SIGTERM |
stop accepting, finish in-flight requests, close DB |
| logs to stdout as JSON | the platform collects them |
Health checks
Load balancers and orchestrators poll an endpoint to decide whether to send traffic to an instance. Keep a cheap liveness check (is the process up?) separate from a readiness check (can it serve traffic — is the database reachable?):
const express = require('express');
let dbConnected = false;
const app = express();
app.get('/health/live', (req, res) => res.json({ status: 'ok' }));
app.get('/health/ready', (req, res) => {
if (!dbConnected) return res.status(503).json({ status: 'starting', db: 'down' });
res.json({ status: 'ok', db: 'up' });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const check = async (p) => {
const res = await fetch(base + p);
console.log(p.padEnd(13), res.status, await res.text());
};
await check('/health/live');
await check('/health/ready');
dbConnected = true; // pretend the database connection finished
await check('/health/ready');
server.close();
});/health/live 200 {"status":"ok"}
/health/ready 503 {"status":"starting","db":"down"}
/health/ready 200 {"status":"ok","db":"up"}
Graceful shutdown
During a deploy, the platform sends SIGTERM, waits a few seconds, then kills the process. If you exit immediately, requests in flight are cut off. Instead, stop accepting new connections and let running requests finish. server.close(callback) does exactly that:
const express = require('express');
const app = express();
app.get('/slow', async (req, res) => {
await new Promise((r) => setTimeout(r, 100)); // simulate work
res.json({ done: true });
});
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/slow`;
const inFlight = fetch(url).then(async (res) => console.log('in-flight request:', res.status, await res.text()));
await new Promise((r) => setTimeout(r, 20)); // the request is now being processed
console.log('SIGTERM received, closing server');
const closed = new Promise((resolve) => server.close(resolve));
await inFlight;
await closed;
console.log('server closed, exiting cleanly');
const late = await fetch(url).catch((err) => err.cause?.code ?? err.message);
console.log('new request after close:', late);
});SIGTERM received, closing server
in-flight request: 200 {"done":true}
server closed, exiting cleanly
new request after close: ECONNREFUSED
In a real server.js it looks like this:
process.on('SIGTERM', () => {
logger.info('shutting down');
server.close(async () => {
await db.end(); // close pools and other resources
process.exit(0);
});
setTimeout(() => process.exit(1), 10_000).unref(); // force-exit if something hangs
});A production Dockerfile
A multi-stage build installs dependencies once, copies only what's needed and runs as a non-root user:
# syntax=docker/dockerfile:1
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY src ./src
USER node
EXPOSE 3000
HEALTHCHECK CMD wget -qO- http://localhost:3000/health/live || exit 1
CMD ["node", "src/server.js"]Add a .dockerignore so local junk never enters the image:
node_modules
.env
.git
test
*.logdocker build -t bookmarks-api .
docker run -d -p 3000:3000 -e DATABASE_URL=postgres://… -e JWT_SECRET=… --name api bookmarks-api
curl http://localhost:3000/health/live[+] Building 14.2s (12/12) FINISHED
=> => naming to docker.io/library/bookmarks-api
3f9c1e7a2b6d
{"status":"ok"}
Tip: Use
CMD ["node", …]rather thanCMD npm start. Withnpmin between,SIGTERMmay not reach your Node process, and graceful shutdown silently stops working.
Where to run it
| Option | You manage | Good for |
|---|---|---|
| PaaS (Render, Railway, Fly.io, Heroku) | almost nothing — push code or an image | small teams, side projects |
| Containers (AWS ECS/Fargate, Google Cloud Run, Azure Container Apps) | the image and scaling rules | most production APIs |
| Kubernetes | cluster, manifests, ingress | many services, platform teams |
| A VM with PM2 or systemd + nginx | the whole server | full control, legacy setups |
Security middleware: helmet
helmet sets a batch of protective response headers (Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, …) in one line:
const helmet = require('helmet');
app.use(helmet());Test yourself
What does server.close() do?
- Kills all connections immediately
- Stops accepting new connections and calls back once existing requests finish
- Restarts the server
- Deletes the Express app
Which signal do platforms like Docker and Kubernetes send to stop a container gracefully?
- SIGKILL
- SIGTERM
- SIGHUP
- SIGINT only
Why should a readiness check return 503 while the database is unavailable?
- To crash the container
- So the load balancer stops routing traffic to this instance until it can serve requests
- To trigger a deploy
- 503 means success