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

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


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 alpineRUN 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.


You can simply run the container with network mode equal to host.

docker run --network=host ...

In that case, from the container point of view, localhost or 127.0.0.1 will refer to the host machine. Thus if your db is running in another container B that listens on 3306, an address of localhost:3306 in container A will hit the database in container B.


If you want container B's port to be exposed as a localhost port on container A you can start container B with the network option set to container mode to start container B on container A's network namespace.

Example:

docker run --net=container:A postgres

Where:

  • A is the name or identifier of the container you want to map into.

This will startup postgres in a container on the same network namespace as A, so any port opened in the postgres container will be being opened on the same interface as A and it should be available on localhost inside container A.