Search code examples
kubernetescloudiptableskubernetes-podnetwork-security

How to modify source IP for a Pod in Kubernetes?


To change the source IP to 100.101.102.103 for outgoing data to a specific destination, I modified iptables inside the container of a Kubernetes Pod by executing iptables CLI tool:

iptables -t nat -A POSTROUTING --destination 100.200.150.50/32 -j SNAT --to-source 100.101.102.103

But it blocks my outgoing data to that destination and seems like the data is caught inside the container for example when I send a simple request by Curl and watch it by Tcpdump tool.

The main question can be: How to modify source IP for a Pod in Kubernetes for a destination outside the cluster?

P.S. I deployed my pod in privileged mode with NET_ADMIN and NET_RAW access.


Solution

  • I modified iptables inside the container of a Kubernetes Pod

    I suggest not to do this as it may corrupt kubernetes' CNI and/or kube-proxy. Instead, consider using kubernetes egress to have a well-known source IP address in outgoing packets to a destination outside the cluster.

    Egress packets from a k8s cluster to a destination outside the cluster have node's IP as the source IP.

    https://kubernetes.io/docs/tutorials/services/source-ip/ says egress packets from k8s get source NAT'ed with node's IP:

    Source NAT: replacing the source IP on a packet, usually with a node’s IP

    Following can be used to send egress packets from a k8s cluster: