Home >Database >Mysql Tutorial >How to Efficiently Import Database Dumps into MySQL within a Docker Environment?
Setting Up Database and Importing Dump in Dockerfile
In a Docker environment, it's common to face difficulties when configuring MySQL and importing database dumps during the build process. To resolve these issues, consider the following approach:
The official MySQL Docker image includes a feature that enables data import at startup. This eliminates the need for manual database creation and dump import steps within the Dockerfile. To implement this, create a docker-compose.yml file similar to:
data: build: docker/data/. mysql: image: mysql ports: - "3307:3306" environment: MYSQL_ROOT_PASSWORD: 1234 volumes: - ./docker/data:/docker-entrypoint-initdb.d volumes_from: - data
In this configuration, the data-dump.sql file should be located in the docker/data directory. The volume mapping will make it accessible within the container at /docker-entrypoint-initdb.d.
Behind the scenes, the docker-entrypoint.sh script in the MySQL Docker image includes a code block that automatically executes SQL files found in /docker-entrypoint-initdb.d:
for f in /docker-entrypoint-initdb.d/*; do case "$f" in *.sh) echo "<pre class="brush:php;toolbar:false">FROM n3ziniuka5/ubuntu-oracle-jdk:14.04-JDK8 VOLUME /var/lib/mysql CMD ["true"]: running $f"; . "$f" ;; *.sql) echo ": running $f"; "${mysql[@]}" < "$f" && echo ;; *) echo ": ignoring $f" ;; esac echo done
This ensures that the data-dump.sql file is executed at container startup.
To maintain data persistence across container restarts and removals, it's recommended to create a separate data container. The Dockerfile for such a container can be as simple as:
The CMD ["true"] command is used to prevent the container from exiting. The data container does not need to be in a started state to ensure data persistence.
The above is the detailed content of How to Efficiently Import Database Dumps into MySQL within a Docker Environment?. For more information, please follow other related articles on the PHP Chinese website!