如何将端口从一个Docker容器转发到另一个? [英] How can I forward a port from one docker container to another?
问题描述
我通常会看到将docker容器的端口暴露给主机的解决方案.
I commonly see solutions that expose a docker container's port to the host.
就我而言,我想将本地端口从一个容器转发到另一个.假设我在容器A 上运行了具有硬编码配置的服务,以访问localhost 3306上的db .但是我想在容器B 上运行数据库服务器.
In my case I want to forward a local port from one container, to another. Let's say I run a service on container A that has a hard-coded configuration to access db on localhost 3306. But I want to run the db server on container B.
将从A-localhost:3306移植到B-IP:3306 的最佳方法是什么?
推荐答案
在容器中以及在启动运行时安装socat
Install socat
in your container and at startup run
socat TCP-LISTEN:3306,fork TCP:B-IP:3306 &
这将在您的3306上进行本地侦听,并将任何流量双向传递给B-IP:3306
. socat在名为socat的软件包中可用.因此,您将运行以下任何命令来安装它
This will listen locally on your 3306 and pass any traffic bidirectionally to B-IP:3306
. socat is available in package named socat. So you will run any of the below commands to install it
$ yum install -y socat
$ apt install -y socat
$ apk add socat
编辑1
您甚至可以通过不触摸原始容器来做到这一点
You can even do this by not touching your original container
Dockerfile
FROM alpine
RUN apk update && apk add socat
按如下所示构建文件
docker build -t socat .
现在从同一个容器运行
docker run --name mysql-bridge-a-to-b --net=container:<containerAid> socat socat TCP-LISTEN:3306,fork TCP:BIP:3306
这将在A的网络上运行此容器.因此,当它在A的网络上侦听时,即使未触摸A容器,localhost:3306
也将在A中变为可用.
This will run this container on A's network. So when it listens on A's network the localhost:3306
will become available in A even though A container was not touched.
这篇关于如何将端口从一个Docker容器转发到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!