SolvedGraceful shutdown for a Node API in Docker — what is the right way?

E Emma Member Joined: Oct 1, 2026
Posts: 4
#1

Learning deployment basics. On every deploy the container is stopped and some requests in flight fail. As far as I understand the app should "drain" first. What does a correct shutdown look like in Node, and what do I need to change in Docker?

YS Yury Slinkin Staff · admin Joined: Jun 6, 2026
Posts: 94
#2

On stop, Docker sends SIGTERM, waits (10 seconds by default), then SIGKILL. Your app should, on SIGTERM: stop accepting new connections, let current requests finish, close the database pool, exit. With a hard deadline, in case something hangs.

import http from 'node:http';

const server = http.createServer(handler);
server.listen(3000);

let stopping = false;

function shutdown(signal) {
  if (stopping) return;
  stopping = true;
  console.log(`${signal} received, draining`);

  // hard deadline, a bit below Docker's stop timeout
  setTimeout(() => {
    console.error('drain timed out, exiting');
    process.exit(1);
  }, 8_000).unref();

  server.close(async (err) => {
    try {
      await pool.end(); // your DB pool
    } finally {
      process.exit(err ? 1 : 0);
    }
  });
  // keep-alive connections that are idle would hold close() open
  server.closeIdleConnections();
}

process.once('SIGTERM', () => shutdown('SIGTERM'));
process.once('SIGINT', () => shutdown('SIGINT'));

And make the health check fail as soon as stopping is true, so a load balancer stops sending traffic:

function handler(req, res) {
  if (req.url === '/health') {
    res.writeHead(stopping ? 503 : 200).end(stopping ? 'stopping' : 'ok');
    return;
  }
  // ...
}

In the Dockerfile, the process that receives the signal must be Node itself:

CMD ["node", "server.js"]

The exec form (JSON array) runs Node directly. The shell form CMD node server.js wraps it in /bin/sh, and the signal may never reach Node.

ER Evgeny Rudenko Member Joined: Aug 14, 2026
Posts: 86
#3

On Kubernetes there's one more race: the pod gets SIGTERM at the same time as it is removed from the Service endpoints, and that removal takes a moment to propagate. A few requests can still arrive after you stopped listening. The usual fix is a short pause before draining:

spec:
  terminationGracePeriodSeconds: 30
  containers:
    - name: api
      lifecycle:
        preStop:
          sleep:
            seconds: 5

Then the deadline in the code has to fit inside 30 seconds minus that pause. If your Kubernetes version doesn't support the sleep action yet, use exec with sleep 5, which needs a shell in the image.

TP Tomasz P. Member Joined: Jun 30, 2026
Posts: 84
#4

Question: in our tutorial the Dockerfile has CMD ["npm", "start"]. Is this also wrong?

YS Yury Slinkin Staff · admin Joined: Jun 6, 2026
Posts: 94
#5

>>4
It's the same problem one level up: PID 1 is npm, and Node is its child. Whether SIGTERM gets passed on depends on the npm version and the shell in between, so it's easy to end up with a 10-second wait and a SIGKILL. Call node directly in CMD.

A related detail: as PID 1, Node gets no default signal handlers from the kernel, so without your own process.once('SIGTERM', ...) it ignores the signal. Either keep the handlers from above, or run the container with docker run --init (a tiny init process forwards signals and reaps zombies).

ER Evgeny Rudenko Member Joined: Aug 14, 2026
Posts: 86
#6

And for Bun the same idea: Bun.serve returns a server object, await server.stop() stops accepting connections and waits for active ones; server.stop(true) closes them right away. The signal handling and the Docker part are identical.

Quick reply

Only signed-in members can write. Sign in