Docker › Network

Debugging Docker container networks with netshoot and tcpdump

Attach netshoot to minimal Docker containers to inspect sockets and tcpdump traffic, and fix Docker bypassing Ubuntu UFW firewall rules.

Debugging Docker container networks with netshoot and tcpdump

Debugging network failures inside minimal Distroless or Alpine containers gets frustrating fast when ping, curl, and even bash are missing. This post shows how to attach a netshoot sidecar directly to a running container’s network namespace for ss, tcpdump, and drill inspection, and how to fix Docker’s well-known Ubuntu UFW firewall bypass.

Tested with Docker Engine on Ubuntu Linux (Netfilter/iptables) and nicolaka/netshoot.


1. The minimal-container dilemma: no ping, no curl, no shell

One of the trickiest production incidents is when every container reports healthy, yet inter-container calls fail with Connection refused, Connection timed out, or DNS NXDOMAIN. Everything worked locally, so you open a terminal to poke around inside the container:

1
2
docker exec -it my-backend-api /bin/bash
# OCI runtime exec failed: exec: "/bin/bash": stat /bin/bash: no such file or directory

Falling back to /bin/sh doesn’t get you much further:

1
2
3
4
5
6
7
docker exec -it my-backend-api sh
/ # ping redis-cache
# sh: ping: not found
/ # curl http://order-service:8080/health
# sh: curl: not found
/ # netstat -tlpn
# sh: netstat: not found

Production images increasingly rely on Google Distroless, Scratch, or Alpine-slim bases to keep image sizes small and shrink the CVE attack surface. That means /bin/sh may not exist at all, and diagnostic binaries like ping, curl, netstat, and dig are deliberately stripped out.

Installing iputils-ping or rebuilding the image with debug tools isn’t a viable move during a live incident. Restarting the container wipes the exact in-memory state and active socket tables you need to examine.


2. Attaching netshoot to a container’s network namespace

The cleanest way out of this dilemma is nicolaka/netshoot—a purpose-built troubleshooting image preloaded with tcpdump, curl, grpcurl, drill, dig, mtr, ngrep, socat, iperf3, and iproute2.

Rather than running netshoot as an isolated container, you attach it directly to the target container’s existing network stack.

How --net container:<target-id> works

Linux container isolation relies on kernel namespaces—separate PID, Mount, and Network namespaces per container. When you pass --net container:<container-id>, Docker skips creating a new virtual interface for netshoot and joins it to the target container’s network namespace (CLONE_NEWNET) instead.

flowchart TD
    subgraph Host["Docker Host (Linux Kernel)"]
        subgraph TargetCont["Target Container (my-backend-api)"]
            RootFS1["Isolated Root Filesystem (Distroless / JRE)"]
            AppProc["Application Process (Java/Go/Node)"]
        end
        subgraph NetshootCont["netshoot Container (Debug Session)"]
            RootFS2["netshoot Filesystem (tcpdump, curl, drill)"]
            DebugTool["Diagnostic Shell (zsh/bash)"]
        end
        subgraph SharedNetNS["Shared Network Namespace (Target NetNS)"]
            Loopback["lo (127.0.0.1)"]
            Eth0["eth0 (172.20.0.5)"]
            RouteTable["Routing Table / ARP Cache"]
            OpenSockets["Listening Sockets (0.0.0.0:8080)"]
            IPTableRules["iptables / conntrack State"]
        end
    end
    AppProc -.->|"Shares network namespace"| Eth0
    DebugTool -.->|"--net container:my-backend-api"| Eth0

Filesystem and process isolation stay intact—you don’t touch the running application’s rootfs—while both containers share the exact same loopback (127.0.0.1), eth0 interface, routing table, and listening sockets.

Launching an ephemeral netshoot session

Attach to the target container with a single command:

1
2
3
4
5
docker run -it --rm \
  --net container:my-backend-api \
  --cap-add=NET_ADMIN \
  --cap-add=NET_RAW \
  nicolaka/netshoot

Add --cap-add=NET_ADMIN and --cap-add=NET_RAW when you need live packet capture (tcpdump, promiscuous mode) or interface inspection. Because --rm is set, Docker removes the debug container automatically when you exit.

Inside the netshoot shell, ip addr and ss immediately show the target container’s interface and listening sockets:

1
2
3
4
5
6
7
8
9
# Inspect the target container's network interface
netshoot # ip addr show eth0
24: eth0@if25: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
    inet 172.20.0.5/16 brd 172.20.255.255 scope global eth0

# List active listening TCP ports
netshoot # ss -tlpn
State      Recv-Q     Send-Q          Local Address:Port          Peer Address:Port
LISTEN     0          128                 127.0.0.1:8080               0.0.0.0:*

3. Packet-level diagnosis with tcpdump and drill

Once you’re inside the shared namespace, you can prove the root cause of two common container networking failures in seconds.

Case 1: Service is up, but peer containers get Connection refused

Look closely at the ss -tlpn line above: the process bound to 127.0.0.1:8080 instead of 0.0.0.0:8080. When a Spring Boot, Node.js, or FastAPI process listens only on loopback, any request from another container arriving at 172.20.0.5:8080 gets rejected immediately with a TCP RST (Reset) packet.

Start tcpdump inside netshoot to confirm:

1
tcpdump -nnvv -i eth0 port 8080

Sending curl http://172.20.0.5:8080 from another container produces this capture:

1
2
3
4
5
12:15:30.102345 IP (tos 0x0, ttl 64, id 41201, offset 0, flags [DF], proto TCP (6), length 60)
    172.20.0.3.49822 > 172.20.0.5.8080: Flags [S], cksum 0x3a12, seq 1928374650, win 64240, options [mss 1460,sackOK,TS val 1827364 ecr 0], length 0

12:15:30.102380 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 40)
    172.20.0.5.8080 > 172.20.0.3.49822: Flags [R.], cksum 0x5b3f, seq 0, ack 1928374651, win 0, length 0
sequenceDiagram
    autonumber
    actor Client as Caller Container (172.20.0.3)
    participant NetNS as Target eth0 (172.20.0.5)
    participant App as App Process (127.0.0.1:8080)
    Client->>NetNS: [SYN] Connect to port 8080
    Note over NetNS,App: No listener bound on 172.20.0.5:8080
    NetNS-->>Client: [RST, ACK] Connection Refused

The kernel answers Flags [S] (SYN) with Flags [R.] (RST/ACK) in microseconds. That confirms the traffic reached the container cleanly—no firewall drop—and the fix is simply binding the server to 0.0.0.0:8080.

Case 2: Docker embedded DNS lookup failures (NXDOMAIN)

If HTTP calls to order-service fail with Could not resolve host, query Docker’s embedded DNS server (127.0.0.11:53) directly using drill:

1
2
3
4
5
# Query Docker's embedded DNS server directly
drill @127.0.0.11 order-service

# Watch DNS UDP packets on eth0 in parallel
tcpdump -n -i eth0 udp port 53

If the two containers sit on different user-defined bridge networks (or one is still on the legacy default bridge network, which disables automatic DNS service discovery), 127.0.0.11 returns NXDOMAIN. Attaching both containers to the same user-defined bridge network resolves it immediately.


4. Why Docker bypasses Ubuntu UFW and how to fix it

While auditing container traffic, I often run into a much nastier host-level surprise: you enable Ubuntu’s UFW firewall and block port 8080, yet running docker run -p 8080:8080 still exposes port 8080 to the public internet.

Why UFW doesn’t block published Docker ports

Many engineers configure ufw default deny incoming and ufw allow 22, assuming every other port is sealed off. Because of Linux Netfilter chain order, published Docker ports bypass UFW completely.

flowchart TD
    InPacket["Inbound External Traffic (eth0)"] --> PREROUTING["PREROUTING (nat table)<br/>Docker DNAT rewrites destination to container IP"]
    PREROUTING --> RoutingDecision{"Routing Decision<br/>(Destination is local host?)"}
    RoutingDecision -->|"YES: Local host process"| INPUTChain["INPUT chain (filter table)<br/>UFW rules evaluate here"]
    INPUTChain --> LocalProcess["Host OS Daemons (SSH, etc.)"]
    RoutingDecision -->|"NO: Forward to another interface"| FORWARDChain["FORWARD chain (filter table)<br/>Docker inserts DOCKER chain ACCEPT"]
    FORWARDChain --> DockerBridge["docker0 / User Bridge (veth)"]
    DockerBridge --> Container["Target Container (eth0)"]
    style INPUTChain fill:#f9d5d5,stroke:#c94c4c,stroke-width:2px
    style FORWARDChain fill:#d5f9d5,stroke:#4cc94c,stroke-width:2px

