Home >Database >Mysql Tutorial >How to Initialize a MySQL Database with Schema Inside a Docker Container?

How to Initialize a MySQL Database with Schema Inside a Docker Container?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 12:34:09227browse

How to Initialize a MySQL Database with Schema Inside a Docker Container?

Initializing MySQL Database with Schema in Docker Container

Initializing a MySQL database with schema within a Docker container can be challenging. Here's a solution to address this issue:

1. Dump MySQL Schema

Dump your MySQL schema to a file using the following command:

mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_name> > schema.sql

2. Add Schema File to Dockerfile

In your Dockerfile, add the schema file to the /docker-entrypoint-initdb.d directory using the ADD command. The docker-entrypoint.sh script in the container will execute any .sql files in this directory against the database.

Sample Dockerfile:

FROM mysql:5.7.15

MAINTAINER me

ENV MYSQL_DATABASE=<schema_name> \
    MYSQL_ROOT_PASSWORD=<password>

ADD schema.sql /docker-entrypoint-initdb.d

EXPOSE 3306

3. Build and Run Docker Container

Once the Dockerfile is modified, build and run the container:

docker-compose build
docker-compose up

4. Additional Notes

  • Ensure that the MySQL user has sufficient privileges to create the database and tables.
  • Adjust the MySQL host, user name, password, and schema name as needed.
  • Verify that the docker-entrypoint.sh script is executable by the root user within the container, as it is responsible for executing the schema initialization.

By following these steps, you can successfully initialize a MySQL database with schema within a Docker container and eliminate the issue of the CMD not executing properly.

The above is the detailed content of How to Initialize a MySQL Database with Schema Inside a Docker Container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn