Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Cloud Container Engine/ Best Practices/ Auto Scaling/ Auto Scaling of Multiple Applications Using Nginx Ingresses

Auto Scaling of Multiple Applications Using Nginx Ingresses

Updated on 2025-01-08 GMT+08:00

Deploying applications in multiple pods in a production environment can enhance their stability and reliability, but it can also lead to increased resource waste and costs. To strike a balance between resource utilization and application performance, manually adjusting the number of pods may not be efficient or effective.

However, if the application uses Nginx ingresses to route and forward external traffic, you can configure HPA policies using the nginx_ingress_controller_requests metric. This allows for dynamic adjustment of pods based on traffic changes, optimizing resource utilization.

Prerequisites

  • The NGINX Ingress Controller add-on has been installed in the cluster.
  • You have installed the Cloud Native Cluster Monitoring add-on in the cluster and enabled Local Data Storage for the add-on.
  • You have connected the cluster with the kubectl command line tool or CloudShell.
  • The pressure testing tool Apache Benchmark has been installed.

Creating a Workload and a Service for the Workload

This section provides an example of how to route external traffic for two Services using Nginx ingresses.

  1. Create a test-app workload and a Service for it.

    1. Write a test-app.yaml file.
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: test-app
        labels:
          app: test-app
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: test-app
        template:
          metadata:
            labels:
              app: test-app
          spec:
            containers:
            - image: skto/sample-app:v2
              name: metrics-provider
              ports:
              - name: http
                containerPort: 8080
      --- 
      apiVersion: v1
      kind: Service
      metadata:
        name: test-app
        namespace: default
        labels:
          app: test-app
      spec:
        ports:
          - port: 8080
            name: http
            protocol: TCP
            targetPort: 8080
        selector: 
          app: test-app 
        type: ClusterIP
    2. Deploy the test-app workload and the corresponding Service.
      kubectl apply -f test-app.yaml

  2. Create a sample-app workload and a Service for it.

    1. Write a sample-app.yaml file.
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: sample-app
        labels:
          app: sample-app
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: sample-app
        template:
          metadata:
            labels:
              app: sample-app
          spec:
            containers:
            - image: skto/sample-app:v2
              name: metrics-provider
              ports:
              - name: http
                containerPort: 8080
      --- 
      apiVersion: v1
      kind: Service
      metadata:
        name: sample-app
        namespace: default
        labels:
          app: sample-app
      spec:
        ports:
          - port: 80
            name: http
            protocol: TCP
            targetPort: 8080
        selector:
          app: sample-app
        type: ClusterIP
    2. Deploy the sample-app workload and the corresponding Service.
      kubectl apply -f sample-app.yaml

  3. Deploy an ingress.

    1. Write an ingress.yaml file.
      apiVersion: networking.k8s.io/v1
      kind: Ingress
      metadata:
        name: test-ingress
        namespace: default
      spec:
        ingressClassName: nginx
        rules:
          - host: test.example.com
            http:
              paths:
                - backend:
                    service:
                      name: sample-app
                      port:
                        number: 80
                  path: /
                  pathType: ImplementationSpecific
                - backend:
                    service:
                      name: test-app
                      port:
                        number: 8080
                  path: /home
                  pathType: ImplementationSpecific
      • host: specifies the Service access domain name. In this example, test.example.com is used.
      • path: specifies the URL to be accessed. After receiving a request, the system matches the request with the corresponding Service based on the routing rules and accesses the corresponding pod through the Service.
      • backend: consists of the Service name and Service port and specifies the Service forwarded by the current path.
    2. Deploy an ingress.
      kubectl apply -f ingress.yaml
    3. Obtain an ingress.
      kubectl get ingress -o wide

    4. After the deployment is successful, log in to the target node and add the service domain name and the IP address of the load balancer associated with NGINX Ingress Controller to the local hosts file of the node. The IP address of the load balancer associated with NGINX Ingress Controller is that obtained in 3.c.
      export NGINXELB=xx.xx.xx.xx 
      echo -n "${NGINXELB}  test.example.com" >> /etc/hosts
    5. Log in to the cluster node and access the host address through the / and /home paths.

      NGINX Ingress Controller accesses sample-app and test-app based on the preceding configurations.

      # curl test.example.com/
      Hello from '/' path!
      
      # curl test.example.com/home
      Hello from '/home' path!

