Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Part 1
You run docker stop, and the terminal just hangs for ten seconds. Then the container dies with exit code 137.
Here's what's happening. Docker sends orders-api a SIGTERM, a polite request to shut down. Nothing reacts, so Docker waits out its ten-second grace period. Then it sends SIGKILL, signal 9, and the app is gone. That 137 is 128 plus 9.
The cause: SIGTERM never lands
As PID 1, node gets no default terminate action, so without a SIGTERM handler it ignores the signal. With shell form, sh may never forward it.
A polite request, then a forced exit
Think of docker stop as a bouncer at closing time. The tap on the shoulder is SIGTERM, a polite request to leave. The headphones are orders-api not hearing it, because of no handler or the PID 1 problem. The stopwatch is the ten second grace period. When it runs out, the second bouncer, SIGKILL, carries it out.
Dockerfile
The first fix is in the Dockerfile. Shell form wraps your command in sh, which may become PID 1 and may not forward SIGTERM. Exec form, with the command as a JSON array, makes node itself PID 1, so the signal reaches it. If you can't change that, docker run --init adds tini, which forwards signals and reaps children.
# Shell form: sh -c may be PID 1
# and may not forward SIGTERM
# CMD node server.js
# Exec form: node itself is PID 1
CMD ["node", "server.js"]server.js
Once SIGTERM reaches node, the handler decides what happens. Here it stops accepting new connections, lets in-flight requests finish, then exits with code zero. That's typically well inside the ten seconds. Using docker stop with the t flag only changes how long Docker waits. It doesn't make an ignored signal get handled.
process.on('SIGTERM', () => {
console.log('SIGTERM: closing server');
server.close(() => process.exit(0));
});docker stop asks politely with SIGTERM, then forces SIGKILL after 10s.
docker stop asks politely with SIGTERM, then forces SIGKILL after ten seconds. Whether your app exits cleanly depends on whether node, as PID 1, actually receives that signal and handles it. So use exec form CMD or the --init flag, and add a SIGTERM handler that drains requests and exits zero.
