LoginSignup
1
4

More than 5 years have passed since last update.

Docker-Composeを用いたMySQL5.7環境構築

Last updated at Posted at 2019-01-14

Docker-Composeとは?

複数のコンテナをyaml形式のファイルで一括管理できる優れもの。

公式ドキュメント
http://docs.docker.jp/compose/toc.html

サンプルコード&解説

ファイル構造

docker-compose.ymlにコンテナの設定について記載されている。
dataにはストレージとして使用するコンテナのDockerfileが、
initにはDBの初期データ(.sql)が配置されている。

.
├── README.md
├── data
│   └── Dockerfile
├── docker-compose.yml
└── init
    └── Member.sql

docker-compose.yml

db-storageがData Volumeコンテナ。
データを保持するためだけのコンテナである。
DBのイメージはmysql:5.7を使用。
先ほどのストレージコンテナ上のボリュームをマウントしている。
また、イメージの/docker-entrypoint-initdb.dにsqlファイルを配置するとコンテナ起動時に実行される為、初期データ作成用のsqlファイルを配置している。

version: '3'
services:
  db-storage:
    build: ./data
    volumes:
      - /var/lib/mysql
  db:
    image: mysql:5.7
    ports:
      - 3306:3306
    environment:
        MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
        MYSQL_DATABASE: sample
        MYSQL_USER: example
        MYSQL_PASSWORD: example
    volumes:
      - ./init:/docker-entrypoint-initdb.d
    volumes_from:
      - db-storage

./data/Dockerfile

Data VolumeコンテナのDockerfile。
busyboxというイメージをしている。
centosやubuntuでも問題ないが、busyboxの方がOSとして軽量なため、
今回のようなデータ保持の為のコンテナにはbusyboxを使用した方が良い。

FROM busybox

VOLUME /var/lib/mysql

CMD ["bin/true"]

./init/Member.sql

初期データ作成用のsqlファイル。

USE sample;

CREATE TABLE member
(
    id INT(10),
    name VARCHAR(40),
    age INT(10),
    sex VARCHAR(40)
);

INSERT INTO member
    (id, name, age, sex)
VALUES
    (1, "Nagaoka", 20, "man");
INSERT INTO member
    (id, name, age, sex)
VALUES
    (2, "Tanaka", 30, "man");
INSERT INTO member
    (id, name, age, sex)
VALUES
    (3, "Matsumoto", 25, "woman");

使用例

$ docker-compose up -d
Creating mysql_db-storage_1_6c5a6bdc1e4e ... done
Creating mysql_db_1_b086ce193c2a         ... done
$ mysql -u root -p --host=127.0.0.1
mysql: [Warning] World-writable config file '/usr/local/etc/my.cnf' is ignored.
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.24 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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>
mysql> select * from sample.member;
+------+-----------+------+-------+
| id   | name      | age  | sex   |
+------+-----------+------+-------+
|    1 | Nagaoka   |   20 | man   |
|    2 | Tanaka    |   30 | man   |
|    3 | Matsumoto |   25 | woman |
+------+-----------+------+-------+
3 rows in set (0.00 sec)

参考

MySQL公式Dockerイメージ
https://hub.docker.com/_/mysql/

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4