A better Docker MySQL heathcheck

Published on 2021-02-06 • Modified on 2021-02-06

When you use a database container for MySQL, you start the service by calling docker-compose up -d db. But, if you run a Symfony command to build the database, for example, you will have the following error:

An exception occurred in driver: SQLSTATE[HY000] [2006] MySQL server has gone away

Even if MySQL started, it isn't ready yet to handle such commands. That's why it's essential to have a good health check. You can use docker inspect to be sure the service is OK by running docker inspect --format "{{json .State.Health.Status }}" sb-db. If it returns "healthy" then the service is ready; otherwise, you still have to wait for it. I used a simple bash script in a previous snippet that loops and wait for this condition to be fulfilled. (In fact, I don't use docker inspect but I manually run the same health check). Don't use mysqladmin ping because it can give false positive.


    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -P 3306 -proot | grep 'mysqld is alive' || exit 1"]
      interval: 10s
      timeout: 30s
      retries: 10

 More on Stackoverflow   Read the doc  Random snippet