简体   繁体   English

如何在没有端口冲突的情况下将 mysql 端口从主机绑定到 docker 容器

[英]How to bind mysql port from host to docker container without port clash

I have a docker container running a Flask application that connects to a mySQL server.我有一个运行连接到 mySQL 服务器的 Flask 应用程序的 docker 容器。 The mySQL server is hosted on the host machine at port 3308 on a windows 10 machine. mySQL 服务器托管在主机上,位于 Windows 10 机器上的端口 3308。

When executing docker run -p 5000:5000 -p 3308:3308 -t webui执行docker run -p 5000:5000 -p 3308:3308 -t webui

I receive the error Ports are not available: listen tcp 0.0.0.0:3308: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.我收到错误Ports are not available: listen tcp 0.0.0.0:3308: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted. due to the port being used by the mySQL server on the host machine由于主机上的 mySQL 服务器正在使用该端口

How do I map the port of the mySQL to the docker container such that the Flask application can access the database?如何将 mySQL 的端口映射到 docker 容器,以便 Flask 应用程序可以访问数据库?

There are 2 ways to achieve this.有两种方法可以实现这一点。 The first approach is the recommended one.第一种方法是推荐的方法。

The first is to add an entry to /etc/hosts inside the container:首先是在容器内的 /etc/hosts 添加一个条目:

docker run -p 5000:5000 -p 3308:3308 --add-host database:<HOST_IP> -t webui

You need to replace HOST_IP with the network IP of your host.您需要将 HOST_IP 替换为您主机的网络 IP。 Then you can reference the database inside your container using the name "database" (you can also customize this one).然后,您可以使用名称“database”(您也可以自定义此名称)来引用容器内的数据库。

The second is to bind your container to your host's interface:第二个是将您的容器绑定到您主机的接口:

docker run -p 5000:5000 -p 3308:3308 --bind 127.0.0.1 -t webui

Then you can refer to your database with 127.0.0.1 inside your container.然后您可以在容器内使用 127.0.0.1 引用您的数据库。

The issue was caused by the host name.问题是由主机名引起的。 The mySQL database port did not need to be bound to the container as it did not need to receive any inbound calls, only outbound to the database. mySQL 数据库端口不需要绑定到容器,因为它不需要接收任何入站调用,只需要出站到数据库。 Resolved by adding a new entry into the container's /etc/hosts file as described here .通过在容器的 /etc/hosts 文件中添加一个新条目来解决,如here所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM