DockerIntermediate

Docker Networking: A Complete Guide to Container Communication

8 min read

TL;DR

Master Docker networking with this comprehensive guide covering network drivers, configuration, security, and best practices for container communication.

Docker Networking: A Complete Guide to Container Communication

Executive Summary

Docker networking decides which containers can talk to each other, which can be reached from outside, and how services find each other by name. This guide explains the built-in drivers (bridge, host, overlay, macvlan, and none), when each is appropriate, and how to design networks that enforce segmentation rather than merely describe it. It also covers embedded DNS service discovery, publishing ports safely, and a practical troubleshooting workflow using docker network inspect, connectivity tests, and traffic statistics. After reading, you should be able to look at a Compose file and predict exactly which communication paths exist.

Why This Matters

The default Docker network is permissive: containers on the same bridge can reach each other on every port. In real incidents this is how a vulnerability in a low-value service becomes a database breach, because nothing in the network design prevented the connection. The opposite failure is operational: services hardcoded to IP addresses that change on restart, published ports exposing admin interfaces to the internet, or multi-host applications deployed on a single-host bridge driver that can never work. Networking choices made casually in development tend to survive into production unchanged, so they deserve the same scrutiny as the application code.

Core Concepts

The Drivers and What Each One Actually Does

  • bridge: the default for standalone containers. Containers get private IP addresses on a virtual bridge on one host and communicate through NAT. User-defined bridges are strongly preferred over the legacy default bridge because they provide automatic DNS resolution by container name and better isolation.
  • host: the container shares the host's network namespace. There is no NAT and no port mapping; a process listening on port 80 in the container is listening on the host's port 80. This removes network overhead and removes isolation in equal measure.
  • overlay: spans multiple hosts, used by Swarm services. Traffic between hosts can be encrypted, and services get a virtual IP with built-in load balancing across replicas.
  • macvlan: assigns each container a MAC address so it appears as a physical device on the LAN, with its own IP from the physical network. Useful for legacy applications that expect to be directly addressable.
  • none: no networking at all, for batch or offline workloads that should have no network attack surface.
  • User-Defined Bridge Networks and Segmentation

    Define one network per trust zone and attach each service only where it belongs. The API below sits on both networks because it is the only component allowed to talk to both sides; the database never joins the frontend network and, with internal: true, has no route off the host at all.

    version: '3.8'
    services:
      web:
        image: nginx
        networks:
          - frontend
        ports:
          - "80:80"
    
      api:
        image: node:18-alpine
        networks:
          - frontend
          - backend
    
      db:
        image: postgres:14
        networks:
          - backend
    
    networks:
      frontend:
        driver: bridge
        ipam:
          config:
            - subnet: 172.20.0.0/16
      backend:
        driver: bridge
        internal: true

    Two details matter here. First, a port is only reachable from outside if it is published with ports:; containers on a shared network reach each other on the container port regardless. Second, internal: true blocks outbound access too, which also stops a compromised database container from calling out.

    Service Discovery via Embedded DNS

    On user-defined networks, Docker runs an embedded DNS server. Containers resolve each other by container name and by service name, and in Swarm mode a service name resolves to a virtual IP that load-balances across healthy replicas. This is why hardcoding container IPs is always wrong: IPs change on restart, names do not. Compose service names are the stable addresses your configuration should use.

    You can layer custom DNS servers and search domains on top when containers must resolve corporate or external names through specific resolvers:

    version: '3.8'
    services:
      web:
        image: nginx
        networks:
          - app_net
        dns:
          - 8.8.8.8
          - 8.8.4.4
        dns_search:
          - example.com
    
    networks:
      app_net:
        driver: bridge

    Overlay Networks for Multi-Host Services

    When services run across several Docker hosts under Swarm, overlay networks carry container traffic between hosts and give every service a stable virtual IP.

    version: '3.8'
    services:
      web:
        image: nginx
        deploy:
          replicas: 3
        networks:
          - overlay_net
    
    networks:
      overlay_net:
        driver: overlay
        attachable: true
        driver_opts:
          encrypted: "true"

    Set attachable: true only if standalone containers need to join the overlay; otherwise leave it off to keep the boundary tight. Enable encryption when traffic crosses hosts you do not fully control.

    Troubleshooting Workflow

    Work from the outside in: confirm the network exists and the container is attached to it, confirm name resolution, then confirm reachability.

    # Inspect network
    docker network inspect my_network
    
    # Check container connectivity
    docker exec container1 ping container2
    
    # View network statistics
    docker stats --format "table {{.Name}}\t{{.NetIO}}"

    docker network inspect shows the subnet, gateway, and every attached container with its assigned address; most "cannot connect" problems are visible here as a container attached to the wrong network. A successful ping by name proves both attachment and DNS. If names resolve but connections time out, suspect published-versus-container port confusion, an internal network, or a firewall on the host. docker stats NetIO counters tell you whether traffic is flowing at all before you reach for packet capture.

    Performance Notes

    Bridge networking with NAT costs some throughput and adds latency compared with host networking, which is why host mode appears in benchmarks. For most services the difference is irrelevant next to application time; measure before sacrificing isolation. Overlay networking adds encapsulation overhead on top. Choose the driver for the topology you need, then optimise the application.

    Decision Framework

    SituationRecommendation
    Services on one host that must talk to each otherUser-defined bridge, one network per trust zone
    Database or internal serviceBackend bridge with internal: true, no published ports
    Multi-host Swarm servicesOverlay network, encryption enabled if hosts are not fully trusted
    Legacy app that must appear on the LANmacvlan, with an IP range reserved so it cannot collide with DHCP
    Maximum network throughput, single trusted workloadHost networking, accepting the loss of isolation and port mapping
    Batch job that needs no networknone driver
    Debugging name resolutionCheck attachment with docker network inspect before changing configuration

    Implementation Checklist

  • [ ] Every stack uses user-defined networks, not the default bridge
  • [ ] Each service joins only the networks it genuinely needs
  • [ ] Backend networks are marked internal: true where outbound access is not required
  • [ ] Only intended ports are published; database and admin ports are not
  • [ ] Services address each other by service name, never by container IP
  • [ ] Subnets are planned so Docker networks do not overlap office or cloud VPC ranges
  • [ ] Overlay encryption is enabled for multi-host traffic that crosses untrusted networks
  • [ ] A runbook entry covers inspect, ping-by-name, and stats checks for connectivity incidents
  • Trade-offs

    Segmentation multiplies networks and makes Compose files longer; teams feel this as friction whenever a new legitimate connection is needed. Host networking is fast and simple but discards port mapping and isolation, and behaves differently across platforms. Macvlan integrates with physical networks at the cost of promiscuous-mode requirements and parent-interface quirks. Overlay networking is the only built-in multi-host option, but it ties you to Swarm's model; larger estates usually adopt Kubernetes networking instead, where policies can express allow-lists rather than just shared-network membership.

    When Not to Use

  • Bridge networking for multi-host communication: it is single-host by design. Use overlay under Swarm, or move to Kubernetes with a CNI plugin.
  • Host networking for untrusted or multi-tenant workloads: you give up the network boundary entirely; a VM or a dedicated host is the right container.
  • Docker networks as your only access control: shared-network membership is a coarse allow-all between members. Where you need per-port, per-service rules, use Kubernetes NetworkPolicy or host firewall rules in addition.
  • Conclusion

    Docker networking rewards deliberate design: user-defined bridges per trust zone, DNS names instead of IPs, published ports kept to a minimum, and overlays reserved for genuine multi-host needs. Most connectivity incidents and most container network breaches trace back to skipping one of those four habits. Design the networks when you design the stack, and troubleshooting becomes a short checklist instead of guesswork.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.