CodeBlanks Logo Icon CodeBlanks

Container connectivity

Learn how containers on the same network communicate.

Connecting containers

A running container can be connected to other networks later or removed from a network; a container can be on several networks at once. This is used, for example, to temporarily put a debugging tool into the back-end network:

docker network connect arka api
docker network disconnect arka api
docker inspect -f '{{range $ad, $_ := .NetworkSettings.Networks}}{{$ad}} {{end}}' api
# on arka

Alias

--network-alias gives the container an extra DNS name inside the network. Several containers can carry the same alias; the DNS query returns all their IPs (simple load distribution):

docker run -d --network uygulama-agi --network-alias arama elasticsearch:8.15.0
docker run -d --network uygulama-agi --network-alias arama elasticsearch:8.15.0
docker run --rm --network uygulama-agi alpine nslookup arama   # two addresses

Practice Join and leave

Write three commands: connect the running api container to the arka network; run ping -c 1 db inside api; then disconnect api from the arka network.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker network connect arka api
docker exec api ping -c 1 db
docker network disconnect arka api

Expected output

PING db (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.098 ms

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If a container is attached to two networks, which containers can it reach?

  • Only the host
  • Containers on both networks Correct answer
  • Only those on the first network
  • None

Explanation: It gets a separate interface and IP for each network.

2 Connect a running container to a network.

Question
docker network ____ arka api
Answer
docker network connect arka api

Explanation: connect is written in network container order.

3 Match.

Term Meaning
network connect Join a network
network disconnect Leave a network
--network-alias Extra DNS name
nslookup DNS query

All lessons in Beginner