Docker: network debugging and firewalling

Featured image

In general I like the nicolaka/netshoot image for troubleshooting. It has all the tools you need (ip, curl, …). It’s nice for network debugging used with docker run --network=container:$existing_running_containter. Then you have the same ip/traffic like the container you want to debug. If you’re looking for something like top but for containers, I recommend ctop. Just check the aliases below.

Some aliases

DOCKER_FORMAT="table {{ .Names }}\t{{ .Image }}\t{{ .Status }}\t{{ .Ports }}\t{{ .Names }}"

alias dl='docker ps --format "$DOCKER_FORMAT"'
alias dg='docker ps --format "{{ .Names }}" | rg $1'
alias ctop="docker run --rm --name ctop -v /var/run/docker.sock:/var/run/docker.sock -it nicolaka/netshoot ctop"

alias deb=docker_exec_bash
docker_exec_bash() {
    docker exec -it $1 bash
}

alias des=docker_exec_sh
docker_exec_sh() {
    docker exec -it $1 sh
}

alias den=network_debug
network_debug() { # docker exec network (run debug container with network of $1 container)
    docker run --rm --network=container:$1 -it nicolaka/netshoot
}

alias di=container_ips
container_ips() { # show all running containers and their ip addresses
for container in $(docker ps -q)
do
        docker inspect -f '{{ .Name }}: {{range.NetworkSettings.Networks}}{{.IPAddress}} {{end}}' $container;
done
}

Firewalling with Docker

Docker automatically adds iptable rules. When port forwarding is configured, it automatically opens ports in the firewall. Some ways to fix that:

  • Use firewall provided by the hosting platform (some providers allow to set firewall rules)
  • Use ufw-docker (Pull Request with v6 support)
  • Set "ip": "127.0.0.1" in daemon.json. Then 8080:80 binds to 127.0.0.1 only (docs).
  • Do firewalling manually:
  1. Set { "iptables": false } in /etc/docker/daemon.json.
  2. Use a fixed name for the bridge in docker-compose.yml.
networks:
  nextcloud:
    driver_opts:
      com.docker.network.bridge.name: br-nextcloud
  1. Use your favorite firewall tool. I like ferm (example config).