Last active
July 18, 2020 12:49
-
-
Save nevmerzhitsky/663210d7a0908800e61eedda633e2f11 to your computer and use it in GitHub Desktop.
Run a docker container with a timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
TIMEOUT=1m | |
IMAGE=nginx:latest | |
CONTAINER_ID= | |
term_handler() { | |
# This catch both temporary and persistent containers | |
if docker inspect -f {{.State.Running}} $CONTAINER_ID > /dev/null; then | |
docker rm -f $CONTAINER_ID > /dev/null | |
fi | |
exit 0 | |
} | |
trap 'term_handler' SIGINT SIGTERM | |
# Warning: only --rm can save you from losing control over the spawned container if the host OS | |
# will terminated suddenly | |
# Time for pulling the image will not included to timeout | |
CONTAINER_ID=$(docker run -d --rm $IMAGE) | |
echo "Container $CONTAINER_ID started in background for $TIMEOUT" | |
# Sleep in the foreground will block traps thus doing this in the background. | |
sleep $TIMEOUT & | |
SLEEP_PID=$! | |
# Wait until sleep is finished | |
wait $SLEEP_PID | |
docker rm -f $CONTAINER_ID > /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment