pythondockerdockerpy

Docker.py how to stop a container with the stdin_open=True?


There is the following code:

import docker
client = docker.from_env()
container = client.containers.create("ubuntu", stdin_open=True)
container.start()
container.stop()

The option stdin_open must be set to True. The stop operations takes 10 seconds to execute (it sends SIGTERM first, if it fails then after 10 seconds it sends SIGKILL). So it looks that SIGTERM is ignored. How to stop the container gracefully with stdin_open set to True?


Solution

  • This is because PID 1 isn't something like systemd and doesn't handle SIGTERM/SIGINT, as you'd expect. Under normal circumstances, a process runs as PID > 1 and PID 1 handles system signals. A container doesn't have systemd running as PID 1 but your entrypoint, instead. Now that something else has taken over (entrypoint) and is PID 1, it is their responsibility to handle system signals. It must be programmed to do so explicitly.

    You have a warning about this in the docs.

    A solution for this is using something like tini that functions as a valid PID 1 process. Specifically, handles SIGINT/SIGTERM in your case and won't require 10 seconds timeout for SIGKILL.