I ran the following command:
docker run python:3.8-alpine /bin/sh -c "timeout 1s sleep 5"
I expected it to terminate after 1 second, but it took 5 seconds to terminate instead.
If I enter the container and execute the command like below, it terminates correctly after 1 second:
docker run -it python:3.8-alpine /bin/sh
timeout 1s sleep 5
Why did the first command behave differently than expected?
In Docker container this process /bin/sh -c "timeout 1s sleep 5" runs as PID 1.
The timeout command uses the SIGTERM to stop a process.
According to this link:
A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. As a result, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so.
And according to this link:
The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.
You must tell Docker to run the container with --init option (runs an init process):
docker run --init python:3.8-alpine /bin/sh -c "timeout 1s sleep 5"
you can also kill the PID 1 with trap and kill the process.
Trap allows you to catch signals and execute code when they occur.
docker run python:3.8-alpine /bin/sh -c "trap "exit" SIGINT SIGTERM && timeout 1s sleep 5"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With