Skip to content

Instantly share code, notes, and snippets.

@nevmerzhitsky
Last active July 18, 2020 12:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevmerzhitsky/663210d7a0908800e61eedda633e2f11 to your computer and use it in GitHub Desktop.
Save nevmerzhitsky/663210d7a0908800e61eedda633e2f11 to your computer and use it in GitHub Desktop.
Run a docker container with a timeout
#!/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