TExcelTAD
Home › Node.js › Deploying & Docker

Deploying & Docker

Your app works on your laptop — now it has to run somewhere else, all day, for real users. Deploying a Node app means getting the code and its dependencies onto a server, starting it with the right configuration, and keeping it running. This lesson covers the checklist, process managers, and packaging your app with Docker.

Production checklist

Topic What to do
Node version use an LTS release (even numbers: 22, 24) and pin it ("engines" in package.json, .nvmrc, Docker tag)
Dependencies install exactly what the lockfile says: npm ci --omit=dev
Configuration read ports, URLs and secrets from environment variables
NODE_ENV set NODE_ENV=production (frameworks enable caching and hide stack traces)
Port & host listen on process.env.PORT, host 0.0.0.0 inside containers
Logging log to stdout/stderr; let the platform collect the logs
Shutdown handle SIGTERM and close the server gracefully
Health expose a cheap /health endpoint for load balancers

Listening on the right port

Hosting platforms (Render, Railway, Fly.io, Heroku, Cloud Run…) tell your app which port to use through PORT. Always fall back to a default for local development:

js
const port = Number(process.env.PORT ?? 3000);
server.listen(port, '0.0.0.0', () => console.log(`listening on ${port}`));

Graceful shutdown

When a platform deploys a new version or scales down, it sends your process the SIGTERM signal and kills it a few seconds later. A well-behaved server stops accepting new connections, finishes the requests in flight, closes database pools and then exits.

The example sends SIGTERM to itself to simulate the platform:

node · try it yourself
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.end(req.url === '/health' ? 'ok' : 'hello');
});

function shutdown(signal) {
  console.log(`received ${signal}, closing server…`);
  server.close(() => {
    console.log('all connections closed, exiting with code 0');
    process.exit(0);
  });
  // safety net: force exit if something hangs
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);   // Ctrl+C in a terminal

server.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/health`);
  console.log('health check:', res.status, await res.text());
  process.kill(process.pid, 'SIGTERM');
});
health check: 200 ok
received SIGTERM, closing server…
all connections closed, exiting with code 0

Note: If you start Node through npm start inside a container, npm may not forward signals to your app. In Docker, start node directly as the main process.

Keeping the process alive

A crash should not mean downtime. Something must restart the process:

Option Where
Container platforms / Kubernetes restart policy restarts crashed containers
systemd classic Linux servers (Restart=always)
PM2 (npm i -g pm2) VMs; also runs one process per CPU core in cluster mode
node --watch development only — restarts on file changes, not on crashes
bash · try it yourself
$ pm2 start server.js -i max --name shop
[PM2] Starting /srv/shop/server.js in cluster_mode (4 instances)
[PM2] Done.
[PM2] Starting /srv/shop/server.js in cluster_mode (4 instances)
[PM2] Done.

Docker

A container image bundles your code, its node_modules and the exact Node runtime into one artifact that runs the same on every machine. You describe the image in a Dockerfile:

dockerfile
# ---- build stage: install all deps and build (e.g. compile TypeScript) ----
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build --if-present

# ---- runtime stage: only what production needs ----
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

Why it is written this way:

  • COPY package*.json before COPY . — Docker caches each step. Dependencies are reinstalled only when the package files change, not on every code edit.
  • npm ci installs exactly the lockfile versions and fails if they don't match.
  • Two stages keep compilers and dev dependencies out of the final image, making it smaller and safer.
  • USER node — the official images include an unprivileged node user; don't run as root.
  • CMD ["node", …] in exec form, so Node receives SIGTERM directly.

Add a .dockerignore so local junk doesn't end up in the image:

text
node_modules
.git
.env
*.log

Build and run it:

bash · try it yourself
$ docker build -t shop-api .
$ docker run --rm -p 8080:3000 -e PORT=3000 shop-api
listening on 3000
listening on 3000

-p 8080:3000 maps port 8080 on your machine to port 3000 in the container, so you'd open http://localhost:8080.

Where to deploy

Kind Examples You manage
Platform as a Service Render, Railway, Heroku, Fly.io almost nothing — push code or an image
Container services Google Cloud Run, AWS App Runner / ECS, Azure Container Apps the image
Serverless functions AWS Lambda, Vercel/Netlify functions single handler functions
Virtual machine any VPS OS, Node, process manager, reverse proxy (nginx)

Whatever you choose, automate it: a CI pipeline (for example GitHub Actions) that runs npm ci, npm test, builds the image and deploys only when the tests pass.

Test yourself

Which command installs exactly the versions in package-lock.json and skips dev dependencies?

  1. npm install
  2. npm ci --omit=dev
  3. npm update --prod
  4. npm i -g

Which signal do hosting platforms usually send to stop your app gracefully?

  1. SIGKILL
  2. SIGTERM
  3. SIGHUP
  4. SIGSTOP

Why copy package*.json and run npm ci before copying the rest of the code in a Dockerfile?

  1. Docker requires that order
  2. So the dependency layer is cached and reused when only code changes
  3. To make the image run as root
  4. To delete node_modules