Mirror or forward network traffic from one container to another container

Hello,

Is that possible to mirror or forward traffic from container-A to container-B?

For example, I have 2 containers in the same docker network:

Container-APP, the IP is 172.0.0.1
Container-MySQL, the IP is 172.0.0.5

I would like to forward container-A 127.0.0.1:30000 to container-B port 3306
So I can find Container-MySQL when I run the command mysql -u root -p -h 172.0.0.1 --port=30000 in the Container-APP

You could try socat (https://www.cyberciti.biz/faq/linux-unix-tcp-port-forwarding/) but do you really want to forward port or just have two containers and still access the mysql server running in an other container without knowing its IP address? If this is the case, you can share network namespaces. Example:

docker run --name mysql ...
docker run --name app --network container:mysql ...

It would be easier with Docker Compose using the network_mode parameter. This way the localhost of the app container would be the same as the localhost of the mysql container. This also means you would need to publish the ports of the app container (if it is necessary) on the mysql container, not on the app container.

1 Like