[Docker] 用 mysql 指令,連不上用 Docker 做的 MySQL server 容器?

[Docker] 用 mysql 指令,連不上用 Docker 做的 MySQL server 容器?

今天在 Ubuntu 上,用 docker 跑了一個 MySQL server 容器 (container):

docker run -d --name mysql8 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=myPassword mysql:8

 

結果想用 mysql 指令去連這個 MySQL server,卻出現錯誤訊息,

說無法透過 socket /var/run/mysqld/mysqld.sock 連上 MySQL server:

$ mysql -h localhost -u root -pmyPassword

mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

 

但明明 MySQL server 就有好好的跑在 docker 裡,

而且 port forwarding 也有開呀?

 

爬文了一下,原來用 localhost 的話,

mysql 會直接用 socket (我想應該是指 unix domain socket) 去連。

改用 127.0.0.1 時,就會用 TCP/IP socket 去連,

這才有辦法連上 docker 裡的 MySQL server,

畢竟我們平常從外面是碰不到容器裡的 unix domain socket 的:

$ mysql -h 127.0.0.1 -u root -pmyPassword@1 -P 3306

mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
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>

 

真沒想到平常的 localhost 和 127.0.0.1 可以互換,

卻在這種小地方,會造成不同的效果呀~

 

參考資料:Can’t connect to local MySQL server through socket

(本頁面已被瀏覽過 246 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料