How do I restrict CIDR IP addresses for a LoadBalancer type service in Amazon EKS?

Last updated: 2021-08-23

I want to restrict CIDR IP addresses for a LoadBalancer type service in Amazon Elastic Kubernetes Service (Amazon EKS).

Short description

If you create a service of type:LoadBalancer, then requests from the source are allowed by default. If your load balancer is in a public subnet, then requests are routed to worker nodes from anywhere on the internet.


Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

Set up your environment

1.    Create an Amazon EKS cluster.

2.    Create and launch worker nodes.

3.    Set up kubectl.

4.    Set up the AWS CLI.

5.    Set up the AWS Load Balancer Controller.

Note: The AWS Load Balancer Controller supports the following versions of the AWS Network Load Balancer for Services of type LoadBalancer: NLB ip mode (version 2.0.0 or above) and NLB instance mode (2.2.0 or above)

Important: It's a best practice to use the AWS Load Balancer Controller when you provision a new Network Load Balancer for Services of type LoadBalancer. Use the AWS Load Balancer Controller instead of the Kubernetes in-tree service load balancer controller.

Restrict CIDR IP addresses

1.    In your service manifest file (svc.yaml), add the .spec.loadBalancerSourceRanges field. For example:

apiVersion: v1
kind: Service
    app: nginx
  name: nginx
  annotations: "external" "instance" "internet-facing"
  - port: 80
    protocol: TCP
    targetPort: 80
    app: nginx
  type: LoadBalancer
  - ""

2.    To apply the manifest file, run the following command:

$ kubectl apply -f svc.yaml

3.    To confirm that the inbound rules on the security group are modified, run the following AWS CLI command:

$ aws ec2 describe-security-groups --group-ids sg-XXXXXXXXXXXXXXXXX
    "CidrIp": ""

Finally, consider the following:

If you use NLB ip mode, then the .spec.loadBalancerSourceRanges field is ignored by default. In this case, use the following annotation: preserve_client_ip.enabled=true

This annotation enables Client IP preservation.

For a service with a Network Load Balancer type, consider the maximum security group limit. For each node port and subnet CIDR range, the controller creates rules on the worker node's security group.

Did this article help?

Do you need billing or technical support?