Modifying user-adapter-config in Prometheus

  1. Run the following command to edit user-adapter-config:

    kubectl -n monitoring edit configmap user-adapter-config

  2. Add the following rules to the ConfigMap of the adapter:

    apiVersion: v1
    data:
      config.yaml: |
        rules:
        - metricsQuery: sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)
          name:
            as: ${1}_per_second
            matches: ^(.*)_requests
          resources:
            namespaced: false
            overrides:
              exported_namespace:
                resource: namespace
              service:
                resource: service
          seriesQuery: nginx_ingress_controller_requests
        resourceRules:
          cpu:
            containerQuery: sum(rate(container_cpu_usage_seconds_total{<<.LabelMatchers>>,container!="",pod!=""}[1m])) by (<<.GroupBy>>)
            nodeQuery: sum(rate(container_cpu_usage_seconds_total{<<.LabelMatchers>>, id='/'}[1m])) by (<<.GroupBy>>)
            resources:
              overrides:
                instance:
                  resource: node
                namespace:
                  resource: namespace
                pod:
                  resource: pod
            containerLabel: container
          memory:
            containerQuery: sum(container_memory_working_set_bytes{<<.LabelMatchers>>,container!="",pod!=""}) by (<<.GroupBy>>)
            nodeQuery: sum(container_memory_working_set_bytes{<<.LabelMatchers>>,id='/'}) by (<<.GroupBy>>)
            resources:
              overrides:
                instance:
                  resource: node
                namespace:
                  resource: namespace
                pod:
                  resource: pod
            containerLabel: container

  3. Restart custom-metrics-apiserver.

    kubectl -n monitoring delete pod -l app=custom-metrics-apiserver

  4. Log in to the cluster node and access the host address through the / and /home paths for multiple times.

    # curl test.example.com/
    Hello from '/' path!
    
    # curl test.example.com/home
    Hello from '/home' path!

  5. Run the following command to check whether the metric is added:

    kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/default/services/*/nginx_ingress_controller_per_second | python -m json.tool

Creating an HPA Policy

  1. Create an hpa.yaml file and configure auto scaling for the test-app and sample-app workloads based on Prometheus metrics.

    apiVersion: autoscaling/v2 
    kind: HorizontalPodAutoscaler 
    metadata: 
      name: sample-hpa  # HPA name
    spec: 
      scaleTargetRef: 
        apiVersion: apps/v1 
        kind: Deployment 
        name: sample-app  # Deployment name
      minReplicas: 1      # Minimum number of pods
      maxReplicas: 10     # Maximum number of pods
      metrics: 
        - type: Object 
          object: 
            metric: 
              name: nginx_ingress_controller_per_second  # Metric
            describedObject: 
              apiVersion: v1 
              kind: service 
              name: sample-app  # Service of the Deployment
            target: 
              type: Value 
              value: 30   # Scaling is triggered when the metric value is within the range of (Actual value/30)±0.1.
    --- 
    apiVersion: autoscaling/v2 
    kind: HorizontalPodAutoscaler 
    metadata: 
      name: test-hpa 
    spec: 
      scaleTargetRef: 
        apiVersion: apps/v1 
        kind: Deployment 
        name: test-app 
      minReplicas: 1 
      maxReplicas: 10 
      metrics: 
        - type: Object 
          object: 
            metric: 
              name: nginx_ingress_controller_per_second 
            describedObject: 
              apiVersion: v1 
              kind: service 
              name: test-app 
            target: 
              type: Value 
              value: 30

  2. Deploy the HPA policy.

    kubectl apply -f hpa.yaml

  3. Check the HPA deployment.

    kubectl get hpa

Verifying Scaling

  1. Log in to the target cluster node and perform a pressure testing on the /home path.

    ab -c 50 -n 5000 test.example.com/home

  2. Check the HPA.

    kubectl get hpa

  3. Log in to the target cluster node and perform a pressure testing on the root path.

    ab -c 50 -n 5000 test.example.com/

  4. Check the HPA.

    kubectl get hpa

    Compared with the HPA metrics obtained before the pressure testing, the service application is scaled out when the number of requests exceeds the threshold.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback