Docker : How to find the network my container is in?

Solution 1:

To see what network(s) your container is on, assuming your container is called c1:

$ docker inspect c1 -f "{{json .NetworkSettings.Networks }}"

To disconnect your container from the first network (assuming your first network is called test-net):

$ docker network disconnect test-net c1

Then to reconnect it to another network (assuming it's called test-net-2):

$ docker network connect test-net-2 c1

To check if two containers (or more) are on a network together:

$ docker network inspect test-net -f "{{json .Containers }}"

Solution 2:

  1. The network is visible in the docker container inspect $id output, where $id is the container id or container name. The name is listed under the NetworkSettings -> Networks section.

  2. You can use docker network connect $network_name $container_name to add a network to a container. And similarly, docker network disconnect $network_name $container_name will disconnect a container from a docker network.

  3. Containers can ping each other by IP address if they are on the same docker network and you have not disabled ICC. If you are not on the default network named "bridge" you can use the included DNS discovery to ping and connect to containers by container name or network alias. Any new network you have created with docker network create $network_name has the DNS discovery turned on, even if it's using the bridge driver, it just needs to be separate from the one named "bridge". Containers can also connect over TCP ports, even without exposing or publishing ports in docker, as long as they are on the same docker network.

Here's a low level example of testing a network connection with netcat:

$ docker network create test-net

$ docker run --net test-net --name nc-server -d nicolaka/netshoot nc -vl 8080
17df24cf91d1cb785cfd0ecbe0282a67adbfe725af9a1169f0650a022899d816

$ docker run --net test-net --name nc-client -it --rm nicolaka/netshoot nc -vz nc-server 8080
Connection to nc-server 8080 port [tcp/http-alt] succeeded!

$ docker logs nc-server
Listening on [0.0.0.0] (family 0, port 8080)
Connection from nc-client.test-net 37144 received!

$ docker rm nc-server
nc-server

$ docker network rm test-net

Solution 3:

I required a quick test to validate what containers were connected to my custom bridge to troubleshoot a connectivity issue between containers. The below test can answer both the 1st & 3rd parts of the OP's question:

docker network inspect bridge my-bridge | grep IPv4Address

or by containerName:

docker network inspect bridge my-bridge | grep Name

The results will reveal all the containers joined to the specified bridge.

As for the 2nd part of the OP's question, I refer the reader to @johnharris85 's excellent answer.