LoginSignup
11
5

More than 3 years have passed since last update.

【Docker-compose】MySQLの環境構築

Last updated at Posted at 2019-11-12

なぜDocker-composeなのか?

他のコンテナと合わせて使用することを考えdocker-composeにしました。

構成

├── docker-compose.yml
├──.env
└── mysql
    └── initdb
        ├── 1_create_tables.sql
        └── 2_insert_seed.sql

docker-compose.yml

今回はブラウザからもアクセスできるようにしてMySQLをGUIでも操作できるようにしました。

docker-compose.yml
version: '3'

services:
  mysql:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    env_file: .env
    environment:
      TZ: "Asia/Tokyo"

    ports:
      - 3306:3306
    volumes:
      - mysql:/var/lib/mysql
      - ./mysql/initdb:/docker-entrypoint-initdb.d

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    restart: always
    ports:
      - 8080:80
    environment:
      PMA_ARBITRARY: 1
    env_file: .env
    depends_on:
      - mysql

volumes:
  mysql:

.env

docker-compose.ymlファイルに書くこともできますが分けた方がいいと思います!

MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_db
MYSQL_USER: test
MYSQL_PASSWORD: test

PMA_HOST: mysql
PMA_USER: root
PMA_PASSWORD: root

初期化用sqlファイル

以下のファイルはあくまで一例です。
自由に書き換えて使用してください。

1_create_tables.sql

1_create_tables.sql
create table users
(
    id serial primary key,
    username varchar(50) unique not null,
    password varchar(50) not null,
    email varchar(255) unique not null
);

2_insert_seed.sql

2_insert_seed.sql
insert into users (username, password, email) values ('keid', 'keidpass', 'keid@developer.com');
insert into users (username, password, email) values ('jobs', 'jobspass', 'jobs@developer.com');
insert into users (username, password, email) values ('mask', 'maskpass', 'mask@developer.com');

起動

docker-compose.ymlファイルのあるディレクトリに移動してください

docker-compose up -d

コンテナに入ってMySQLを起動

docker-compose exec mysql bin/bash

root@30bffee726ff:/# mysql -u test -p
Enter password: test # 入力しても表示されません
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.18 MySQL Community Server - GPL

Copyright (c) 2000, 2019, 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>

phpMyAdminからアクセス

ブラウザなどからlocalhost:8080でphpMyAdminにアクセスできます。

まとめ

今回はDockerをやって欲しいというリクエストがありましたのでdocker-composeを使用してMySQL環境を構築してみました。
一人でも多くのクジラ信者が増えるようにdockerの良さが伝わればいいなと思います!!

11
5
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
11
5