Obtaining the Client Source IP Address for a Container

Background

There may be different types of proxy servers between a client and a container server. How can a container obtain the real source IP address of the client? This section describes several scenarios you may encounter.

Principles

Layer-7 forwarding:

Ingress: If this access mode is used, the client source IP address is saved in the X-Forwarded-For HTTP header field by default. No other configuration is required.

Layer-4 forwarding:

Ingress

Configure the application server and obtain the IP address of a client from the HTTP header.

The real IP address is placed in the X-Forwarded-For HTTP header field by the load balancer in the following format:

X-Forwarded-For: IP address of the client,Proxy server 1-IP address,Proxy server 2-IP address,...

If you use this method, the first IP address obtained is the IP address of the client.

For details, see How Can I Obtain the IP Address of a Client?

  • When adding an ingress, if the backend service is of the NodePort type, set Service Affinity to Node level, that is, set spec.externalTrafficPolicy to Local. For details, see NodePort.

LoadBalancer

For a LoadBalancer Service, different types of clusters obtain source IP addresses in different scenarios. In some scenarios, source IP addresses cannot be obtained currently.

VPC and Container Tunnel Network Models

To obtain source IP addresses, perform the following steps:

  1. When creating a LoadBalancer Service on the CCE console, set Service Affinity to Node level instead of Cluster level.

  2. Go to the ELB console and enable the function of obtaining the client IP address of the listener corresponding to the load balancer. Transparent transmission of source IP addresses is enabled for dedicated load balancers by default. You do not need to manually enable this function.

    1. Log in to the ELB console.
    2. Click in the upper left corner to select the desired region and project.
    3. Click Service List. Under Networking, click Elastic Load Balance.
    4. On the Load Balancers page, click the name of the load balancer.
    5. Click Listeners.
      • To add a listener, click Add Listener.
      • To modify a listener, locate the listener and click the edit button on the right of its name.
    6. Enable Obtain Client IP Address.

NodePort

Set the service affinity of a NodePort Service to Node level instead of Cluster level. That is, set spec.externalTrafficPolicy of the Service to Local.