Here is the exact bypass sequence:

  1. When an external packet arrives on eth0, Docker’s DNAT rule in PREROUTING rewrites the destination IP from the host IP to the container’s private IP (172.20.0.x).
  2. Because the destination is no longer the host itself, Linux routes the packet to the FORWARD chain instead of the INPUT chain.
  3. UFW’s default inbound rules live on the INPUT chain.
  4. Docker prepends its own DOCKER accept rules at the top of FORWARD, sending the packet straight into the container past UFW.

Why you should never set {"iptables": false}

Many quick answers online tell you to add {"iptables": false} to /etc/docker/daemon.json. Don’t do this.

Disabling Docker’s iptables management strips out inter-container routing and outbound MASQUERADE NAT rules too. Containers lose outbound internet access, breaking external API calls and package downloads across the host.

Proper fixes: DOCKER-USER chain or ufw-docker

If a container only needs to be reached by a reverse proxy on the same host (such as Nginx or Caddy), the simplest safeguard is binding to localhost: -p 127.0.0.1:8080:8080. When you genuinely need external access restricted by source IP, use one of the two methods below.

Option 1: Add rules to Docker’s official DOCKER-USER chain

Docker creates a DOCKER-USER chain at the very top of FORWARD specifically for administrator firewall rules, and never overwrites it on daemon restarts.

To allow only a trusted office IP (203.0.113.50) to reach port 8080 on eth0 and drop everything else:

1
2
3
4
5
6
7
8
9
10
11
# 1. Allow return traffic for established connections
sudo iptables -A DOCKER-USER -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# 2. Allow only the trusted office IP on port 8080
sudo iptables -A DOCKER-USER -i eth0 -s 203.0.113.50 -p tcp --dport 8080 -j ACCEPT

# 3. Drop all other external traffic on eth0 destined for port 8080
sudo iptables -A DOCKER-USER -i eth0 -p tcp --dport 8080 -j DROP

# 4. Return remaining traffic to Docker's default rules
sudo iptables -A DOCKER-USER -j RETURN

Option 2: Manage container rules with ufw-docker

If you’d rather not maintain raw iptables rules by hand, chaifeng/ufw-docker integrates Docker’s FORWARD filtering cleanly into UFW:

1
2
3
4
5
6
7
# Install ufw-docker
sudo wget -O /usr/local/bin/ufw-docker https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker
sudo chmod +x /usr/local/bin/ufw-docker

# Inject DOCKER-USER rules into UFW's after.rules and reload UFW
sudo ufw-docker install
sudo systemctl restart ufw

Once installed, you control published container ports with familiar UFW syntax:

1
2
3
4
5
# Allow port 8080 on my-backend only from 192.168.1.0/24
sudo ufw-docker allow my-backend 8080/tcp from 192.168.1.0/24

# Inspect active Docker firewall rules
sudo ufw-docker status

5. Container network debugging cheat sheet

Keep these commands handy when investigating a live container network issue:

ScenarioCommand
Attach to target network namespacedocker run -it --rm --net container:<id> --cap-add=NET_ADMIN --cap-add=NET_RAW nicolaka/netshoot
Check listening ports and bind IPsss -tlpn (or netstat -tlpn)
Capture live packets on a porttcpdump -nnvv -i eth0 port <port>
Inspect plaintext HTTP payloadsngrep -W byline -d eth0 'HTTP' 'port 8080'
Test Docker embedded DNSdrill @127.0.0.11 <service-name>
Restrict published port via UFWufw-docker allow <container-name> <port>

Next time a minimal container drops connections in production, resist the urge to restart it blindly. Attach netshoot to its network namespace, check ss -tlpn, and read the packets directly—you’ll replace guesswork with packet-level proof in minutes.

This post is licensed under CC BY 4.0 by the author.