> ## Content Index
> Fetch the complete content index at: https://sudosecurity.org/llms.txt
> Use this file to discover other available public pages before exploring further.

# Production JavaScript, Part 1: Graceful Shutdown in Node, and the Three Ways Docker Kills Your Requests Anyway
- URL: https://sudosecurity.org/nodejs-graceful-shutdown-sigterm-docker/
- Published: 2026-12-04T14:00:00.000Z
- Updated: 2026-12-04T14:00:00.000Z
- Description: Every deploy sends your Node server a SIGTERM, and what happens next decides whether users see errors. I tested six ways of running the same server under docker stop: a correct shutdown handler drained in-flight requests in 1.5 seconds, while npm start and a shell-form CMD threw that work away...
- Author: Santhdium
- Tags: Node.js, JavaScript, Tutorials, Backend Development, Docker, Containers, DevOps, Software Engineering

Here's something most tutorials skip: your server's last few seconds matter as much as its first. Every deploy, autoscale-down and node drain ends the same way. The platform sends your process a `SIGTERM`, waits a grace period, then sends `SIGKILL`. Whatever requests were in flight when that first signal arrived either finish or fail, and if they fail, the users who sent them see errors on every single deploy, at random.

This is the first article in a series on production JavaScript: the things that work fine on your laptop and fail once real traffic and real infrastructure are involved. Each piece has runnable code, tests I ran with their real output, and exercises at the end. This one is about shutting down cleanly, and the surprising number of ways it goes wrong in containers even when your code is right.

## Graceful Shutdown in Node.js, in Plain Terms

A graceful shutdown has three steps:

1. **Stop accepting new connections**, so the load balancer sends new traffic to other instances.
2. **Let in-flight requests finish**, so nobody gets a connection reset partway through.
3. **Exit**, with a deadline, so one stuck client can't block the deploy forever.

What you'll learn here:

- What Node does with `SIGTERM` by default, and why that's different inside a container
- How to write a shutdown handler with `server.close()` and a drain timeout
- Why `npm start` and shell-form `CMD` lines break shutdown even when your handler is correct
- How keep-alive connections and grace periods interact with draining

## The Test Server

Two versions of the same tiny server. Every request takes 2 seconds, standing in for a slow query, an upload or a report. The first has no shutdown handling:

```js
// No shutdown handling at all.
import { createServer } from "node:http";
import { setTimeout as sleep } from "node:timers/promises";

createServer(async (req, res) => {
  await sleep(2000);                       // a request that takes 2 s: an upload, a report, a slow query
  res.end("done\n");
}).listen(8090, () => console.log(`pid ${process.pid} listening`));

```

The second handles `SIGTERM` properly:

```js
// Stop accepting, finish in-flight requests, then exit. Force-exit if draining takes too long.
import { createServer } from "node:http";
import { setTimeout as sleep } from "node:timers/promises";

const SLOW_MS = Number(process.env.SLOW_MS ?? 2000);      // how long the slow endpoint takes
const DRAIN_MS = Number(process.env.DRAIN_MS ?? 10_000);  // give up on draining after this long

const server = createServer(async (req, res) => {
  if (req.url !== "/fast") await sleep(SLOW_MS);
  res.end("done\n");
}).listen(8090, () => console.log(`pid ${process.pid} listening`));

let shuttingDown = false;
function shutdown(signal) {
  if (shuttingDown) return;
  shuttingDown = true;
  console.log(`${signal}: closing server, ${server.listening ? "draining" : "not listening"}`);
  server.close((err) => {                  // stops accepting; callback runs when every connection is closed
    console.log(err ? `close error: ${err.message}` : "all connections closed, exiting");
    process.exit(err ? 1 : 0);
  });
  setTimeout(() => {                       // don't hang forever on a stuck client
    console.log("drain timeout: closing remaining connections");
    server.closeAllConnections();
    process.exit(1);
  }, DRAIN_MS).unref();
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);

```

