Docker Networking
Docker networking enables containers to communicate with each other and with the outside world. Understanding networking is crucial for building distributed applications.
At its core, Docker networking is built on Linux networking capabilities, providing a flexible and powerful system for connecting containers. Docker uses a pluggable architecture that supports various network drivers to accommodate different use cases, from simple single-host applications to complex multi-host distributed systems.
The networking subsystem in Docker is designed to be:
- Isolated: Containers have their own network namespace
- Configurable: Multiple network types for different requirements
- Performant: Optimized for container-to-container communication
- Secure: Support for network segmentation and access controls
- Extensible: Pluggable architecture for custom networking solutions
Network Types
Bridge Network
- Default network type (
bridge
driver) - Used when containers need to communicate on the same Docker host
- Provides network isolation between containers
- Containers can communicate using container names as DNS
- Creates a virtual bridge interface on the host (typically
docker0
) - Assigns containers to a private subnet (typically 172.17.0.0/16)
- Default bridge network doesn't provide automatic DNS resolution
- Custom bridge networks support DNS resolution by container name
- Each container gets its own IP address within the subnet
Host Network
- Removes network isolation between container and host (
host
driver) - Container uses host's network directly (shares host's network namespace)
- Better performance but less secure (no network isolation)
- Useful for specific use cases requiring direct host network access
- No port mapping needed as container ports are exposed directly on host
- Potential port conflicts with host services or other containers
- Limited to services running on a single host
- Not compatible with Docker Swarm mode services
Overlay Network
- Enables communication between containers across multiple Docker hosts
- Used in Docker Swarm mode (
overlay
driver) - Provides multi-host networking out of the box
- Supports container-to-container encryption
- Uses VXLAN encapsulation for traffic between hosts
- Automatically manages IP allocation across the cluster
- Enables service discovery across the entire swarm
- Integrates with swarm load balancing for distributed services
- Supports both swarm services and standalone containers
Macvlan Network
- Assigns MAC address to containers (
macvlan
driver) - Containers appear as physical devices on network
- Useful for legacy applications
- Provides better network performance
- Gives each container a unique MAC and IP address on the physical network
- Requires promiscuous mode support on host network interface
- Can connect containers directly to existing VLANs
- May require configuration of physical network equipment
- Good for applications that expect to be directly connected to physical network
None Network
- Container has no network connectivity (
none
driver) - Complete network isolation
- Container cannot communicate with external networks or other containers
- Useful for batch processing jobs where network access is not required
- Maximum security isolation from network perspective
- Can still use IPC or volume sharing for communication if needed
IPvlan Network
- Alternative to macvlan that doesn't require promiscuous mode
- Shares MAC address with host but assigns unique IP addresses to containers
- Supports L2 and L3 modes for different routing requirements
- Good for environments where promiscuous mode is restricted
- Often more efficient for large-scale deployments
Basic Networking Commands
These commands can be combined with other Docker commands and options to create sophisticated networking configurations for your containerized applications.
Network Configuration Examples
Creating a User-Defined Network
Connecting Containers
Docker Compose Networking
Port Mapping
Port mapping allows access to container services from the host:
Port mapping works by configuring iptables rules on the host that redirect traffic from the host's port to the container's port. This enables:
- External access to container services
- Service availability on well-known ports
- Load balancing across multiple containers
- Security through controlled exposure
Note that port mappings only apply to bridge networks, not to containers using host networking mode (which already expose all ports directly).
DNS and Service Discovery
Docker provides automatic DNS resolution between containers in the same network:
- Containers can refer to each other by name
- Built-in DNS server at 127.0.0.11
- Automatic service discovery in user-defined networks
How Docker DNS Works
- Container DNS Configuration: Docker automatically configures each container's
/etc/resolv.conf
to use the Docker DNS server: - Name Resolution Process:
- Container requests are sent to Docker's embedded DNS server
- The DNS server maintains records for all containers in the same network
- If the name matches a container, it returns the container's IP address
- Otherwise, it forwards the request to the external DNS servers specified in the host's
/etc/resolv.conf
- Network Scope: DNS resolution only works between containers on the same user-defined network; the default bridge network does not support this feature
Service Discovery in Swarm Mode
In Docker Swarm mode, DNS-based service discovery is enhanced:
- Each service gets a DNS entry in the format
service_name
- Load balancing happens automatically between service replicas
- Virtual IP (VIP) mode provides a single IP that load balances across all replicas
- DNS Round Robin (DNSRR) mode returns all container IPs for client-side load balancing
Custom DNS Configuration
You can customize container DNS settings:
Network Security Best Practices
- Use user-defined networks instead of default bridge
- Custom networks provide container name DNS resolution
- Better isolation between container groups
- More control over subnet and IP assignment
- Example:
docker network create --internal db-network
for a database network with no internet access
- Limit container network access
- Use
--internal
flag to create networks without external connectivity - Restrict exposed ports to only what's necessary
- Bind to specific interfaces when needed:
docker run -p 127.0.0.1:8080:80 nginx
- Implement drop-all iptables policies and add specific rules
- Use
- Use network segmentation
- Create separate networks for different application tiers
- Place frontend, backend, and database containers in dedicated networks
- Connect gateway containers to multiple networks to enable controlled communication
- Example: Three-tier architecture with frontend, backend, and database networks
- Enable network encryption in overlay networks
- Use
--opt encrypted=true
when creating overlay networks - Secures container-to-container communication across hosts
- Protects sensitive data in transit
- Consider performance impact (about 10% overhead)
- Use
- Regularly audit network configurations
- Review network resources with
docker network ls
anddocker network inspect
- Check container connections with
docker inspect --format='{{json .NetworkSettings.Networks}}' container-name
- Monitor network traffic with tools like tcpdump or Wireshark
- Use logging to track connection attempts
- Review network resources with
- Follow principle of least privilege
- Containers should only connect to networks they need
- Implement application-level authentication even between containers
- Use read-only file systems when possible
- Drop unnecessary capabilities:
docker run --cap-drop=NET_ADMIN nginx
- Additional security measures
- Consider network plugins with advanced security features
- Implement network policies (with Kubernetes or custom solutions)
- Use TLS for all service-to-service communication
- Deploy a service mesh for advanced security controls in larger deployments
Common Network Troubleshooting
Common Network Issues and Solutions
Issue | Symptoms | Troubleshooting Steps |
---|---|---|
Container can't reach internet | ping google.com fails | Check container DNS, verify host networking, check NAT configuration |
Containers can't find each other | Name resolution fails | Ensure they're on same network, check service names, inspect DNS configuration |
Port mapping not working | External connection refused | Verify app is listening on correct interface (0.0.0.0), check port conflicts |
Overlay network issues | Multi-host communication fails | Verify required ports open (2377, 7946, 4789), check VXLAN configuration |
Performance problems | High latency, low throughput | Monitor network metrics, check for packet loss, verify driver configuration |
IP address conflicts | Containers fail to start | Use custom subnets, check overlap with existing networks |
Advanced Topics
Network Plugins
- Docker supports third-party network plugins via Container Network Interface (CNI)
- Extends networking capabilities beyond built-in drivers
- Enables integration with SDN solutions (Software-Defined Networking)
- Supports custom network implementations for specialized requirements
- Notable plugins:
- Calico: Advanced network policies and security
- Weave: Simple, resilient, multi-host networking
- Cilium: eBPF-based networking with enhanced observability and security
- Flannel: Simple overlay network focused on Kubernetes
- Contiv: Policy-based networking for enterprise environments
Load Balancing
- Built-in load balancing in Swarm mode using ingress routing mesh
- Service discovery with DNS round-robin for distributed service access
- Support for external load balancers through exposed ports
- Health checks and automatic container replacement for service resilience
- Modes of operation:
- VIP (Virtual IP): A single virtual IP load balances across all service tasks
- DNSRR (DNS Round-Robin): Returns all container IPs for client-side load balancing
- Example configuration:
Network Policies
- Control traffic flow between containers with fine-grained rules
- Define allowed communication paths based on ports, protocols, and sources
- Implement micro-segmentation for defense-in-depth security
- Enhanced security control for multi-tenant environments
- Implementation options:
- Kubernetes Network Policies (when using Kubernetes)
- Calico Network Policies
- Custom iptables rules within containers
- Application-level authorization
Exposing Services
- Multiple patterns for exposing containerized services:
- Port publishing: Expose on host with
-p
flag - Ingress routing mesh: Swarm's built-in load balancer
- Reverse proxy: Using Traefik, Nginx, or HAProxy containers
- Service mesh: Advanced routing with Istio or Linkerd
- Port publishing: Expose on host with
- Considerations:
- Security (exposure surface)
- Load balancing requirements
- SSL/TLS termination
- Authentication and authorization
Container Network Namespaces
- Advanced manipulation for specialized networking:
Performance Tuning
- MTU optimization for improved throughput
- TCP settings adjustment for specific workloads
- Network mode selection based on performance requirements
- Monitoring network performance:
- Driver-specific optimizations