All Products
Search
Document Center

Container Service for Kubernetes:Use an existing SLB instance to expose an application

Last Updated:Nov 20, 2024

To access a Service exposed by a Server Load Balancer (SLB) instance from outside the cluster, use the domain name of the SLB instance or the <IP:Service port> endpoint. To access the Service from within the cluster, use the <Service name:Service port> endpoint. This topic uses an NGINX application as an example to describe how to use a LoadBalancer Service that uses an existing SLB instance to expose an application.

Prerequisites

Usage notes

When you specify an existing SLB instance, how the listeners of the SLB instance are configured depends on the version of cloud-controller-manager.

  • cloud-controller-manager v1.9.3.59-ge3bc999-aliyun and later versions: When you specify an existing SLB instance, cloud-controller-manager does not configure listeners for the SLB instance by default. You can add the service.beta.kubernetes.io/alibaba-cloud-loadbalancer-force-override-listeners: "true" annotation to enable listeners, or manually configure listening rules for the SLB instance.

  • cloud-controller-manager versions earlier than v1.9.3.59-ge3bc999-aliyun: When you specify an existing SLB instance, cloud-controller-manager automatically creates backend server groups for the SLB instance and manages these backend server groups. It also ensures that the listeners of the SLB instance are associated with the backend server groups even if the listeners are manually configured.

How to view the version of cloud-controller-manager

Use the console

On the Add-ons page of the ACK cluster, view the version of cloud-controller-manager.

  1. Log on to the ACK console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, find the cluster that you want to manage and click its name. In the left-side navigation pane, choose Operations > Add-ons.

  3. On the Core Components tab of the Add-ons page, view the version of Cloud Controller Manager.

Use kubectl (applicable to ACK dedicated clusters)

kubectl get pod -n kube-system -o yaml|grep image:|grep cloud-con|uniq

Precautions

Before you use an existing SLB instance to expose an application, we recommend that you read the precautions. For more information, see the following topics:

Step 1: Deploy an application

This topic uses an NGINX stateless application as an example to demonstrate how to use a LoadBalancer Service to expose an application.

Use the ACK console

  1. Log on to the ACK console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, find the cluster that you want to manage and click its name. In the left-side pane, choose Workloads > Deployments.

  3. On the Deployments page, click Create from Image and configure the basic information, container settings, and advanced settings of the Deployment.

    1. On the Basic Information wizard page, specify Name, keep the default settings for other parameters, and click Next. In this example, the name is set to my-nginx.

    2. On the Container wizard page, specify the image name and container ports, keep the default settings for other parameters, and click Next.

      Parameter

      Valid value

      Image Name

      Click Select images. In the Select images and image tags dialog box, click the Artifact Center tab, search for nginx, and select the image repository named openanolis/nginx. Then, click Select Image Tag, set an image tag, and click OK.

      Port

      • Name: nginx.

      • Container Port: 80.

    3. On the Advanced wizard page, keep the default settings and click Create to create an NGINX application.

Use kubectl

  1. Create a file named my-nginx.yaml file and add the following YAML content to the file:

    apiVersion: apps/v1 # for versions before 1.8.0 use apps/v1beta1
    kind: Deployment
    metadata:
      name: my-nginx    # The name of the sample application. 
      labels:
        app: nginx
    spec:
      replicas: 2       # The number of replicated pods. 
      selector:
        matchLabels:
          app: nginx     # You must specify the same value in the selector of the Service that is used to expose the application. 
      template:
        metadata:
          labels:
            app: nginx
        spec:
        #  nodeSelector:
        #    env: test-team
          containers:
          - name: nginx
            image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
            ports:
            - containerPort: 80                                # The port that you want to expose in the Service.

  2. Run the following command to deploy the my-nginx application:

    kubectl apply -f my-nginx.yaml
  3. Run the following command to query the status of the application:

    kubectl get deployment my-nginx

    Expected output:

    NAME       READY   UP-TO-DATE   AVAILABLE   AGE
    my-nginx   2/2     2            2           50s

Step 2: Create a LoadBalancer Service that uses an existing SLB instance to expose the application

You can use the ACK console or kubectl to create a LoadBalancer Service to expose the application.

Use the ACK console

  1. Log on to the ACK console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, find the cluster that you want to manage and click its name. In the left-side pane, choose Network > Services.

  3. On the Services page, click Create. In the Create Service dialog box, configure the required parameters.

    Parameter

    Description

    Example

    Name

    The name of the Service.

    my-nginx-svc

    Service Type

    Specify Service Type. You can create the following types of Services to handle access from different types of sources:

    Cluster IP

    A ClusterIP Service. This type of Service is used for communication within the cluster. Only ClusterIP Services can discover and communicate with each other. If you select Headless Service, you can interact with other service discovery mechanisms without the need to rely on the ClusterIP-based service discovery and load balancing features provided by Kubernetes by default.

    SLB.

    SLB allows you to create LoadBalancer Services to expose applications in a cluster by using CLB instances or NLB instances. Compared with NodePort Services, the availability and performance of applications exposed by using LoadBalancer Services are greatly improved. Supported SLB instances:

    • CLB: For more information, see CLB.

    • NLB: For more information, see NLB.

    Node Port

    A NodePort Service. External users can access this type of Services by using the IP address and specified port of a node. You can connect to a NodePort Service through <NodeIP>:<NodePort>. However, you must manually configure load balancing.

    1. Select SLB.

    2. Click Use Existing Resource and select a CLB instance from the drop-down list.

      The CLB instance in this example is newly created. You must configure listeners for the CLB instance. Therefore, select Overwrite Existing Listeners.

    External Traffic Policy

    The External Traffic Policy parameter is available only if you set the Service Type parameter to Node Port or Server Load Balancer. For more information about external traffic policies, see the Differences between external traffic policies section of the "Getting started" topic. Valid values:

    • Local: routs traffic only to the pods of the current node.

    • Cluster: routes traffic to pods on other nodes in the cluster.

    Local

    Backend

    The backend application that you want to associate with the Service. If you do not select a backend application, no Endpoint objects are created. For more information, see Services-without-selectors.

    Name: app.

    Value: my-nginx.

    Port Mapping

    The Service port and container port. The Service port corresponds to the port field in the YAML file and the container port corresponds to the targetPort field in the YAML file. The container port must be the same as the port that is exposed in the backend pod.

    80

    Annotations

    The annotations to be added to the Service to configure the SLB instance. For more information, see Use annotations to configure CLB instances and Use annotations to configure NLB instances.

    Important

    Do not reuse the SLB instance of the API server in the cluster. Otherwise, cluster access failures may occur.

    In this example, two annotations are added to specify the pay-by-bandwidth billing method and set the maximum bandwidth to 2 Mbit/s to limit the amount of traffic that flows through the Service. Example:

    • service.beta.kubernetes.io/alibaba-cloud-loadbalancer-charge-type:paybybandwidth

    • service.beta.kubernetes.io/alibaba-cloud-loadbalancer-bandwidth:2

    Label

    The label to be added to the Service, which identifies the Service.

    None

    Service Deletion Protection

    Enable deletion protection for Services involving critical business or sensitive data to avoid maintenance costs associated with accidental deletions. After you enable this feature, you must manually disable it before deleting any resources.

    Note

    You must first install policy-template-controller and gatekeeper for management of container security policies. On your cluster details page, choose Operations > Add-ons. You will find these components. Click Install to deploy these components.

    Disabled

    Click OK.

  4. On the Services page, click the name of the Service to go to the details page. In the Basic Information section, click the External Endpoint of the Service, such as 39.106.XX.XX:80, to access the application.

Use kubectl

  1. Create a Service.

    Create a file named my-nginx-svc.yaml and add the following content to the file.

    • Replace ${YOUR_LB_ID} in service.beta.kubernetes.io/alibaba-cloud-loadbalancer-id with the ID of the SLB instance that you created in the SLB console.

    • If you use an existing SLB instance, no listeners are created for the SLB instance and the existing listeners of the SLB instance are not overridden by default. To override the listeners, set service.beta.kubernetes.io/alibaba-cloud-loadbalancer-force-override-listeners to "true". In this example, the annotation is set to true to create listeners for the SLB instance because the SLB instance is newly created. For more information about annotations, see Use annotations to configure CLB instances and Use annotations to configure NLB instances.

    • Set selector to the value of matchLabels in the my-nginx.yaml file, which is app: nginx. This way, the Service is associated with the backend pod.

    apiVersion: v1
    kind: Service # Define a Service. 
    metadata:
      annotations:
        service.beta.kubernetes.io/alibaba-cloud-loadbalancer-id: ${YOUR_LB_ID}
        service.beta.kubernetes.io/alicloud-loadbalancer-force-override-listeners: 'true'
      labels:
        app: nginx
      name: my-nginx-svc
      namespace: default
    spec:
      ports:
      - port: 80
        protocol: TCP
        targetPort: 80
      selector:
        app: nginx
      type: LoadBalancer

    Parameter

    Description

    kind

    Specifies that the resource object is a Service.

    metadata

    Defines the basic information about the Service, such as the name, labels, and namespace.

    metadata.annotations

    You can add LoadBalancer annotations. In this example, the annotation service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type is set to intranet, which specifies that the Service is accessible over the internal network. For more information, see Use annotations to configure CLB instances.

    spec.selector

    Defines the label selector of the Service. The Service exposes the pods whose labels match the label selector.

    spec.ports.port

    Specifies the Service port that is exposed with the cluster IP address. You can access the Service from within the cluster by sending requests to clusterIP:port.

    spec.ports.targetPort

    Specifies the port of the backend pod to receive traffic. The traffic that flows through the Service port is forwarded by kube-proxy to the port (specified by targetPort) of the backend pod and then reaches the containers.

    spec.type

    Defines how the Service is accessed.

    • LoadBalancer: The Service is exposed by using an SLB instance. When no SLB instance is specified for the Service, an Internet-facing SLB instance is created by default. You can set the annotation to intranet to create an internal-facing SLB instance to expose the Service to internal access. For more information, see Use annotations to configure CLB instances and Use annotations to configure NLB instances.

    • ClusterIP: exposes the Service within the cluster. A ClusterIP Service is accessible from within the cluster.

    • NodePort: maps a node port to the backend Service. You can access the Service from outside the cluster by sending requests to NodeIP:NodePort.

    • ExternalName: maps the Service to a DNS server.

  2. Run the following command to create a Service named my-nginx-svc and use the Service to expose the application:

    kubectl apply -f my-nginx-svc.yaml
  3. Run the following command to confirm that the LoadBalancer Service is created:

    kubectl get svc my-nginx-svc

    Expected output:

    NAME           TYPE           CLUSTER-IP    EXTERNAL-IP      PORT(S)        AGE
    my-nginx-svc   LoadBalancer   172.21.5.82   39.106.XX.XX     80:30471/TCP   5m
  4. Run the following command to access the application:

    curl <YOUR-External-IP> # Replace <YOUR-External-IP> with the external IP address that you obtained in the preceding step.

    Expected output:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Welcome to nginx!</title>
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
    </head>
    <body>
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
    working. Further configuration is required.</p>
    
    <p>For online documentation and support please refer to
    <a href="http://nginx.org/">nginx.org</a>.<br/>
    Commercial support is available at
    <a href="http://nginx.com/">nginx.com</a>.</p>
    
    <p><em>Thank you for using nginx.</em></p>
    </body>
    </html>

CLB

Create CLB Instance

If you select Create CLB Instance, you can set the access mode of the CLB instance to public access or internal access and the billing method of the CLB instance to pay-by-specification or pay-as-you-go. For more information, see Create and manage a CLB instance.

Parameter

Description

Name

Name of the CLB instance. This parameter is required only if you create a CLB instance.

Access Method

Valid values: Public Access and Internal Access.

Billing Method

Valid values: Pay-by-specification and Pay-as-you-go (Pay-by-CU). For more information, see CLB billing overview.

IP Version

Version of the IP address. Valid values: IPv4 and IPv6.

Scheduling Algorithm

Valid values: Round Robin (RR) and Weighted Round Robin (WRR). Default value: Round Robin (RR). Round Robin (RR): Requests are distributed to backend servers in sequence. Weighted Round Robin (WRR): Backend servers with higher weights receive more requests than those with lower weights.

