Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Allow communication on specific ports between two Docker containers on different bridge networks

Preface: This question is similar to Allow communication between two docker bridge networks using docker-compose but that question is 4+ years old so I felt it best to ask a new question.

I have two bridge networks and two containers, one on each network. I am trying to figure out how to make a port on one container available to another container.

$ docker network create net1
$ docker network create net2

$ docker run -it -d --net=net1 --name container1 -p 1234:80 ....
$ docker run -it -d --net=net2 --name container2 -p 5678:80 ....

Now, I'd like container1 to be able to make a call to container2:80 and container2:4321 but I am not sure how to do that.

I am trying to do this without using the macvlan driver.


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

1 Answer

0 votes
by (71.8m points)

I have a lesser restriction in my case where I open up certain port numbers in all containers. The containers communicate with each other by using the host IP and the exposed port number.

In my case, on top connecting to the custom network, I also connect the containers to the default bridge network. The default network does not allow communication between the containers.

Then in iptables, I create a new pipeline and pipe docker0 (the bridge network) to it

-F FILTERS
-A DOCKER-USER -i docker0 -o docker0 -j FILTERS

And allow the whitelisted port numbers

-A FILTERS -p tcp --dport 1234 -m state --state NEW -j ACCEPT -m comment --comment container1
-A FILTERS -p tcp --dport 5678 -m state --state NEW -j ACCEPT -m comment --comment container2

You can try tightening the restriction, by

  • not connecting the default bridge network
  • finding the network interface of net1 and net2 via ip link show and ifconfig
  • changing the pipeline to
-F CONTAINER1-CONTAINER2
-F CONTAINER2-CONTAINER1
-A DOCKER-USER -i br-xxxx -o br-yyyy -j CONTAINER1-CONTAINER2
-A DOCKER-USER -i br-yyyy -o br-xxxx -j CONTAINER2-CONTAINER1
  • Modifying the port list to
-A CONTAINER2-CONTAINER1 -p tcp --dport 1234 -m state --state NEW -j ACCEPT -m comment --comment container1
-A CONTAINER1-CONTAINER2 -p tcp --dport 5678 -m state --state NEW -j ACCEPT -m comment --comment container2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...