What’s the difference between `docker stop` and `docker kill`

docker

What's the difference between docker stop and docker kill?

Afaik, both will stop a running container. Is it that docker stop attempts to stop the process run inside the container in the correct way, while docker kill will send a kill signal? If so how would docker stop know how to correctly stop the running process. (Since this differs from process to process)

Best Answer

Is it that docker stop attempts to stop the process run inside the container in the correct way, while docker kill will send a kill signal?

Basically yes, the difference is subtle, but outlined in the Command Line reference:

  • docker stop: Stop a running container (send SIGTERM, and then SIGKILL after grace period) [...] The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL. [emphasis mine]
  • docker kill: Kill a running container (send SIGKILL, or specified signal) [...] The main process inside the container will be sent SIGKILL, or any signal specified with option --signal. [emphasis mine]

So stop attempts to trigger a graceful shutdown by sending the standard POSIX signal SIGTERM, whereas killjust kills the process by default (but also allows to send any other signal):

The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate. It should be noted that SIGINT is nearly identical to SIGTERM.

While not enforced in anyway, processes are generally expected to handle SIGTERM gracefully and do the right thing depending on their responsibilities - this can easily fail due to the graceful shutdown attempt taking longer than the grace period though, which is something to consider if data integrity is paramount (e.g. for databases); see e.g. Major Hayden's SIGTERM vs. SIGKILL for a more detailed explanation:

The application can determine what it wants to do once a SIGTERM is received. While most applications will clean up their resources and stop, some may not. An application may be configured to do something completely different when a SIGTERM is received. Also, if the application is in a bad state, such as waiting for disk I/O, it may not be able to act on the signal that was sent.

Related Question