Skip to main content

Docker Networking & Volumes

Learn how containers communicate with each other and the outside world, and how to persist data.

Docker Networking

Docker provides several network drivers to control how containers communicate.

1. Bridge Network (Default)

The default network driver. Containers on the same bridge network can communicate via IP address or container name (DNS).
  • Isolation: Containers on different bridge networks cannot communicate.
  • Use Case: Standalone containers communicating on the same host.
# Create a custom bridge network (Recommended)
docker network create my-net

# Run containers on this network
docker run -d --name db --network my-net postgres
docker run -d --name app --network my-net my-app

# 'app' can now reach 'db' using the hostname "db"

2. Host Network

Removes network isolation between the container and the Docker host.
  • Performance: Best performance (no NAT).
  • Port Conflicts: Container ports map directly to host ports.
docker run --network host nginx
# Nginx is now accessible on host's port 80 directly

3. None Network

Disables all networking.
  • Use Case: Security-sensitive batch jobs that don’t need network access.
docker run --network none alpine

DNS Resolution

Docker has an embedded DNS server.
  • On default bridge network: DNS by container name is NOT supported (only IP).
  • On custom networks: DNS by container name IS supported.

Docker Volumes

Containers are ephemeral. When they stop, their filesystem is lost. Volumes persist data. Managed by Docker. Stored in /var/lib/docker/volumes/ (on Linux).
# Create volume
docker volume create db-data

# Mount volume
docker run -d \
  -v db-data:/var/lib/postgresql/data \
  postgres

2. Bind Mounts

Maps a specific file or directory on the host to the container.
  • Use Case: Development (live reloading code), sharing config files.
# Mount current directory to /app
docker run -d \
  -v $(pwd):/app \
  node:18-alpine

3. Tmpfs Mounts

Stored in the host’s memory only. Never written to disk.
  • Use Case: Storing sensitive secrets or high-performance temporary data.
docker run --tmpfs /run/secrets my-app

Managing Networks & Volumes

# List networks
docker network ls

# Inspect network (see connected containers)
docker network inspect my-net

# Remove unused networks
docker network prune

# List volumes
docker volume ls

# Remove unused volumes
docker volume prune

Key Takeaways

  • Always use Custom Bridge Networks for inter-container communication.
  • Use Named Volumes for database persistence.
  • Use Bind Mounts for development (code reloading).
  • Use Host Networking only when performance is critical and port conflicts aren’t an issue.

Docker Networking Deep Dive

How Bridge Networking Works

┌─────────────────────────────────────────────────────────┐
│                        Host                              │
│  ┌─────────────────────────────────────────────────┐   │
│  │              docker0 (bridge)                     │   │
│  │                 172.17.0.1                        │   │
│  └──────┬─────────────────┬─────────────────┬───────┘   │
│         │                 │                 │           │
│    ┌────┴────┐      ┌────┴────┐      ┌────┴────┐       │
│    │Container│      │Container│      │Container│       │
│    │172.17.0.2│     │172.17.0.3│     │172.17.0.4│      │
│    └─────────┘      └─────────┘      └─────────┘       │
└─────────────────────────────────────────────────────────┘

iptables Rules

Docker manipulates iptables for networking:
# View Docker's iptables rules
sudo iptables -t nat -L -n

# DNAT rule for port mapping (-p 8080:80)
-A DOCKER -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80

DNS Resolution

Docker’s embedded DNS server (127.0.0.11):
# Inside container
cat /etc/resolv.conf
# nameserver 127.0.0.11

# Resolve other containers by name
ping db  # Works on custom networks

Overlay Networks (Multi-Host)

For containers across multiple Docker hosts (Swarm mode).
# Create overlay network
docker network create --driver overlay my-overlay

# Containers on different hosts can communicate
docker service create --network my-overlay --name web nginx
docker service create --network my-overlay --name api myapi

How Overlay Works

