Bài gốc: Deep Dive: How Linux Conntrack Determines Performance and Security in Docker Containers — tác giả BaconYao, lấy qua Notion public API.

Introduction

This article is a continuation of my previous post, 11. A Brief Introduction to Conntrack . In this piece, we will dive deeper into the impact of conntrack on Docker networking. Furthermore, we will explore how the TCP three-way handshake and four-way handshakes (teardown) operate within this context.

Lab3 - How Linux Conntrack Determines Performance and Security in Docker Containers

In this experiment, we will observe how Docker utilizes conntrack to establish filter table rules (stateful connections), which not only optimizes performance but also enhances security.We will explore the contributions of conntrack through three sub-experiments:
  1. Use the nc command to observe packet changes during TCP establishment and analyze the packet transitions during the three-way handshake and four-way teardown.
  2. Use the curl command to observe packet changes during HTTP Requests and Responses.
  3. Remove conntrack rules to understand the impact of stateless connections.

Environment Setup

For this session, we will use iximiuz Labs’ flexbox to set up two machines.
  • For box-01, select docker as the Rootfs so that Docker comes pre-installed on the machine.
  • For box-02, select ubuntu-24-04, which will serve as the client to access the Nginx server container on box-01.

1. View the initial state of the filter table

First, once the environment initialization is complete, let’s observe the iptables filter table on box-01. You will see the content as shown in the figure on the left.

Chain Analysis

  • INPUT = ACCEPT → Packets destined for Host A itself are not blocked.
  • FORWARD = DROP → Any “forwarded” traffic is dropped by default (Very Important).
  • OUTPUT = ACCEPT → Packets sent out from Host A itself are not blocked.
Traffic flow order:
  • FORWARD → DOCKER-USER: Reserved for user-defined rules; empty by default.
  • FORWARD → DOCKER-FORWARD: Where Docker actually attaches its forwarding rules.
If someone sends packets directly to docker0 (from the external network → docker0), all of them will be DROPped.In other words, eth0 → docker0 is not allowed. To access a container, traffic must pass through NAT + DNAT to enter.
All traffic destined for docker0 will jump to the DOCKER chain, where it is then matched against inbound rules.
This rule is the core of Docker’s network security and performance optimization; it can be understood through the concepts of a “fast pass” or “connection state tracking.”
In iptables terminology, this is known as Stateful Inspection.
  • -A DOCKER-CT: Appends the rule to the DOCKER-CT sub-chain (a dedicated chain used by Docker to handle connection tracking traffic).
  • -o docker0: Specifies packets being sent “out to the docker0 bridge” (i.e., traffic destined for containers).
  • -m conntrack: Invokes the conntrack kernel module—a powerful state-tracking engine that remembers the context and history of every connection.
  • --ctstate RELATED,ESTABLISHED: This is the most critical condition. It checks the “state” of the packet:
    • ESTABLISHED: The packet belongs to a legitimate connection that has already completed the “three-way handshake” (SYN→SYN/ACK→ACKSYN \rightarrow SYN/ACK \rightarrow ACK). Simply put, these are “returning customers.”
    • RELATED: The packet is not part of the original connection but is associated with an existing one (e.g., FTP data channels or certain ICMP error messages).
  • -j ACCEPT: If the packet matches these states, it is immediately allowed.
  1. Performance Optimization: The “Fast Pass” Lane
    1. In the absence of this rule, every single packet entering a container (whether it’s raw data or an acknowledgement) would have to be matched against the complex DOCKER chain rules (checking destination IP, TCP headers, Port 80, etc.).
    2. With this rule, as long as the initial SYN packet (the new connection) is permitted by the DOCKER chain, conntrack remembers the IP and port pair. Subsequent thousands of data packets are intercepted by this rule and “instantly released,” bypassing complex rule checks and significantly saving CPU resources.
  2. Allowing Return Traffic
    1. Firewalls are typically “one-way” by default. If you initiate a request from inside a container to the outside world (e.g., running apk update inside an Nginx container), the returning data packets will be recognized as ESTABLISHED or RELATED by this rule and automatically allowed through. Without it, the response packets would be blocked by the default FORWARD DROP policy.
