BlindSniper
BlindSniper

Reputation: 1861

Does Docker run command runs in background?

I am running an docker Run command on bash it looks like immediately after firing this command control start executing next line instead of waiting for docker container startup. Is this is how docker works??

UPDATE : I am using -dit as attribute which means it is running in detached mode which I think explains why it jumped to next line immediately. As it is a VM's startup script it will have to be detached but is there is any option where we can at least wait till docker container is done with its provisioning ?

Upvotes: 0

Views: 397

Answers (1)

Matt
Matt

Reputation: 74821

The -d is causing the container to detach immediately. All containers have a different idea of when they are "done with their provisioning" and Docker can't know how the internals of every container work so it's hard for Docker to be responsible for this.

Docker has added a HEALTHCHECK so you can define a test specifically for you container. Then you can query the containers state and wait for it to become healthy in your script.

HEALTHCHECK --interval=1m --timeout=5s \
  CMD curl -f http://localhost/ || exit 1

Then wait in the script

now="$(date +%s)"
let timeout=now+60
while sleep 5; do
  res="$(docker inspect --format='{{.State.Health}}' container_id) 2>&1"
  if [ "res" == "healthy" ]; then break; fi
  if [ "$(date +%s)" -lt "$timeout" ]; then
    echo "Error timeout: $res"
    # handle error
    break
  fi
done

You can modify the wait to run any command, like a curl or nc if you want to forgo the HEALTHCHECK in the container

docker logs container_id may also include the information you need to wait for. Most daemons will log something like "Ready to accept connections"

Upvotes: 1

Related Questions