ファイル構造
yuta:~/mysql $ tree
.
├── docker-compose.yml
└── volumes
├── data
└── init
└── init.sql
3 directories, 2 files
docker-compose.ymlを書く
-
/docker-entrypoint-initdb.d
にシェルやsqlスクリプトなどを配置しておくことで、mysqlのコンテナイメージ起動時に実行することができる
docker-compose.yml
version: "3"
services:
mysql:
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: pass
volumes:
- ./volumes/init/:/docker-entrypoint-initdb.d
- ./volumes/data/:/var/lib/mysql
初回に実行するsqlを用意
init.sql
DROP DATABASE IF EXISTS sample;
CREATE DATABASE sample;
USE sample;
DROP TABLE IF EXISTS name;
CREATE TABLE name (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name TEXT NOT NULL
)DEFAULT CHARACTER SET=utf8;
INSERT INTO name (name) VALUES ("田所"),("浩二"),("令和");
起動
docker-compose up -d
確認
yuta:~/mysql $
yuta:~/mysql $ d ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
76412daa6954 mysql:latest "docker-entrypoint.s…" 30 seconds ago Up 30 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp mysql_mysql_1
yuta:~/mysql $ vim docker-compose.yml
yuta:~/mysql $ d ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
76412daa6954 mysql:latest "docker-entrypoint.s…" 39 seconds ago Up 39 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp mysql_mysql_1
yuta:~/mysql $ d exec -it 76412daa6954 /bin/bash
root@76412daa6954:/#
root@76412daa6954:/# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
root@76412daa6954:/# mysql -uroot -ppass
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sample |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql>
mysql> use sample
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql>
mysql> show tables;
+------------------+
| Tables_in_sample |
+------------------+
| name |
+------------------+
1 row in set (0.00 sec)
mysql>
参考
https://qiita.com/juhn/items/274e44ee80354a39d872
https://noumenon-th.net/programming/2019/04/01/docker-entrypoint-initdb01/