The Flow Sequence:
  1. Allow Return Traffic First
    Does not block conntrack ESTABLISHED traffic; this ensures existing connections stay active and performant.
  2. Perform Inter-Container Isolation Checks
    Jump to the isolation chain (Handling inter-network blocking).
  3. Validate Inbound DNAT
    If inbound traffic needs to enter a container, it must be ACCEPTED here after passing NAT/DNAT rules.
  4. Allow Container → Host or Container → External Network
    Permits outgoing traffic initiated by the container to reach the host or the public internet.

2. Start the Nginx server container

To observe how packets traverse the filter table, we will start an Nginx web server on the box-1 machine.
From the diagram on the left, we can conclude the following three things:
  1. nginx-server container: The IP address is 172.17.0.2/32.
  2. box-01: The IP address is 172.16.0.2/24.
  3. docker0 bridge: The IP address is 172.17.0.1/16.

Re-examining the Filter Table Rules

Next, let’s examine the iptables filter table rules on box-1 again. You will notice that a new rule (indicated by the red arrow in your diagram) has been added.Rule Analysis
  • -A DOCKER: Appends this rule to the DOCKER chain. This is the centralized location where Docker manages all forwarding filter logic for published ports.
  • -d 172.17.0.2/32: Defines the Destination Address. This rule specifically targets packets destined for 172.17.0.2 (the internal private IP of your Nginx container).
  • ! -i docker0 -o docker0: Interface Logic.
    • o docker0: The packet is heading “out” through the docker0 bridge (towards the container).
    • ! -i docker0: The packet is NOT coming from the docker0 bridge.
    • Meaning: This targets “Inbound” traffic—packets coming from the physical network (e.g., eth0) rather than traffic moving between containers on the same bridge.
  • -p tcp -m tcp --dport 80: Protocol and Port. It only permits TCP traffic where the destination port is 80 (the internal port the Nginx process is listening on).
  • -j ACCEPT: The action is ACCEPT. If a packet matches all the above criteria, it is allowed to pass through the firewall.

3. Access the Web Server on box-1 from the box-2 machine

Before we begin the experiment, let’s confirm the IP addresses: box-01 is 172.16.0.2 and box-02 is 172.16.0.3. To observe the connection tracking (conntrack) behavior in real-time, we need to install the conntrack utility, which allows us to peer into the kernel’s state table.

3.1 Establishing a TCP Connection Using nc (Netcat)

Next, we use the nc (netcat) command on box-02 to establish a TCP connection to the nginx-server container on box-01 (as shown in the image below). After establishing the connection, we observe the changes in packet counts across different chains in the filter table on box-01. Here is the detailed analysis: 1. The Entrance: FORWARD Chain
  • [3:172] -A FORWARD -j DOCKER-USER
  • [3:172] -A FORWARD -j DOCKER-FORWARD
  • Analysis: We see 3 packets here (typically the TCP three-way handshake: SYN, SYN/ACK, and ACK). Every packet first visits the DOCKER-USER chain (where users can set custom intercept rules) before proceeding to DOCKER-FORWARD.
2. The Transit: DOCKER-FORWARD Chain Once inside, the packets pass through three sub-chains in sequence:
  • DOCKER-CT (Connection Tracking)
    • [1:52] -A DOCKER-CT ... -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
    • Analysis: This chain caught 1 packet. This is usually the returning or subsequent packet marked as ESTABLISHED. Since the connection is already recognized, it is immediately allowed to pass, bypassing further checks.
  • DOCKER-INTERNAL (Inter-container Communication)
    • [2:120] packets flowed through here. It seems they did not trigger any specific blocking rules and continued downward.
  • DOCKER-BRIDGE (Bridge to the DOCKER chain)
    • [2:120] -A DOCKER-BRIDGE -o docker0 -j DOCKER
    • Analysis: These 2 packets (the initial SYN and the final ACK of the handshake) are directed to the critical DOCKER chain.
3. The Destination: DOCKER Chain
  • [1:60] -A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT
  • Analysis: This rule precisely recorded 1 packet (60 bytes)—this is the SYN packet (the very first connection request).
  • It was accepted because it matched all criteria:
    1. Destination: The container’s private IP (172.17.0.2).
    2. Inbound: It did not originate from docker0 (meaning it came from an external source like box-02).
    3. Service: Targeted at Port 80.
  • Result: The packet was ACCEPTED, and the connection to the Nginx container was successful.
