ジャコ Lab

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

Docker で立てた MySQL に接続できなかった件

以下のエラーが出てしまいます
$ mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
調べます...

docker-compose.yml の確認

services:
  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 ps
NAME      IMAGE          COMMAND                   SERVICE   CREATED         STATUS         PORTS
mysql     mysql:latest   "docker-entrypoint.s…"   mysql     5 seconds ago   Up 4 seconds   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp
コンテナ自体は立ってる

コンテナに潜って接続してみる

$ docker compose exec mysql bash

bash-5.1# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
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.

mysql> 
いけた、ということはホストからコンテナの MySQL へ接続ができていない

調べてみるとトランスポートプロトコルが影響しているっぽい

dev.mysql.com

トランスポートプロトコルが明示的に指定されていない場合、暗黙的に決定されます。 たとえば、localhost に接続すると、Unix および Unix に似たシステムでソケットファイル接続が行われ、それ以外の場合は 127.0.0.1 への TCP/IP 接続が行われます。
トランスポートプロトコルが明示的に指定されている場合localhost はそのプロトコルに関して解釈されます。 たとえば、--protocol=TCP では、localhost に接続すると、すべてのプラットフォームの 127.0.0.1TCP/IP 接続されます。

--protocol オプションで接続できるようになった
$ mysql -u root -p --protocol tcp
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
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.

mysql> 

その他、127.0.0.1 でも OK

ソケットファイル接続 ではなく TCP/IP 接続 であれば接続できるようなので、
以下のように -h 127.0.0.1 を指定しても接続できる

$ mysql -u root -p -h 127.0.0.1

コンテナの IP でも OK

bash-5.1# cat /etc/hosts
172.20.0.2  10f9947580ce
$ mysql -u root -p -h 172.20.0.2
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
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.

mysql> 

まとめ

localhost127.0.0.1って同じ扱いだと思ってた...