How do I know when my docker mysql container is up and mysql is ready for taking queries?

后端 未结 14 1015
猫巷女王i
猫巷女王i 2020-11-30 22:33

I am deploying a few different docker containers, mysql being the first one. I want to run scripts as soon as database is up and proceed to building other containers. The sc

14条回答
  •  天命终不由人
    2020-11-30 23:19

    This was more or less mentioned in comments to other answers, but I think it deserves its own entry.

    First of all you can run your container in the following manner:

    docker run --name mysql --health-cmd='mysqladmin ping --silent' -d mysql
    

    There is also an equivalent in the Dockerfile.

    With that command your docker ps and docker inspect will show you health status of your container. For mysql in particular this method has the advantage of mysqladmin being available inside the container, so you do not need to install it on the docker host.

    Then you can simply loop in a bash script to wait on the status to become healthy. The following bash script is created by Dennis.

    function getContainerHealth {
      docker inspect --format "{{.State.Health.Status}}" $1
    }
    
    function waitContainer {
      while STATUS=$(getContainerHealth $1); [ $STATUS != "healthy" ]; do 
        if [ $STATUS == "unhealthy" ]; then
          echo "Failed!"
          exit -1
        fi
        printf .
        lf=$'\n'
        sleep 1
      done
      printf "$lf"
    }
    

    Now you can do this in your script:

    waitContainer mysql
    

    and your script will wait until the container is up and running. The script will exit if the container becomes unhealthy, which is possible, if for example docker host is out of memory, so that the mysql cannot allocate enough of it for itself.

提交回复
热议问题