Why are the counts different?The rule in the DOCKER chain only captured 1 packet because only the “first packet (NEW)” of a connection initiation needs to undergo this complex inspection.Once the connection is established, all subsequent packets are quickly released by the ESTABLISHED rule within DOCKER-CT. This explains why the DOCKER-CT chain also shows a packet count. This is a performance optimization mechanism.

3.2 Terminating the nc Command TCP Connection

Next, we terminate the nc command on box-2 and observe the changes in packet counts again (as shown in the image below).

3.2.1 Observing the TCP Four-Way Handshakes (Connection Termination)

From the statistics table above, we observe that only two packets pass through the FORWARD rule when a TCP connection is closed. However, wait a moment—doesn’t TCP connection termination rely on the 「TCP four-way handshake 」mechanism? If so, in theory, we should observe four packets instead.
The standard TCP four-way handshake for connection termination works as follows:
  • Client → Server: FIN (I want to close the connection)
  • Server → Client: ACK (Acknowledged, but I’m still processing the remaining data)
  • Server → Client: FIN (I’m also ready to close the connection)
  • Client → Server: ACK (Acknowledged, goodbye)
To investigate this further, let’s use tcpdump to observe the packet changes when terminating the TCP connection of nc (as shown in the figure below).
  • Phase 1: Client Initiates Connection Closure 16:27:12.659835 IP 172.16.0.3.59810 > 172.17.0.2.80: Flags [F.], ...
    • Interpretation: The client (.0.3) sends a FIN packet to the server (.0.2).
    • iptables impact: This is a packet entering the container. FORWARD chain +1, DOCKER-CT +1.
  • Phase 2: Server Sends a Combined Response (Piggybacking) 16:27:12.660078 IP 172.17.0.2.80 > 172.16.0.3.59810: Flags [F.], ack 1, ...
    • Interpretation: After receiving the FIN, the server determines that it also has no more data to send, so it combines the ACK (acknowledging the client’s FIN) and the FIN (indicating it is also closing) into a single packet.
    • iptables impact: This is a packet leaving the container.FORWARD chain +1, i docker0 rule +1.
  • Phase 3: Final Acknowledgment 16:27:12.660598 IP 172.16.0.3.59810 > 172.17.0.2.80: Flags [.], ack 2, ...
    • Interpretation: After receiving the server’s FIN, the client sends the final ACK.
    • iptables impact: In theory, this should be the third packet, so why does your iptables counter only record two?
      • This is related to a subtle timing issue in how the Linux kernel handles connection tracking (conntrack):
        • Conntrack state transition: When the second packet (the server’s FIN/ACK) passes through the firewall, the Linux kernel’s state machine typically marks the connection as CLOSE_WAIT or LAST_ACK.
        • Counter classification: In some kernel versions or configurations, once a connection has entered the final stage of teardown, the last pure ACK packet may not be counted under the ESTABLISHED state statistics, or it may already have been garbage-collected by the conntrack subsystem before iptables-save is executed.
        • Your counter increments:
          • Packet 1 (incoming): Client FIN → DOCKER-CT (+1)
          • Packet 2 (outgoing): Server FIN/ACK → i docker0 (+1)
          • Total: The FORWARD chain increases by exactly 2.

Experimental Conclusion

  • Theory vs. Reality: Textbooks describe a four-way handshake, but in practice, the use of Flags [F.] (combining FIN and ACK) turns it into a three-step exchange, reducing network overhead.
  • Firewall Visibility: iptables counters are based on rule matching. For TCP connections that are about to disappear, the final ACK packet often becomes an “invisible member”—it completes its job, but does not always show up in the Filter Table statistics.

3.3 Let’s try the curl command

