LoginSignup
0
0

More than 3 years have passed since last update.

DockerでMySQLコンテナを立ち上げ~実行確認

Last updated at Posted at 2020-07-29

Dockerのお勉強シリーズその1(続く予定)

を参考にやってみたことのメモ。

最終的には
frontend + backend + db
の構成を作りたいの第一歩

実行環境

  • Windows 10
  • DockerDesktop for Windows

ディレクトリ構成

.
├── docker-compose.yml
└── mysql
    ├── conf.d
    ├── initdb.d
    │   ├── schema.sql
    │   └── testdata.sql
    └── log

docker-compose.yml

version: '3.3'
services:
  db:
    image: mysql:latest
    restart: always
    volumes:
      - .\mysql\initdb.d:/docker-entrypoint-initdb.d
      - .\mysql\conf.d:/etc/mysql/conf.d
      - .\mysql\log\ysql:/var/log/mysql
    environment:
      MYSQL_DATABASE: sample_db
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: rootpassword
    ports:
      - 3306:3306

テーブル定義&初期データ

mysql/init.dにテーブル定義と投入する初期データのファイルを作成する

schema.sql
CREATE TABLE Comment
(
        id int NOT NULL AUTO_INCREMENT,
        title varchar(32) NOT NULL,
        category varchar(32) NOT NULL,
        content varchar(256) NOT NULL,
        PRIMARY KEY(id)
);
testdata.sql
INSERT INTO Comment (title, category, content) VALUES ('curry', 'food', 'good');
INSERT INTO Comment (title, category, content) VALUES ('poteto', 'vegitable', 'good');
INSERT INTO Comment (title, category, content) VALUES ('onion', 'vegitable', 'bad');
INSERT INTO Comment (title, category, content) VALUES ('poak', 'meat', 'very good');

コンテナ起動&確認

docker-compose upでコンテナ起動

$ docker-compose up -d

docker execで起動したコンテナに入り、mysqlに接続。
テストデータが入っていることまで確認。

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
f225c6620b90        mysql:latest        "docker-entrypoint.s…"   11 minutes ago      Up 11 minutes       0.0.0.0:3306->3306/tcp, 33060/tcp   webapp_db_1
$ docker exec -it f225c6620b90 bash
# mysql --user=user --password=password
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| sample_db          |
+--------------------+
mysql> show tables;
+---------------------+
| Tables_in_sample_db |
+---------------------+
| Comment             |
+---------------------+
1 row in set (0.00 sec)

mysql> select * from Comment;
+----+--------+-----------+-----------+
| id | title  | category  | content   |
+----+--------+-----------+-----------+
|  1 | curry  | food      | good      |
|  2 | poteto | vegitable | good      |
|  3 | onion  | vegitable | bad       |
|  4 | poak   | meat      | very good |
+----+--------+-----------+-----------+
4 rows in set (0.01 sec)
0
0
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
0
0