How to limit `docker run` execution time?
The --stop-timeout
option is the maximum amount of time docker should wait for your container to stop when using the docker stop
command.
A container will stop when it's told to or when the command is running finishes, so if you change you sleep from 100 to 1, you'll see that the container is stopped after a second.
What I'll advice you to do is to change the ENTRYPOINT
of your container to a script that you create, that will execute what you want and keep track of the execution time from within and exit when timeout.
After that you can start your container using the --rm
option that will delete it once the script finishes.
A small example.
Dockerfile:
FROM ubuntu:16.04
ADD ./script.sh /script.sh
ENTRYPOINT /script.sh
script.sh:
#!/bin/bash
timeout=5
sleep_for=1
sleep 100 &
find_process=$(ps aux | grep -v "grep" | grep "sleep")
while [ ! -z "$find_process" ]; do
find_process=$(ps aux | grep -v "grep" | grep "sleep")
if [ "$timeout" -le "0" ]; then
echo "Timeout"
exit 1
fi
timeout=$(($timeout - $sleep_for))
sleep $sleep_for
done
exit 0
Run it using:
docker build -t testing .
docker run --rm testing
This script will execute sleep 100
in background, check if its still running and if the timeout of 5 seconds is reach then exit.
This might not be the best way to do it, but if you want to do something simple it may help.
You can try
timeout 3 docker run...
there is a PR on that subject
https://github.com/moby/moby/issues/1905
See also
Docker timeout for container?