The biggest difference between using curl and nc is that curl performs a full HTTP request and response (data transfer), so the change in the number of bytes is much more significant than a simple TCP handshake. This time, by using the curl command, we not only establish a TCP connection but also retrieve the full content from the nginx-server. This allows us to observe the packet changes in the filter table during actual HTTP data transfer. The above figure shows a comparison of the filter table on box-2 before and after executing the curl command from box-1 We can observe that the yellow line increased by only 1 packet, while the blue line increased by 6 packets. Here’s the analysis:
  • Rule: -A DOCKER -d172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp--dport80 -j ACCEPT
    • This rule handles new connections
    • The incremented packet corresponds to the first packet of the TCP three-way handshake (SYN)
    • Size analysis: 60 bytes is the standard TCP SYN packet size (including headers)
    • Conclusion: Regardless of the webpage size curl fetches, this rule only counts once per new connection. It just “opens the door” and does not handle the subsequent data transfer
  • Rule: -A DOCKER-CT -o docker0 -m conntrack--ctstate RELATED,ESTABLISHED -j ACCEPT
    • This rule handles all subsequent packets of already established connections. In a single curl request, this includes:
      1. The 3rd packet of the TCP handshake (ACK)
      2. HTTP Request packet (the client’s GET request)
      3. Inbound packets during the TCP teardown
    • Size analysis: 392 bytes represents the combined size of the client’s HTTP header plus TCP control packets.
    • Conclusion: This is the core of Docker’s forwarding efficiency. Thanks to conntrack, subsequent data packets do not need to be matched against complex rules in the DOCKER chain (like destination IP or port checks), but are quickly allowed through the DOCKER-CT chain.
  • Overall Inbound / Outbound Traffic Comparison
    • Looking at i docker0 (traffic leaving the container): [9:1345] - [4:224] = Increment [+5:1121]
    • Key point: The byte count increased significantly (+1121 bytes).
    • Analysis: These 1121 bytes are primarily the HTML content returned by Nginx (HTTP Response). Since the response packets leave through docker0, they are counted under the rule: DOCKER-FORWARD -i docker0 -j ACCEPT

4. Delete the DOCKER-CT chain (conntrack) from the filter table

In this experiment, we will delete the DOCKER-CT conntrack rule and then try issuing a curl command from box-2 to see whether the data can still be successfully retrieved.
From the figure above, we can see that after removing the conntrack fast path, box-2 is still able to successfully retrieve data from the nginx-server container on box-1. However, what impact does this have?
  • Performance Degradation (CPU Overhead)
    • With conntrack: The kernel recognizes the traffic as part of an established connection and allows it to pass immediately (very fast table lookup).
    • Without conntrack: The kernel must re-evaluate every single packet—checking source/destination IPs, ports, and protocol each time. Under high traffic loads, this results in significantly higher CPU usage.
  • Reduced Security Even though the destination is restricted to 172.17.0.2:80, the presence or absence of conntrack (DOCKER-CT) makes a critical difference:
    • With conntrack (Stateful firewalling)
      • The firewall keeps track of whether a connection has completed the TCP three-way handshake.
      • If a packet arrives with the ACK flag set but the firewall has never seen the corresponding SYN, it is treated as invalid and dropped.
      • This helps protect against TCP scans and certain types of DDoS attacks.
    • Without conntrack (Stateless firewalling)
      • The firewall only checks the destination IP, protocol, and port, which leads to several risks:
        • State spoofing attacks: An attacker can send a large number of forged ACK packets. Although these packets will eventually be dropped by the container’s operating system (e.g., the Nginx kernel) because no matching socket exists, the “junk traffic” has already passed through the host firewall and entered the Docker virtual network, consuming host CPU resources and internal network bandwidth.
        • Bypassing certain inspections: Some Intrusion Detection Systems (IDS) rely on connection state to identify attacks. Without stateful inspection at the firewall level, attackers can more easily exploit fragmented packets to attempt to evade deeper inspection mechanisms.
Summary: We have lost a layer that could block non-compliant packets for the container.
  • Normal Situation: The host firewall helps Nginx by dropping any packets not belonging to known, legitimate connections.
  • Current Situation: The host firewall becomes “transparent glass”, any packet claiming to target port 80 is allowed through, shifting all the burden of filtering junk traffic entirely onto the Nginx process inside the container.

Conclusion

Now, we understand that using conntrack not only reduces the number of rule lookups in the iptables filter table for improving performance but also acts as a stateful firewall, blocking packets from connections that were never established, thereby enhancing security. This is one of the key technologies Docker uses to manage container networking.