Access Control

Specify whether to enable the access control feature for the listener. For more information, see Access control.

Health Check

Specify whether to enable the health check feature. You can set the Health Check Protocol parameter to TCP or HTTP. After the health check feature is enabled, you can determine the service availability of backend servers by using the health check feature. For more information about how health checks work, see How CLB health checks work.

Others

You can also use annotations to configure CLB instances. For more information, see Use annotations to configure CLB instances.

Use Existing CLB Instance

You can select an existing CLB instance from the drop-down list below Use Existing CLB Instance. You can also choose whether to enable Overwrite Existing Listeners. For more information, see Use an existing CLB instance and forcefully overwrite the listeners of the CLB instance.

Important

You must take note of some limits and usage notes when you use an existing CLB instance. For more information, see the Usage notes section of the "Considerations for configuring a LoadBalancer Service" topic.

Advanced Settings

Parameter

Description

Scheduling Algorithm

Valid values: Round Robin (RR) and Weighted Round Robin (WRR). Default value: Round Robin (RR). Round Robin (RR): Requests are distributed to backend servers in sequence. Weighted Round Robin (WRR): Backend servers with higher weights receive more requests than those with lower weights.

Access Control

Specify whether to enable the access control feature for the listener. For more information, see Access control.

Health Check

Specify whether to enable the health check feature. You can set the Health Check Protocol parameter to TCP or HTTP. After the health check feature is enabled, you can determine the service availability of backend servers by using the health check feature. For more information about how health checks work, see How CLB health checks work.

Others

You can also use annotations to configure CLB instances. For more information, see Use annotations to configure CLB instances.

NLB

Create NLB Instance

If you select Create NLB Instance, you can set the access mode of the NLB instance to public access or internal access. For more information, see Create and manage an NLB instance.

Parameter

Description

Name

Name of the NLB instance. This parameter is required only if you create an NLB instance.

Access Method

Valid values: Public Access and Internal Access.

Billing Method

Valid value: Pay-as-you-go (Pay-by-CU). For more information, see NLB billing.

IP Version

Version of the IP address. Valid values: IPv4 and Dual-stack.

Scheduling Algorithm

Valid values:

  • Round-Robin: Requests are forwarded to backend servers in sequence.

  • Weighted Round-Robin (default): Backend servers that have higher weights receive more requests than backend servers that have lower weights.

  • Source IP Hashing: specifies consistent hashing that is based on source IP addresses. Requests from the same source IP address are distributed to the same backend server.

  • Four-Element Hashing: specifies consistent hashing that is based on the following factors: source IP address, destination IP address, source port, and destination port. Requests that contain the same information based on the preceding factors are forwarded to the same backend server.

  • QUIC ID Hashing: specifies consistent hashing based on QUIC IDs. Requests with the same QUIC ID are forwarded to the same backend server.

  • Weighted Least Connections: Requests are forwarded based on the weights and number of connections to backend servers. If two backend servers have the same weight, the backend server that has fewer connections receives more requests.

Health Check

Specify whether to enable the health check feature.

  • TCP (default): To perform TCP health checks, NLB sends SYN packets to a backend server to check whether the port of the backend server can receive requests.

    • Health Check Response Timeout: the amount of time to wait before you receive a response from a health check. If a backend server does not respond within the specified timeout period, the backend server is considered unhealthy.

    • Health Check Interval: the interval at which health checks are performed.

    • Healthy Threshold: the minimum number of times that a backend server must consecutively pass health checks before the backend server is considered healthy.

    • Unhealthy Threshold: the minimum number of times that a backend server must consecutively fail to pass health checks before the backend server is considered unhealthy.

  • HTTP: To perform HTTP health checks, NLB sends HEAD or GET requests to a backend server to check whether the backend server is healthy.

    • Domain Name: the domain name that is used for the health check.

      • Backend Server Internal IP (default): uses the private IP addresses of backend servers for health checks.

      • Custom Domain Name: Enter a domain name.

    • Path: the URL of the health check page.

    • Health Check Status Codes: the status code that is returned for a health check. Valid values: http_2xx, http_3xx, http_4xx, and http_5xx. Default value: http_2xx.

