Docker: How do I find the network my container is on?

I am trying to understand something about Docker:

  1. How can I find the network my container is on?
  2. Can I dynamically detach my container and reconnect to a different network? How?
  3. If I have two containers running, how can I check if the two are on the same network? Can I ping one from the other?
+21


source to share


2 answers


To find out what network your container is on, assuming your container is named c1

:

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

      

To disconnect a container from the first network (if your first network is named 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 (or more) containers are online:

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

      

+35


source


  • The network is displayed in the output docker container inspect $id

    , where $id

    is the container ID or container name. The name is listed under NetworkSettings → Networks.

  • You can use docker network connect $network_name $container_name

    to add a network to a container. Likewise, docker network disconnect $network_name $container_name

    will disconnect the container from the docker network.

  • Containers can ping each other by IP if they are on the same docker network and you haven't disabled ICC. If you are not on the default network named "bridge", you can use the enabled DNS discovery to ping and connect to containers by container name or network alias. Any new network created with docker network create $network_name

    included DNS discovery, even if it uses a bridge driver, it just needs to be separated from the one called "bridge". Containers can also connect over TCP ports without even exposing or publishing ports in docker if they are on the same docker network.

Here's a low-level example of testing network connectivity 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

      

+7


source







All Articles