Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to make mysql in docker execute sql statement automatically when it starts?

Shulou Source: shulou.com Published: 2022-06-02 00:11:14 10月04日 Update

This article mainly introduces how to make the mysql in docker automatically execute the sql statement when it starts, it has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

When creating a mysql container with docker, we sometimes expect that the database and table will be automatically built and the initialization data will be automatically entered after the container is started, that is, we can directly connect to the database in the container and use the data in the container after startup.

In fact, the official image of mysql supports this capability. The specified sql script or shell script is automatically executed when the container starts. Let's take a look at the Dockerfile of the official image of mysql, as shown below:

ENTRYPOINT has been set, and the script / entrypoint.sh will be called. Let's pull the image mysql:8 locally, start it with docker run, and take a look at the contents of the entrypoint.sh script. There is a section that traverses all the .sh and .sql suffixes from a fixed directory, and then executes them, as shown below:

Now that we've figured out the principle, let's put it into practice:

When building a disconf environment on docker, we need to build a mysql database, and execute four sql files in turn to initialize the database, table, and data. We can do this in two ways:

Copy the four sql files to the / docker-entrypoint-initdb.d directory, so that the four sql will be executed automatically when the container run, but from the screenshot script, the execution order in multiple files cannot be specified. If the script that creates the database is executed later than the script that creates the table, it will cause the table to fail, so this way of copying sql does not meet our needs (but If you synthesize four files into one sql in order, you can meet the requirements.

Make a sh file and execute the sql according to our own needs, as follows:

#! / bin/bashmysql-uroot-p$MYSQL_ROOT_PASSWORD

Tags: File container data database script directory image content time article folder statement official file name environment order work support login that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia vpn Microsoft Huawei