Others

You can also use annotations to configure NLB instances. For more information, see Use annotations to configure NLB instances.

VPC

Default cluster VPC region and VPC ID.

Vswitch

You can choose the vSwitches in the zones supported by the instance in the VPC, or create a new one.

Use Existing NLB Instance

If you select Use Existing NLB Instance, you can select an existing NLB instance from the drop-down list below Use Existing NLB Instance. You can also choose whether to enable Overwrite Existing Listeners. For more information, see Use an existing NLB instance.

Important

You must take note of some limits and usage notes when you use an existing NLB instance. For more information, see Usage notes section of the "Considerations for configuring a LoadBalancer Service" topic.

Advanced Settings

Parameter

Description

Scheduling Algorithm

Valid values:

  • Round-Robin: Requests are forwarded to backend servers in sequence.

  • Weighted Round-Robin (default): Backend servers that have higher weights receive more requests than backend servers that have lower weights.

  • Source IP Hashing: specifies consistent hashing that is based on source IP addresses. Requests from the same source IP address are distributed to the same backend server.

  • Four-Element Hashing: specifies consistent hashing that is based on the following factors: source IP address, destination IP address, source port, and destination port. Requests that contain the same information based on the preceding factors are forwarded to the same backend server.

  • QUIC ID Hashing: specifies consistent hashing based on QUIC IDs. Requests with the same QUIC ID are forwarded to the same backend server.

  • Weighted Least Connections: Requests are forwarded based on the weights and number of connections to backend servers. If two backend servers have the same weight, the backend server that has fewer connections receives more requests.

Health Check

Specify whether to enable the health check feature.

  • TCP (default): To perform TCP health checks, NLB sends SYN packets to a backend server to check whether the port of the backend server can receive requests.

    • Health Check Response Timeout: the amount of time to wait before you receive a response from a health check. If a backend server does not respond within the specified timeout period, the backend server is considered unhealthy.

    • Health Check Interval: the interval at which health checks are performed.

    • Healthy Threshold: the minimum number of times that a backend server must consecutively pass health checks before the backend server is considered healthy.

    • Unhealthy Threshold: the minimum number of times that a backend server must consecutively fail to pass health checks before the backend server is considered unhealthy.

  • HTTP: To perform HTTP health checks, NLB sends HEAD or GET requests to a backend server to check whether the backend server is healthy.

    • Domain Name: the domain name that is used for the health check.

      • Backend Server Internal IP: uses the private IP addresses of backend servers for health checks. This is the default value.

      • Custom Domain Name: Enter a domain name.

    • the URL of the health check page.

    • Health Check Status Codes: the status code that is returned for a health check. Valid values: http_2xx, http_3xx, http_4xx, and http_5xx. Default value: http_2xx.

Others

You can also use annotations to configure NLB instances. For more information, see Use annotations to configure NLB instances.

VPC

Default cluster VPC region and VPC ID.

Vswitch

You can choose the vSwitches in the zones supported by the instance in the VPC, or create a new one.

What to do next

You can view, update, and delete Services. For example, you can modify the Internet-facing SLB instance of a Service.

Use the ACK console

  1. Log on to the ACK console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, find the cluster that you want to manage and click its name. In the left-side pane, choose Network > Services.

  3. On the Services page, you can click a Service to view details or click Update or Delete in the Actions column of the Service to update or delete the Service.

Use kubectl

Update a Service

  • Method 1: Run the following command to update a Service:

    kubectl edit service my-nginx-svc
  • Method 2: Manually delete a Service, modify the YAML file, and then recreate the Service.

    kubectl apply -f my-nginx-svc.yaml

View a Service

Run the following command to view a Service:

kubectl get service my-nginx-svc

Expected output:

NAME           TYPE           CLUSTER-IP    EXTERNAL-IP      PORT(S)        AGE
my-nginx-svc   LoadBalancer   172.21.XX.XX   192.168.XX.XX     80:31599/TCP   5m

Delete a Service

Run the following command to delete a Service:

kubectl delete service my-nginx-svc