Connection Tracking and NAT

NAT rules on a Node send a new Service connection to one Pod, later packets usually follow, and replies come from the Service IP. How is the choice remembered, why do they skip NAT, and what limits that memory?

Play the animation 5 steps, animated, plays on a computer or a tablet

Connection Tracking and NAT, Kubernetes diagram

Connection Tracking and NAT, step by step

  1. The client dials a Service address that no host owns, and the first packet of the flow reaches netfilter. There is no conntrack entry matching this packet, so nothing about this connection has been decided yet.

    Play from step 1
  2. With no entry to match, the NAT rules have to be walked. The chain is read top to bottom until a rule claims the destination and a backend is chosen for this connection. The first packet of every new flow pays this walk, and no later packet of that flow pays again while the entry lives.

    Play from step 2
  3. The flow is now recorded by conntrack as one entry with two tuples: the original direction the client sent, and the reply direction the client expects back. The destination is rewritten to the chosen backend and the packet delivered, with the mapping stored as long as the entry lives.

    Play from step 3
  4. The backend answers from its own address, and the packet matches the reply tuple of the stored entry. That match alone undoes the translation, so the client sees an answer from the Service address it dialed, and the reply is what flips the entry to ESTABLISHED. Not one NAT rule is read on the way back.

    Play from step 4
  5. Every later packet of this flow matches the original tuple and is translated straight off the entry, leaving the rule ladder untouched. That is why a flow stays on one backend while its entry lives. For the same reason a Node opening huge numbers of short connections can fill its conntrack table and start dropping new ones.

    Play from step 5

Sources