# Docker Networking

## Network Modes
- **bridge** (default): Containers get their own IP on a private network. Use for most deployments
- **host**: Container shares the host's network stack. No port mapping needed. Use when performance matters or for apps that bind to many dynamic ports
- **none**: No networking. Rare — only for fully isolated tasks

## Service Discovery (DNS)
- Containers on the same Docker Compose network can reach each other by **service name**
- Example: a service called `db` is reachable at hostname `db` from other services
- No need to expose ports for inter-service communication — only expose ports that need host access
- If using multiple compose files, create a shared external network:
  ```yaml
  networks:
    shared:
      external: true
  ```

## Port Mapping
- Syntax: `"HOST_PORT:CONTAINER_PORT"`
- Bind to localhost only: `"127.0.0.1:8080:80"` — prevents LAN/WAN access
- Bind to all interfaces: `"0.0.0.0:8080:80"` or just `"8080:80"`
- UDP ports: `"5353:5353/udp"`
- Port ranges: `"8000-8005:8000-8005"`

## Port Conflicts
- Symptom: `bind: address already in use`
- Diagnose: `sudo lsof -i :PORT` or `ss -tlnp | grep PORT`
- Fix: stop the conflicting process, or change the host port mapping
- Common conflicts: 80 (Apache/Nginx), 5432 (Postgres), 3306 (MySQL), 6379 (Redis), 8080 (various)

## Custom Networks
- Docker Compose creates a default bridge network for each project
- Define custom networks for isolation between service groups:
  ```yaml
  services:
    app:
      networks: [frontend, backend]
    db:
      networks: [backend]

  networks:
    frontend:
    backend:
  ```
- Services on different networks cannot communicate directly

## DNS Resolution Issues
- Symptom: `Could not resolve host` or `EAI_AGAIN` inside a container
- Cause: Docker daemon DNS issue or custom DNS configuration
- Fix: restart Docker daemon, or set DNS explicitly:
  ```yaml
  services:
    app:
      dns:
        - 8.8.8.8
        - 8.8.4.4
  ```

## WebSocket Services
- Expose the WS port directly — don't put behind a reverse proxy unless properly configured
- If using Nginx as a proxy, add the necessary `Upgrade` headers:
  ```
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  ```
