Home > database >  Replicate Dockers network mode `container:<name>` with a user created network
Replicate Dockers network mode `container:<name>` with a user created network

Time:09-01

So lets say I have 2 containers that needs to share the same network. I can do this

docker run some_image

and then do

docker run --network=container:some_image another_image

another_image would now join the same IPC namespace as some_image.

But could one replicate this by a pre-defined network?

Say like:

docker network create my_network

then

docker run --network=my_network some_image
docker run --network:my_network another_image

Are these the same thing? Or is it possible to replicate the first option but first create a common network?

CodePudding user response:

They are both valid approaches and they work. Using --network container:name makes your intentions clear: you want to be on the same network as the other container. And this helps the readers of your code.

Of course you can maybe achieve the same by calling the network common_network_container1_container2 but I find it uglier. It's a matter of style in the end.

CodePudding user response:

Are these the same thing?

No. The first case spawns one network for all containers spawned from the image on docker run some_image to connect to. When using --network container:<container_name>, containers use that container's network stack as their own (I.E: they share the same "hardware" and network config, you can verify that by running hostname inside both containers). The documentation offers a good example of the effect this produces. Notice how both processes communicate through each other through the localhost interface.

On the other hand, when using user-defined networks, containers can connect to it and communicate with other container's through their names (hostname) or IPs. That is, there is no shared network stack and each container is an isolated host in the network.

But could one replicate this by a pre-defined network?

Yes, you could issue the following commands so that your containers all share the network stack:

docker network create foobar
docker run --network=foobar --name container1 some_image
docker run --network=container:container1 another_image

Inside both containers, running hostname would yield the same value.

  • Related