Home >Database >Mysql Tutorial >How to Successfully Initialize a MySQL Database Schema within a Docker Container?

How to Successfully Initialize a MySQL Database Schema within a Docker Container?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 06:41:101030browse

How to Successfully Initialize a MySQL Database Schema within a Docker Container?

How to Initialize a MySQL Database with Schema in a Docker Container

Initializing a database with a schema can be a complex process, especially when using a Docker container. This article addresses a common issue encountered when initializing a MySQL database with schema using a Docker container and provides a solution based on dumping the schema to a file and adding it to the /docker-entrypoint-initdb.d directory.

Problem Description

When attempting to create a Docker container with a MySQL database and initialize it with a schema using the following Dockerfile:

FROM mysql
MAINTAINER (me) <email>

# Copy the database schema to the /data directory
COPY files/epcis_schema.sql /data/epcis_schema.sql

# Change the working directory
WORKDIR data

CMD mysql -u $MYSQL_USER -p $MYSQL_PASSWORD $MYSQL_DATABASE < epcis_schema.sql

The container fails to start, and the CMD command is not executed successfully.

Solution

To initialize the database with the schema, follow these steps:

  1. Dump the MySQL schema to a file using:
mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_name> > schema.sql
  1. Add the schema file to the /docker-entrypoint-initdb.d directory in the 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
  1. Start the Docker MySQL instance using:
docker-compose build
docker-compose up

By using the /docker-entrypoint-initdb.d directory, the SQL file will be automatically executed against the MySQL database upon container initialization, ensuring that the database is initialized with the desired schema.

The above is the detailed content of How to Successfully Initialize a MySQL Database Schema within 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