Creating Custom Networks

Manage your own networks with docker network create, connect and disconnect to control which containers can reach each other.

Syntaxdocker network create|connect|disconnect|rm NAME

Custom networks give you control over which containers can communicate. You can even segment an app so, for example, the frontend cannot reach the database directly.

The network commands

  • docker network create NAME — create a network.
  • docker network connect NET CONTAINER — attach a running container.
  • docker network disconnect NET CONTAINER — detach it.
  • docker network rm NAME — delete a network.
  • docker network prune — remove unused networks.

Multiple networks

A container can join several networks at once, letting you build tiers such as a public-facing network and a private backend network.

Example

Example · bash
# Create separate frontend and backend networks
docker network create frontend
docker network create backend

# api joins both; db only joins backend
docker run -d --name db --network backend postgres:16
docker run -d --name api --network backend myapi:1.0
docker network connect frontend api
# The frontend can reach api, but never db directly

When to use it

  • A team creates separate frontend and backend networks so the database is only reachable by the API container, not the frontend.
  • A platform engineer uses docker network create with a custom subnet to avoid conflicts with existing corporate VPN address ranges.
  • A developer disconnects a compromised container from the database network while keeping it running for forensic inspection.

More examples

Create a custom network with subnet

Creates a bridge network with an explicit subnet and gateway, useful when avoiding IP conflicts with VPNs.

Example · bash
docker network create \
  --driver bridge \
  --subnet 192.168.100.0/24 \
  --gateway 192.168.100.1 \
  my-custom-net

Connect and disconnect containers

Moves a container from one network to another while it is still running, without a restart.

Example · bash
# Connect running container to the new network
docker network connect my-custom-net myapp

# Disconnect it from the default bridge
docker network disconnect bridge myapp

Remove unused networks

Cleans up networks that are no longer needed to keep the Docker host tidy.

Example · bash
# Remove a specific network (no containers must be using it)
docker network rm my-custom-net

# Remove all networks not used by any container
docker network prune -f

Discussion

  • Be the first to comment on this lesson.