← Back to Node.js, page 5

nodejs-0097 · Medium mid

What does a good Dockerfile for a Node.js service look like, and why does PID 1 and signal handling matter?

Use a small official Node image with a fixed version, copy package files first so dependency installation is cached, run npm ci with only production dependencies, run as the non-root node user, set NODE_ENV=production, add a health check, and start with node directly (not through npm), so SIGTERM reaches the app. Use an init process or handle signals in code, because PID 1 behaves differently.

Full answer

A reasonable multi-stage Dockerfile (written for explanation; it was not built on this box, which has no Docker):

FROM node:24-slim AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev

FROM node:24-slim ENV NODE_ENV=production WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . USER node EXPOSE 3000 HEALTHCHECK --interval=30s --timeout=3s CMD ["node", "healthcheck.js"] CMD ["node", "server.js"]

Why each choice:

  • Pin the image version (node:24-slim or a digest), not latest, so builds repeat.
  • Copy package files before the source so Docker reuses the cached dependency layer until package.json changes.
  • npm ci uses the lock file and gives repeatable installs. --omit=dev leaves out test and build tools, which makes the image smaller and safer.
  • A .dockerignore (node_modules, .git, .env, logs) keeps secrets and junk out of the build context.
  • USER node: do not run as root. A bug then has fewer rights.
  • NODE_ENV=production switches libraries to their production behaviour.
  • Never bake secrets into the image. Pass them at run time as environment variables or mounted secrets.

PID 1 and signals: docker stop sends SIGTERM to the process with PID 1 in the container. If you start the app with npm start, npm (or a shell) is PID 1 and may not forward the signal, so the app is killed hard after the timeout (10 seconds by default). Use CMD ["node", "server.js"] in exec form. Also, on Linux PID 1 has no default signal handlers, so a Node process as PID 1 ignores SIGTERM unless the code registers a handler. Handle SIGTERM in code (graceful shutdown) or add a tiny init such as tini (docker run --init).

Other points: write logs to stdout, set memory limits and make Node aware of them (--max-old-space-size or the default container awareness in current Node), and use a health check that tests the app, not only the process.

javascript
const { spawn, spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-demo-'));

// The service: /health answers 200 and the app stops cleanly on SIGTERM.
fs.writeFileSync(path.join(dir, 'server.js'), `
const http = require('node:http');
const server = http.createServer((req, res) => {
  if (req.url === '/health') { res.statusCode = 200; return res.end('ok'); }
  res.end('Hello from the container');
});
server.listen(0, '127.0.0.1', () => console.log('PORT=' + server.address().port));
process.on('SIGTERM', () => server.close(() => { console.log('server stopped after SIGTERM'); }));
`);

// The health check used in HEALTHCHECK: exit 0 when healthy, 1 when not.
fs.writeFileSync(path.join(dir, 'healthcheck.js'), `
const http = require('node:http');
const req = http.get({ host: '127.0.0.1', port: process.env.PORT, path: '/health', timeout: 1000 }, (res) => {
  process.exit(res.statusCode === 200 ? 0 : 1);
});
req.on('error', () => process.exit(1));
req.on('timeout', () => { req.destroy(); process.exit(1); });
`);

const check = (port) => spawnSync(process.execPath, [path.join(dir, 'healthcheck.js')], { env: { ...process.env, PORT: String(port) } }).status;

const server = spawn(process.execPath, [path.join(dir, 'server.js')], { stdio: ['ignore', 'pipe', 'inherit'] });
let output = '';
server.stdout.on('data', (chunk) => {
  output += chunk;
  const match = output.match(/PORT=(\d+)/);
  if (!match || server.checked) return;
  server.checked = true;
  const port = match[1];
  console.log('healthcheck while the server runs -> exit code', check(port));
  server.kill('SIGTERM'); // what "docker stop" sends
});
server.on('exit', (code, signal) => {
  console.log('server output:', output.split('\n').filter((l) => l && !l.startsWith('PORT')).join(' '));
  console.log('server exit code:', code, '| killed by signal:', signal);
  console.log('healthcheck after the server stopped -> exit code', check(server.checked ? output.match(/PORT=(\d+)/)[1] : 0));
  fs.rmSync(dir, { recursive: true });
});

This snippet demonstrates the health check and the SIGTERM handling that the Dockerfile relies on. The Dockerfile text in the answer was not built here. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): healthcheck while the server runs -> exit code 0 server output: server stopped after SIGTERM server exit code: 0 | killed by signal: null healthcheck after the server stopped -> exit code 1

Key points

  • Pin versions, cache dependencies, npm ci --omit=dev.
  • Run as a non-root user with NODE_ENV=production.
  • Use exec form CMD ["node", ...] so signals arrive.
  • Handle SIGTERM in code. PID 1 has no default handler.
  • No secrets in the image.

Common mistakes

  • Starting the app with npm start inside the container and losing SIGTERM.
  • Copying the whole source before installing dependencies and losing the layer cache.
  • Running as root and baking .env into the image.
  • A health check that only tests that the process exists.

Follow-ups

  • What does docker run --init do?
  • How do you pass secrets to a container safely?
  • How would you keep the final image small?

Tips

  • Show the Dockerfile in the right order: dependencies first.
  • Explain PID 1 in one sentence.
  • Mention exec form versus shell form.