Browse topics

User-defined bridge networks

Version
29
Review
Draft

Summary#

Containers on the same user-defined bridge network can reach each other by container name or network alias. The default bridge network lacks automatic container-name resolution.

Syntax#

sh
docker network create NETWORK
docker run --network NETWORK --network-alias ALIAS IMAGE
docker network connect NETWORK CONTAINER
docker network disconnect NETWORK CONTAINER
docker network rm NETWORK

Example#

The example uses a local busybox:1 image.

sh
(
  set -eu
  id="dlr-docker-commands-net-$$"
  trap 'docker rm -f "$id-web" "$id-client" >/dev/null 2>&1 || true; docker network rm "$id" >/dev/null 2>&1 || true' EXIT

  docker network create --label "dlr-docker-commands-net=$$" "$id" >/dev/null
  docker run --pull never --detach --name "$id-web" --network "$id" --network-alias web busybox:1 \
    sh -c 'echo "hello over the network" > /tmp/index.html; exec httpd -f -p 8080 -h /tmp' >/dev/null

  tries=0
  until reply=$(docker run --pull never --rm --name "$id-client" --network "$id" \
    busybox:1 wget -qO- http://web:8080/ 2>/dev/null); do
    tries=$((tries + 1))
    [ "$tries" -lt 30 ]
    sleep 1
  done
  echo "$reply"
  docker run --pull never --rm --name "$id-client" --network "$id" \
    busybox:1 wget -qO- "http://$id-web:8080/"

  if ! docker run --pull never --rm --name "$id-client" busybox:1 \
    ping -c 1 -W 1 "$id-web" >/dev/null 2>&1; then
    echo "default bridge: name not reachable"
  fi
  docker network inspect --format 'driver: {{.Driver}}' "$id"
)

Expected output#

Text
hello over the network
hello over the network
default bridge: name not reachable
driver: bridge

Common mistakes#

Inside a container, localhost is that container. Connect to another service by its name or alias and the port it listens on inside the container, not the published host port. The server must also listen on more than its loopback interface.

Version applicability#

Checked with Docker Engine 29. These names apply to containers on one Docker daemon. A bridge network does not connect containers on different hosts.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0