前提
$ mysql --version
mysql Ver 8.0.28 for macos12.2 on x86_64 (Homebrew)
$ docker run --rm mysql mysql --version
mysql Ver 8.0.29 for Linux on x86_64 (MySQL Community Server - GPL)
手順
DockerでMySQLサーバを起動する。
$ docker run --rm -p 3306:3306 -e MYSQL_ROOT_PASSWORD=<rootのパスワード> mysql
ローカルのmysqlクライアントからTCPでサーバに接続する。
$ mysql --protocol=TCP -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.29 MySQL Community Server - GPL
Copyright (c) 2000, 2022, 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>
なぜ--protocol=TCP
を指定するのか
mysql
はデフォルトでlocalhostに接続しようとし、localhostに接続するときはデフォルトでUnixドメインソケットを使おうとする。しかしDockerとホストでファイルシステムが分かれているので、次のエラーになる。
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
そこで、プロトコルを明示的にTCPに設定して、暗黙のうちにUnixドメインソケットが使われることを回避する。
参考
-
MySQL :: MySQL 8.0 Reference Manual :: 4.2.4 Connecting to the MySQL Server Using Command Options
- "The default host name is localhost"とあるので、
mysql
の--host
オプションのデフォルト値もlocalhostになる
- "The default host name is localhost"とあるので、
-
MySQL :: MySQL 8.0 Reference Manual :: 4.5.1.1 mysql Client Options
-
--socket
オプションに渡す値の説明に"For connections to localhost, the Unix socket file to use"と書いてあるので、localhostに接続するときはデフォルトでUnixドメインソケットを使うと解釈できる -
--protocol
オプションに渡すことができる値としてTCP
やSOCKET
がある
-
- mysql locahost の接続では、unix socket かTCPかを明示しないとsock エラーで混乱した - それマグで!