Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

portforwarding - How can I forward a port from one docker container to another?

I commonly see solutions that expose a docker container's port to the host.

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.

What is the best way to port-forward from A-localhost:3306 to B-IP:3306?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Install socat in your container and at startup run

socat TCP-LISTEN:3306,fork TCP:B-IP:3306 &

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

Edit-1

You can even do this by not touching your original container

Dockerfile

FROM alpine
RUN apk update && apk add socat

Build the file as below

docker build -t socat .

Now run a container from same

docker run --name mysql-bridge-a-to-b --net=container:<containerAid> socat socat TCP-LISTEN:3306,fork TCP:BIP:3306

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...