LoginSignup
0
1

Docker composeでMySQLのコンテナを複数同時に起動する場合のポート設定

Posted at

はじめに

Docker ComposeでMySQLのコンテナを複数同時に起動して作業したいことがあったのですが、その際にうまくいかなかったので備忘録として残しておきます。

MySQLのコンテナ

docker-compose.yml
version: "3.9"
volumes:
  db-store:
services:
  db:
    build:
      context: .
      dockerfile: ./infra/docker/mysql/Dockerfile
    ports:
      - 3306:3306
    volumes:
      - type: volume
        source: db-store
        target: /var/lib/mysql
        volume:
          nocopy: true
    environment:
      - MYSQL_DATABASE=${DB_DATABASE}
      - MYSQL_USER=${DB_USERNAME}
      - MYSQL_PASSWORD=${DB_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${DB_PASSWORD}

事象

2つ目のコンテナを起動する際、MySQLのポート番号がそれぞれ通常の3306のままだった場合、以下のようなエラーが表示されます。

$ docker compose up -d
 ⠿ Container container-db-1   Starting
Error response from daemon: driver failed programming external connectivity on endpoint container-db-1 (...): Bind for 0.0.0.0:3306 failed: port is already allocated
make: *** [up] Error 1

ポート番号が被っているのでそれは確かに接続できないですよね。

対処:ホスト側のポート番号を変更

そこでホスト側のポート番号を3307へ変更します。

docker-compose.yml
    ports:
      - 3307:3306

コンテナが起動できました。

$ docker compose up -d
 ⠿ Container container-db-1   Started

試しにSequel Aceで接続

しかし、データベース管理アプリのSequel Aceで接続しようとすると、エラーが出てしまいました。

Connection failed!

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently 10 seconds).

MySQL said: Lost connection to MySQL server at 'reading initial communication packet', system error: 0
Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Sequel Aceの設定値は以下の通りです。

項目名 設定値
Host 127.0.0.1
Username MYSQL_USERの値を入力
Password MYSQL_PASSWORDの値を入力
Database MYSQL_DATABASEの値を入力
Port 3307

対処:コンテナ側のポート番号を変更

結局、コンテナ側のポート番号も3307に変更してホスト側と合わせました。

docker-compose.yml
    ports:
      - 3307:3307

Sequel Aceでも接続できました。
ひとまずこれで複数同時に起動して利用することができました。

0
1
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
1