To create a MySQL init script on Docker Compose, follow the steps below:
- Create a directory for your Docker Compose project and navigate into it:
mkdir docker-mysql
cd docker-mysql
- Create a
docker-compose.yaml
file and open it in a text editor:
touch docker-compose.yaml
nano docker-compose.yaml
- Inside the
docker-compose.yaml
, define the MySQL service with the following content:
version: '3.9'
services:
mysql:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=your_mysql_root_password
ports:
- 3306:3306
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
Replace your_mysql_root_password
with your desired MySQL root password.
- Create an
init.sql
file in the same directory and open it in a text editor:
touch init.sql
nano init.sql
- Inside the
init.sql
file, write the SQL statements you want to execute as initialization scripts for MySQL.
For example, you can create a database and a table:
CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE mytable (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
-
Save and exit the
init.sql
file. -
Start the Docker Compose project using the following command:
docker-compose up -d
This will start the MySQL container in detached mode, and it will execute the init.sql
script during initialization.
Now, when you access the MySQL database, you will find the mydatabase
database and the mytable
table created as per the initialization script.