[英]Accessing a Docker MySQL server from the host machine, without needing the container's IP address
I'm writing setup instructions for an application needing a MySQL database, and I'd like it to be easy even for people that don't have a MySQL installation. 我正在为需要MySQL数据库的应用程序编写设置说明,即使没有安装MySQL的人也希望它很容易。
Therefore, I'd like to run the MySQL server in a container: 因此,我想在一个容器中运行MySQL服务器:
docker run -p 3306:3306 \
--name mysql \
-e MYSQL_ROOT_PASSWORD=test \
-e MYSQL_DATABASE=my_db \
-d mysql
And to be able to connect to it this way: 为了能够以这种方式连接到它:
mysql -u root -ptest -D my_db
Which doesn't work because the MySQL server only listens locally on the container. 这是行不通的,因为MySQL服务器仅在容器上本地侦听。
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
So I see three options, none of which fitting my needs: 因此,我看到了三个选择,没有一个可以满足我的需求:
1) Using the container IP everytime 1)每次使用容器IP
mysql -u root -ptest -D my_db -h 172.17.0.4
Annoying, the IP will often change and I don't want people to have to update their configuration this much. 令人讨厌的是,IP经常会改变,我不希望人们这么多地更新其配置。
2) Changing the configuration of MySQL inside the container 2)更改容器内MySQL的配置
Requires to run a docker exec ...
each time the container is run, so it's annoying as well. 每次运行容器时都需要运行
docker exec ...
,这也很烦人。
3) Making a custom image where the configuration suits my needs 3)在适合我需要的配置下制作自定义映像
Seems a bit overkill, I'm pretty sure there is a better solution. 似乎有些矫kill过正,我敢肯定有更好的解决方案。
Thoughts? 有什么想法吗?
When the mysql
client is invoked as you did: 当像您一样调用
mysql
客户端时:
mysql -u root -ptest -D my_db
(ie without the hostname) or with localhost
as hostname it tries to connect to the local server using Unix pipes. (即没有主机名)或以
localhost
作为主机名,它尝试使用Unix管道连接到本地服务器。 A pipe is a special file type and the client communicate with the server through it. 管道是一种特殊的文件类型,客户端通过它与服务器进行通信。
Your MySQL server is not local, it runs on a separate machine. 您的MySQL服务器不在本地,而是在单独的计算机上运行。 You cannot connect to it using pipes.
您不能使用管道连接到它。
As you already noticed, it works if you use the IP address of the container as argument for the -h
command line option of mysql
. 正如您已经注意到的,如果您将容器的IP地址用作
mysql
的-h
命令行选项的参数,则该方法有效。
You also map the port 3306
of the container to port 3306
of the host machine. 您还将容器的端口
3306
映射到主机的端口3306
。 This means any TCP connection to port 3306
of the local machine goes through this mapping to the port 3306
of the container, where the MySQL server is listening. 这意味着到本地计算机端口
3306
的任何TCP连接都通过此映射到达MySQL服务器正在侦听的容器的端口3306
。
Combining the two above, all you have to do is to put 127.0.0.1
as host name in the mysql
command line: 结合以上两者,您要做的就是将
127.0.0.1
作为主机名放在mysql
命令行中:
mysql -u root -ptest -D my_db -h 127.0.0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.