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

后端 未结 14 1034
猫巷女王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:09

    On your ENTRYPOINT script, you have to check if you have a valid MySQL connection or not.

    This solution does not require you to install a MySQL Client on the container and while running the container with php:7.0-fpm running nc was not an option, because it had to be installed as well. Also, checking if the port is open does not necessarily mean that the service is running and exposed correctly. [more of this]

    So in this solution, I will show you how to run a PHP script to check if a MySQL Container is able to take connection. If you want to know why I think this is a better approach check my comment here.

    File entrypoint.sh

    #!/bin/bash
    cat << EOF > /tmp/wait_for_mysql.php
     PDO::ERRMODE_EXCEPTION)
            );
            \$connected = true;
        }
        catch(PDOException \$ex){
            error_log("Could not connect to MySQL");
            error_log(\$ex->getMessage());
            error_log("Waiting for MySQL Connection.");
            sleep(5);
        }
    }
    EOF
    php /tmp/wait_for_mysql.php
    # Rest of entry point bootstrapping
    

    By running this, you are essentially blocking any bootstrapping logic of your container UNTIL you have a valid MySQL Connection.

提交回复
热议问题