ジャコ Lab

プログラミング関連のメモ帳的ブログです

Docker コンテナ間で MySQL にアクセスするには?

1つのコンテナ内に アプリケーションMySQL Server を同居させるのではなく、 アプリケーションコンテナから、別のコンテナ内の MySQL Server にアクセスする感じです。

イメージ図
イメージ図

こんなのをイメージしています。

docker-compose.yml にサービスを2つ用意すれば特に何も考えなくて良い

FROM python:3.11.10-slim-bullseye

RUN apt update -y
RUN apt install default-mysql-client -y
services:
  app:
    build:
      context: .
    container_name: app
    tty: true

  mysql:
    image: mysql:latest
    container_name: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db/data:/var/lib/mysql
    ports:
      - 3306:3306

docker compose を実行する

$ docker compose up -d
~省略~
[+] Running 3/3
 ✔ Network my_app_default  Created  0.3s 
 ✔ Container app           Started  1.5s 
 ✔ Container mysql         Started            

動作確認用に適当なDBを作成してみる

MySQL にログインする

$ mysql -h 127.0.0.1 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 9.0.1 MySQL Community Server - GPL

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

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.

zako-lab929.hatenablog.com

こちらで学んだホストからコンテナ内の MySQL に接続する手順です

データベースを作る

mysql> CREATE DATABASE my_db;
Query OK, 1 row affected (0.00 sec)

次に app コンテナ内から MySQL に接続してみる

app コンテナに潜る

$ docker compose exec app bash
root@9cba4888bf69:/#

app コンテナ内から MySQL へ接続する

root@9cba4888bf69:/# mysql -h mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 9.0.1 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

データベースを確認する

MySQL [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| my_db              |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.009 sec)
先ほど作った my_db が存在していることがわかります。

ホストから接続するときと異なる点としては、-h mysql なところです。
これは、コンテナ名です

IP アドレスなどの代わりにコンテナ名で接続ができるようになっています。

まとめ

docker-compose を使うと、docker comand のオプションを YAML で定義できるようになるので楽だと思っていましたが、コンテナ管理も楽になることがわかりました。