The test script runs each server in a `node:26-slim` container (Node 26.13.1), starts one 2-second request, waits half a second, then runs `docker stop -t 10`. That sends `SIGTERM`, waits 10 seconds, then sends `SIGKILL`, which is the same sequence Kubernetes and most platforms use. It records how long the stop took, the exit code, and what the client saw:

```bash
#!/bin/bash
# Run a server in a container, start a 2-second request, then `docker stop -t 10` (SIGTERM, then SIGKILL after 10 s).
# Report how long the stop took, the exit code, and what the in-flight client saw.
# usage: test-shutdown.sh LABEL "docker run options" command...
label=$1; opts=$2; shift 2
docker rm -f srv >/dev/null 2>&1; rm -f /tmp/body /tmp/code /tmp/cexit
docker run -d --name srv --network host $opts -v $PWD:/w -w /w node:26-slim "$@" >/dev/null
for i in $(seq 100); do docker logs srv 2>&1 | grep -q listening && break; sleep 0.1; done
( curl -s -o /tmp/body -w '%{http_code}' --max-time 30 http://127.0.0.1:8090/ > /tmp/code; echo "curl exit $?" > /tmp/cexit ) &
CURL=$!; sleep 0.5
T0=$(date +%s%N); docker stop -t 10 srv >/dev/null; T1=$(date +%s%N); code=$(docker inspect -f '{{.State.ExitCode}}' srv); wait $CURL
printf '%-38s exit %-3s after %5d ms | client: HTTP %s, %s, body "%s"\n' "$label" "$code" $(( (T1-T0)/1000000 )) "$(cat /tmp/code)" "$(cat /tmp/cexit)" "$( [ -f /tmp/body ] && tr -d '\n' < /tmp/body )"
docker logs srv 2>&1 | grep -vE 'listening|^> |^$' | sed 's/^/      log: /'
docker rm -f srv >/dev/null 2>&1

```

