gpt4 book ai didi

mysql - 在cli中从主机访问mysql到容器

转载 作者:可可西里 更新时间:2023-11-01 07:56:06 25 4
gpt4 key购买 nike

我这样创建我的容器:

$ docker run -d -p 33060:3306 myimage

然后我尝试从主机连接到容器中的 mysql 服务器:

$ mysql -uroot -proot -P 33060

我遇到了这个错误:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

这很奇怪,因为只有在 Navicat 中我更改了端口并且工作正常: enter image description here

但是如果我有容器的IP:

$ docker inspect --format '{{ .NetworkSettings.IPAddress }}' mycontainer
172.17.0.55

然后就可以成功连接到mysql服务器了:

$ mysql -uroot -proot -h 172.17.0.55

但每次我创建一个新容器来连接到 mysql 时都必须检查 ip 是一项繁琐的任务。我可以做哪些设置来简化此任务?

最佳答案

这不是 Docker 问题。默认情况下,mysql 命令行客户端将连接到本地 (Unix) 套接字而不是网络套接字,即使您指定了 -P

此行为在 the documentation 中有所描述:

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given

你必须传递 -hlocalhost 选项,或者你可以在 /etc/mysql/my.cnf 中设置你的连接默认值

关于mysql - 在cli中从主机访问mysql到容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33175361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com