Overview and What You Will Learn
Docker networking decides which containers can talk to each other, to the host, and to the internet. Every container joins a network, and the network driver determines isolation, addressing and name resolution. Most connectivity bugs come from one of three causes: the containers are on different networks, the default bridge is being used (it has no name resolution), or a port was never published.
In this lab you will:
- Compare the bridge, host, overlay and none drivers and know when to pick each
- See why the default bridge cannot resolve container names and a user-defined bridge can
- Publish ports safely and understand what Docker does to iptables
- Isolate tiers with internal networks and debug failures with a repeatable checklist
Why This Matters in Production
Most "the app cannot reach the database" incidents are not code bugs, they are network placement mistakes. A payments team running on a single host such as mumbai-prod-node-1 typically puts the API, database and metrics agent on separate user-defined networks so a compromised front end cannot reach the database directly. Knowing which layer failed (DNS, network membership, port publishing or firewall) turns a one hour guessing session into a two minute check.
Core Principles
A Docker network driver is the component that creates the virtual network a container attaches to. The driver you choose sets the scope (one host or many), the isolation level, and whether containers can find each other by name.
| Driver | Best for |
|---|---|
bridge (user-defined) |
Multi-container apps on one host, with automatic DNS |
bridge (default docker0) |
Quick throwaway tests only, no name resolution |
host |
Agents and latency-critical tools that need the host stack |
overlay |
Multi-host networking with Swarm |
none |
Fully isolated batch or data-processing jobs |
Docker also ships macvlan and ipvlan for giving containers addresses on the physical LAN, which you only need for legacy systems that expect a real IP.
On a user-defined bridge, Docker runs an embedded DNS server at 127.0.0.11 inside each container. It resolves container names and network aliases to current IP addresses, so restarts never break connectivity.
127.0.0.11 participant DB as postgres API->>DNS: resolve postgres DNS-->>API: 172.18.0.3 API->>DB: connect on 5432 DB-->>API: query results
Detailed Step-by-Step Practical Lab
Milestone 1: See Why the Default Bridge Fails
The default bridge network assigns private IPs but provides no name resolution, so containers can only reach each other by IP address, and that address changes when a container restarts. This milestone proves it.
docker run -d --name web alpine:3.20 sleep 3600docker run -d --name db alpine:3.20 sleep 3600 # Find the db container IP on the default bridgedocker inspect -f '{{.NetworkSettings.IPAddress}}' db# 172.17.0.3 # Name lookup fails on the default bridgedocker exec web ping -c 2 db# ping: bad address 'db' # IP works, but it is not stable across restartsdocker exec web ping -c 2 172.17.0.3 # Clean updocker rm -f web dbMilestone 2: Use a User-Defined Bridge with DNS
A user-defined bridge gives you automatic DNS, better isolation and the ability to attach or detach containers while they run. This is the correct default for any multi-container application.
# Create a network with an explicit subnetdocker network create \ --driver bridge \ --subnet 172.18.0.0/16 \ payment-network # Start a database and give it an extra DNS aliasdocker run -d \ --name postgres \ --network payment-network \ --network-alias db \ -e POSTGRES_PASSWORD=change-me-rahul \ postgres:15 # Start a client container on the same networkdocker run -d --name payment-api --network payment-network alpine:3.20 sleep 3600 # Both the container name and the alias resolvedocker exec payment-api ping -c 2 postgresdocker exec payment-api ping -c 2 dbdocker exec payment-api nslookup postgres # The resolver is Docker's embedded DNS serverdocker exec payment-api cat /etc/resolv.conf# nameserver 127.0.0.11 # Check the database port with a real protocol clientdocker run --rm --network payment-network postgres:15 pg_isready -h postgres -p 5432# postgres:5432 - accepting connections # Attach a running container to a second network, then detach itdocker network create monitoring-networkdocker network connect monitoring-network payment-apidocker network disconnect monitoring-network payment-apiMilestone 3: Publish Ports Deliberately
Publishing a port maps a host port to a container port so clients outside Docker can reach the service. Unpublished ports are reachable only from containers on the same network.
# Host 8080 -> container 80, on all host interfacesdocker run -d --name public-web -p 8080:80 nginx:1.25 # Bind to localhost only, for admin UIs that must not be publicdocker run -d --name admin-ui -p 127.0.0.1:8081:80 nginx:1.25 # Show the mappingsdocker port public-web# 80/tcp -> 0.0.0.0:8080 # Docker implements this with iptables DNAT rulessudo iptables -t nat -L DOCKER -n --line-numbersSecurityDocker writes its own iptables rules, so a published port can bypass host firewalls such as
ufw. A rule that says "deny 8080" may not block-p 8080:80. Bind internal services to127.0.0.1and put real filtering in the cloud security group or theDOCKER-USERchain.
Milestone 4: Use Host Networking Only When Needed
Host mode removes the network namespace boundary, so the container shares the host IP and ports directly. It avoids NAT overhead but gives up isolation and causes port conflicts.
# nginx now listens directly on host port 80, no -p neededdocker run -d --name host-nginx --network host nginx:1.25 # Confirm on the hostss -tulpn | grep ':80 ' # -p flags are ignored in host mode, Docker prints a warningdocker rm -f host-nginxGood uses are node-level monitoring agents and network tooling. Avoid it for ordinary application services. It works on Linux only: on Docker Desktop for macOS and Windows, "host" means the internal VM, not your laptop.
Milestone 5: Isolate Tiers with Separate and Internal Networks
Containers on different networks cannot reach each other at all, which is the simplest and most effective isolation primitive. An internal network additionally blocks outbound internet access.
# Frontend can reach the internet, backend cannotdocker network create frontend-networkdocker network create --internal backend-network # The API sits on both networks and bridges the tiersdocker run -d --name api --network frontend-network alpine:3.20 sleep 3600docker network connect backend-network api # The database only lives on the internal networkdocker run -d --name ledger-db --network backend-network \ -e POSTGRES_PASSWORD=change-me-rahul postgres:15 # Proof: a container on frontend-network cannot resolve ledger-dbdocker run --rm --network frontend-network alpine:3.20 nslookup ledger-db# server can't find ledger-db: NXDOMAINMilestone 6: Let Compose Build the Networks
Docker Compose creates a project network automatically and registers every service name in DNS, so services reach each other by name with no extra setup.
# compose.yamlservices: api: image: registry.razorpay.in/payment-api:v3.1.0 ports: - "127.0.0.1:8080:8080" environment: DB_HOST: postgres # service name resolves via Docker DNS networks: [frontend, backend] postgres: image: postgres:15 environment: POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: [db_password] networks: [backend] networks: frontend: backend: internal: true secrets: db_password: file: ./db_password.txtdocker compose up -ddocker compose exec api getent hosts postgresMilestone 7: Debug with a Repeatable Ladder
Work from the bottom up: is the container on the right network, does the name resolve, is the port open, then check the firewall. The netshoot image brings the diagnostic tools your slim containers lack.
# 1. Which networks is each container on?docker inspect -f '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}' apidocker inspect -f '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}' postgres # 2. Share the target container network namespace with a toolbox containerdocker run --rm -it --network container:api nicolaka/netshoot # Inside the toolboxnslookup postgres # does DNS resolve?nc -zv postgres 5432 # is the port open?curl -sv http://postgres:5432 # raw connection attempt # 3. If both are on the same network and it still fails, inspect the firewall rulessudo iptables -L DOCKER-ISOLATION-STAGE-1 -nsudo iptables -L FORWARD -nProduction Best Practices & Common Pitfalls
- Always create a user-defined network. Never rely on the default bridge for an application with more than one container.
- Connect by name, never by IP. Container IPs change on restart, names and aliases do not.
- Bind admin interfaces to
127.0.0.1. Use-p 127.0.0.1:port:portfor anything that should not be public. - Use
--internalnetworks for data tiers. Databases rarely need outbound internet access. - Keep host mode for agents. Application services belong on bridges with explicit port publishing.
- Avoid
-P. Random host ports make firewall rules and runbooks unmanageable.
Common MistakeHardcoding a container IP such as
172.17.0.3in application config. It works until the container restarts and receives a new address. Use the container name, a network alias, or the Compose service name.
TipWhen two containers cannot connect, compare their network lists first. The most common root cause is simply that they are not on a shared network.
RememberDNS by container name exists only on user-defined networks. The default bridge never provides it.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker network ls |
List networks and drivers |
docker network inspect payment-network |
Show subnet, gateway and attached containers |
docker network connect NET CONTAINER |
Attach a running container to a network |
docker network disconnect NET CONTAINER |
Detach a container from a network |
docker port CONTAINER |
Show published port mappings |
docker network prune |
Remove unused networks |
| Symptom | Likely cause and fix |
|---|---|
bad address 'db' |
Default bridge or different network, use a shared user-defined network |
| Connection refused on a known port | App bound to 127.0.0.1 inside the container, bind to 0.0.0.0 |
| Port reachable from outside despite firewall | Docker iptables bypass, bind to localhost or filter in DOCKER-USER |
| Name resolves but connection times out | Network is --internal or a security group blocks the host |