┌────────────────────────┐     ┌────────────────────────┐
│        Host 1          │     │        Host 2          │
│  ┌──────────────────┐  │     │  ┌──────────────────┐  │
│  │ Container A      │  │     │  │ Container B      │  │
│  │ 10.0.0.2         │  │     │  │ 10.0.0.3         │  │
│  └────────┬─────────┘  │     │  └────────┬─────────┘  │
│           │            │     │           │            │
│  ┌────────┴─────────┐  │     │  ┌────────┴─────────┐  │
│  │ VXLAN Tunnel     │◄─┼─────┼─►│ VXLAN Tunnel     │  │
│  └──────────────────┘  │     │  └──────────────────┘  │
└────────────────────────┘     └────────────────────────┘

Container Network Interface (CNI)

CNI is the standard for container networking plugins (used by Kubernetes).
PluginFeatures
CalicoNetwork policies, BGP routing
CiliumeBPF-based, advanced security
FlannelSimple overlay, easy setup
WeaveEncryption, multicast

Volume Drivers

Beyond local storage, Docker supports pluggable volume drivers.
DriverDescription
localDefault, stores on host
nfsNetwork File System
awsAWS EBS/EFS
azureAzure File/Disk
glusterfsDistributed storage
# Create volume with specific driver
docker volume create --driver=nfs \
  --opt share=192.168.1.1:/data \
  nfs-data

Docker Compose Networking

version: '3.8'
services:
  web:
    image: nginx
    networks:
      - frontend
    ports:
      - "80:80"
  
  api:
    image: myapi
    networks:
      - frontend
      - backend
  
  db:
    image: postgres
    networks:
      - backend
    volumes:
      - db-data:/var/lib/postgresql/data

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true  # No external access!

volumes:
  db-data:

Network Aliases

services:
  db:
    image: postgres
    networks:
      backend:
        aliases:
          - database
          - postgres-primary

Interview Questions & Answers

DriverScopeUse Case
bridgeSingle hostDefault, container-to-container
hostSingle hostNo network isolation, max performance
noneSingle hostNo networking
overlayMulti-hostDocker Swarm/K8s
macvlanSingle hostContainer gets MAC address on LAN
Same bridge network:
  1. Container A sends packet to Container B’s name
  2. Docker DNS resolves name to IP
  3. Packet goes through bridge interface
  4. iptables routes to Container B
Different networks:
  • Cannot communicate directly
  • Need a container connected to both networks, or use host network
AspectNamed VolumeBind Mount
LocationDocker managesYou specify path
PortabilityPortableTied to host
Backupdocker volume commandsStandard file tools
PerformanceBetter on non-LinuxNative
Use CaseDatabases, persistent dataDevelopment, configs
Use named volumes:
docker volume create db-data
docker run -v db-data:/var/lib/postgresql/data postgres
Important:
  • Volume survives container deletion
  • Back up with docker run --volumes-from backup-container
  • For production, consider external volume drivers (NFS, cloud storage)
macvlan assigns a MAC address to the container, making it appear as a physical device on the network.Use Cases:
  • Legacy apps requiring specific MAC addresses
  • Apps needing to appear as physical hosts
  • Direct LAN access without port mapping
docker network create -d macvlan \
  --subnet=192.168.1.0/24 \
  --gateway=192.168.1.1 \
  -o parent=eth0 \
  my-macvlan
# Inspect network
docker network inspect bridge

# Check container's network
docker inspect --format='{{.NetworkSettings.Networks}}' container

# Test connectivity from inside container
docker exec -it container ping other-container

# Check DNS resolution
docker exec -it container nslookup db

# Check iptables rules
sudo iptables -t nat -L -n | grep DOCKER

# Use network debug container
docker run --net container:target nicolaka/netshoot

Common Pitfalls

1. Default Bridge DNS: The default bridge network doesn’t support DNS resolution by container name. Use custom networks.2. Not Using Custom Networks: Containers on default bridge can only communicate by IP, which changes.3. Data Loss Without Volumes: Container filesystem is ephemeral. Always use volumes for persistent data.4. Bind Mounts in Production: Bind mounts tie containers to specific host paths. Use named volumes.5. Port Conflicts: Multiple containers can’t bind to the same host port. Plan port mappings.6. Forgetting Network Isolation: All containers on a network can communicate. Use multiple networks for isolation.

Next: Docker Compose →