Graceful Shutdown (Stop vs Kill)

Difficulty: Intermediate

Question

What is the difference between docker stop and docker kill, and how do you make a containerized application shut down gracefully?

Answer

docker stop sends the container's stop signal (SIGTERM by default) to the main process, waits for a grace period (10 seconds by default), and only then sends SIGKILL. docker kill sends SIGKILL immediately by default, so the process has no chance to finish requests, flush buffers or close database connections. Graceful shutdown depends on your application actually receiving and handling SIGTERM as PID 1.

What happens step by step

  1. docker stop api sends SIGTERM (or whatever STOPSIGNAL the image or --stop-signal specifies) to PID 1 in the container.
  2. Docker waits up to the timeout: 10 seconds by default, configurable with docker stop -t 30, --stop-timeout on docker run, or stop_grace_period in Compose.
  3. If the process is still running, Docker sends SIGKILL, which cannot be caught.

docker kill api skips straight to SIGKILL. You can send other signals with docker kill -s SIGHUP api, for example to make nginx reload its config.

docker stopdocker kill
Default signalSIGTERM (STOPSIGNAL)SIGKILL
Grace period10s, then SIGKILLNone
Typical exit code0 or 143 if handled137 (128 + 9)
Use forDeploys, normal stopsHung containers, sending custom signals

Why apps often ignore SIGTERM

  • Shell form CMD: CMD node server.js runs /bin/sh -c ..., so the shell is PID 1 and may not forward the signal. Use exec form CMD ["node", "server.js"].
  • PID 1 special rules: the Linux kernel does not apply default signal actions to PID 1 in a namespace. If your program does not install a SIGTERM handler, the signal is effectively ignored and Docker waits the full timeout before killing it. That is the classic "every deploy takes exactly 10 seconds per container" symptom.
  • Wrapper processes: npm start adds an npm process in front of node. Run node directly.
  • Fix for apps that cannot handle it: run with --init (or init: true in Compose), which uses a tiny init (tini) as PID 1 that forwards signals and reaps zombie processes.

What a good shutdown handler does

For an order service at a food delivery company, a clean shutdown is: stop accepting new connections, let in-flight HTTP requests finish, stop pulling from the queue and finish or requeue the current message, close DB pools, then exit with code 0. In Kubernetes the same thing happens on every rolling update: the kubelet sends SIGTERM, waits terminationGracePeriodSeconds (30s default), then SIGKILL. Getting this wrong shows up as dropped requests and half-processed payments during deploys.

Exit code 137 does not always mean someone ran docker kill; it also appears when the kernel OOM killer terminates the process. Check docker inspect --format '{{.State.OOMKilled}}' to tell them apart.

docker stop with a graceful app. SIGKILL is only sent if the app does not exit within the grace period.
  1. Docker CLI → Docker daemon: docker stop -t 30 api
  2. Docker daemon → App (PID 1): SIGTERM
  3. App (PID 1) → App (PID 1): Drain requests, close DB pool
  4. App (PID 1) → Docker daemon: Exit 0 within grace period
  5. Docker daemon → Docker CLI: Container stopped

Code examples

Handling SIGTERM in a Node.js server

const http = require('node:http');

const server = http.createServer((req, res) => {
  setTimeout(() => res.end('ok'), 2000); // simulate slow work
});
server.listen(3000);

function shutdown(signal) {
  console.log(`${signal} received, draining connections`);
  server.close(async () => {
    // await db.end(); await queue.close();
    console.log('clean exit');
    process.exit(0);
  });
  // Safety net: exit before Docker's SIGKILL arrives
  setTimeout(() => process.exit(1), 25_000).unref();
}

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

server.close stops new connections and waits for in-flight ones; the timer ensures the process exits before the grace period runs out.

Stop, kill and inspecting the result

docker run -d --name api --init --stop-timeout 30 my-api:1.0

docker stop api                      # SIGTERM, up to 30s, then SIGKILL
docker kill api                      # immediate SIGKILL
docker kill -s SIGHUP web            # send a custom signal

docker inspect api --format \
  'exit={{.State.ExitCode}} oom={{.State.OOMKilled}}'

--init adds a signal-forwarding init process, and the inspect output tells you whether the exit was clean, killed or OOM.

Key points

  • docker stop: SIGTERM, wait 10s by default, then SIGKILL; docker kill: SIGKILL now.
  • Use exec-form CMD so your app is PID 1 and receives signals.
  • PID 1 without a SIGTERM handler ignores the signal; use --init or handle it.
  • Exit 137 = SIGKILL (manual kill or OOM); 143 = SIGTERM not handled cleanly.
  • Kubernetes uses the same pattern with a 30s default terminationGracePeriodSeconds.

Common follow-up questions

  • How can you verify your app actually received SIGTERM?
  • What is PID 1 in a container and why is it special?
  • What does the --init flag do?
  • How would you set the grace period in Compose and Kubernetes?
  • How do you tell an OOM kill apart from a manual docker kill?

Interview tips

  • Explain the full SIGTERM, wait, SIGKILL sequence with the default 10 seconds; precision matters here.
  • Connect it to zero-downtime deploys and dropped requests; interviewers care about the business impact.
  • Mention PID 1 signal behaviour and --init to stand out from candidates who only describe the commands.

Concepts covered

SIGTERM, SIGKILL, Stop Timeout, PID 1, Exit Code 137

More Docker & Containers questions