> **We recommend reading** [The JavaScript Event Loop: Call Stack, Task Queue & Microtasks](https://sudosecurity.org/js-event-loop-deep-dive/) to continue reading our selection of content. Shutdown works the way it does because of the event loop, and this explains what's keeping your process alive.

[The JavaScript Event Loop: Call Stack, Task Queue & Microtasks](https://sudosecurity.org/js-event-loop-deep-dive/) A production-focused deep dive into the JavaScript event loop: call stack mechanics, microtasks vs. macrotasks, and how async code really runs. SudoSecurity · Santhdium

## Six Ways to Run the Same Server

```text
naive, node as PID 1                   exit 137 after 10081 ms | client: HTTP 200, curl exit 0, body "done"
naive, --init (tini is PID 1)          exit 143 after    66 ms | client: HTTP 000, curl exit 52, body ""
graceful, node as PID 1                exit 0   after  1552 ms | client: HTTP 200, curl exit 0, body "done"
      log: SIGTERM: closing server, draining
      log: all connections closed, exiting
graceful, --init                       exit 0   after  1549 ms | client: HTTP 200, curl exit 0, body "done"
      log: SIGTERM: closing server, draining
      log: all connections closed, exiting
graceful, via npm start                exit 1   after   647 ms | client: HTTP 000, curl exit 52, body ""
      log: npm error path /w
      log: npm error command failed
      log: npm error signal SIGTERM
      log: npm error command sh -c node server-graceful.mjs
      log: npm error A complete log of this run can be found in: /root/.npm/_logs/2026-11-25T05_02_21_798Z-debug-0.log
graceful, via sh -c (shell-form CMD)   exit 137 after 10080 ms | client: HTTP 200, curl exit 0, body "done"

```

| How the server was started     | Stop took | Exit code     | In-flight request    |
| ------------------------------ | --------- | ------------- | -------------------- |
| Naive, node as PID 1           | 10,081 ms | 137 (SIGKILL) | Finished, by luck    |
| Naive, \--init (tini as PID 1) | 66 ms     | 143 (SIGTERM) | **Connection reset** |
| Graceful, node as PID 1        | 1,552 ms  | 0             | Finished             |
| Graceful, \--init              | 1,549 ms  | 0             | Finished             |
| Graceful, via npm start        | 647 ms    | 1             | **Connection reset** |
| Graceful, via sh -c            | 10,080 ms | 137 (SIGKILL) | Finished, by luck    |

Only the two graceful rows that ran `node` directly did everything right: the request finished, the process exited cleanly with code 0, and the stop took 1.5 seconds, exactly the time the request had left. Every other row fails in its own way.

## What Each Failure Means

**Naive with `--init`: the request dies.** Without a handler, Node's default response to `SIGTERM` is to exit immediately. Exit code 143 is 128 + 15, the signal number for `SIGTERM`. The in-flight request was cut off and curl got exit 52, "empty reply from server." In production, that's a 502 from your load balancer on every deploy.

**Naive as PID 1: the signal is ignored.** This one surprises almost everyone. The Linux kernel doesn't apply default signal actions to PID 1, so a process running as PID 1 that hasn't installed a handler simply ignores `SIGTERM`. The Node Docker image docs say it directly: "Node.js was not designed to run as PID 1 which leads to unexpected behaviour when running inside of Docker." The container kept running for the full 10 seconds until `SIGKILL`. The in-flight request finished only because it happened to be shorter than 10 seconds. Every deploy of this container takes the full grace period per instance.

**Graceful as PID 1: works.** Once you install a handler, PID 1 behaves normally, because the kernel only skips the default action and your handler isn't one. Still, `--init` (or `tini` or `dumb-init` in the image) is worth adding anyway: it also reaps zombie processes and forwards other signals.

**`npm start`: npm got the signal and the request died anyway.** npm ran as PID 1, received `SIGTERM`, exited with code 1 after 647 ms, and logged `npm error signal SIGTERM`. The server never logged its own shutdown messages, and the in-flight request was reset. The graceful handler was in the code and never got the chance to finish. `npm start` is a development convenience, not a process manager. Run `node` directly in the container's `CMD`.

**`sh -c` (shell-form CMD): nobody got the signal.** `CMD node server.js` without the JSON brackets is shell form. Docker runs it as `/bin/sh -c "node server.js"`, so the shell is PID 1\. The shell didn't forward `SIGTERM`, so the server never heard about the shutdown and was `SIGKILL`ed at 10 seconds. Always use the exec form: `CMD ["node", "server.mjs"]`.

## Keep-Alive Connections

Browsers and load balancers reuse connections, so at any moment your server has idle keep-alive sockets open. Older advice says these block `server.close()` until they time out. I tested it with a client that makes one request and then holds the socket open:

```js
// One request over a keep-alive connection, then hold the idle socket open for 30 s.
import http from "node:http";
const agent = new http.Agent({ keepAlive: true });
http.get({ host: "127.0.0.1", port: 8090, path: "/fast", agent }, (res) => {
  res.resume();
  res.on("end", () => console.log("keep-alive request done; socket left idle"));
});
setTimeout(() => {}, 30_000);

```

```text
client: keep-alive request done; socket left idle
established connections to :8090 before stop: 1
server stop with an idle keep-alive socket open: exit 0 after 58 ms
      log: SIGTERM: closing server, draining
      log: all connections closed, exiting

```

The server shut down in 58 ms with the idle socket open. The Node docs record why: since v19.0.0, `server.close()` "closes idle connections before returning," and it now "closes all connections connected to this server which are not sending a request or waiting for a response." On Node 18 and older, those idle sockets held the close callback until `keepAliveTimeout` expired, which is the reason older tutorials include connection-tracking code you no longer need.

## The Drain Timeout Has to Beat the Grace Period

The handler's 10-second drain timeout exists for requests that won't finish. Here's a 30-second request with two different drain timeouts, both under `docker stop -t 10`:

```text
30 s request, drain 10 s, stop -t 10   exit 1   after 10069 ms | client: HTTP 000, curl exit 52, body ""
      log: SIGTERM: closing server, draining
      log: drain timeout: closing remaining connections
30 s request, drain 5 s, stop -t 10    exit 1   after  5071 ms | client: HTTP 000, curl exit 52, body ""
      log: SIGTERM: closing server, draining
      log: drain timeout: closing remaining connections

```

With a 10-second drain timeout and a 10-second grace period, the process exited at 10,069 ms. It won the race against `SIGKILL` by milliseconds, which means it was luck: on a busier machine, `SIGKILL` arrives first and your cleanup code never runs. With a 5-second drain timeout, the process exited deliberately at 5,071 ms, closed the stuck connection itself and still had time to flush logs or close database pools.

The rule: **drain timeout < grace period**, with real margin. Kubernetes' default `terminationGracePeriodSeconds` is 30 seconds per its docs, and `docker stop` defaults to 10\. Set your drain deadline to a few seconds less than whichever applies, and make sure your longest legitimate request fits inside it.

> **We recommend reading** [Node 26 Is LTS and Temporal Is Finally On by Default](https://sudosecurity.org/nodejs-26-lts-upgrade/) to continue reading our selection of content. All of this was tested on Node 26, and here's what else changed when 26 became LTS.

[Node 26 Is LTS and Temporal Is Finally On by Default](https://sudosecurity.org/nodejs-26-lts-upgrade/) Node.js 26 is LTS as of October 28\. Temporal enabled by default, V8 14.6, legacy stream modules removed. What breaks on upgrade. SudoSecurity · Santhdium

## One More Step Behind a Load Balancer

`server.close()` stops accepting new connections, but the load balancer may keep routing new requests to the instance for a few seconds after the pod starts terminating, until it notices. In Kubernetes the usual fix is a short `preStop` sleep, or a readiness endpoint that starts failing as soon as `SIGTERM` arrives, so traffic moves away before the server closes. I didn't test a real load balancer here, so treat this as the next thing to verify on your own platform. The symptom when it's missing is a small burst of connection-refused errors at the start of every deploy.

## Exercises

1. **Reproduce the table.** Run `test-shutdown.sh` for each row. Then change `SLOW_MS` to 12000 and explain why the "naive, PID 1" row now loses the request.
2. **Add a readiness flag.** Add a `/healthz` route that returns 200 normally and 503 once `shuttingDown` is true. Why does this matter only behind a load balancer?
3. **Close a resource.** Add a fake database pool (an object with an async `end()` that takes 300 ms) and close it after `server.close()` finishes, but before `process.exit`. What happens if you call it before the server has drained?
4. **Break it on purpose.** Write a Dockerfile with `CMD npm start`, then one with `CMD ["node", "server-graceful.mjs"]`. Time `docker stop` for each.
5. **Second signal.** What should happen if a second `SIGTERM` (or a Ctrl-C) arrives while draining? Change the handler so a second signal exits immediately.

## What This Doesn't Cover

- **Clustered and worker-thread servers.** `cluster` primaries need to forward signals and wait for workers. That's its own pattern.
- **WebSockets and SSE.** Long-lived connections never finish on their own, so you have to tell clients to reconnect and then close them.
- **Queue consumers.** Stop pulling new jobs, finish the current one, and acknowledge it. Same idea, different API.
- **Bun and Deno.** Both handle signals with their own APIs.

## The Actual Point

Graceful shutdown is about thirty lines of code: catch `SIGTERM`, call `server.close()`, exit when it's done, and force an exit before the platform's deadline. Most of the failures in my tests weren't in that code. They came from how the process was started: `npm start` exiting before the server could drain, a shell-form `CMD` swallowing the signal, and a handlerless Node process as PID 1 ignoring `SIGTERM` entirely. Run `node` directly with an exec-form `CMD`, add `--init`, set a drain timeout below your grace period, and test it with `docker stop` before production tests it for you.

*Sources: the Node.js v26 HTTP documentation for `server.close()` and `closeAllConnections()`, the nodejs/docker-node best-practices guide, and the Kubernetes pod lifecycle documentation. All tests were run by me with node:26-slim containers under Docker's `docker stop`. Every code and output block above is reproduced verbatim from those scripts and runs; the servers and test scripts are original teaching code using Node's public API.*