Help Center/ Cloud Container Engine/ Best Practices/ Container/ Upgrading a Pod Without Interrupting Services
Updated on 2026-11-16 GMT+08:00

Upgrading a Pod Without Interrupting Services

Applications

In a Kubernetes cluster, applications can be accessed externally by deploying in Deployments with the LoadBalancer Services. When an application is updated or upgraded, new pods are created for the Deployment. These new pods will gradually replace the old ones. During this process, services may be interrupted.

Solution

To prevent application upgrades from interrupting services, configure Deployments and Services as follows:

  • In a Deployment, upgrade pods in the Rolling upgrade mode. In this mode, pods are updated one by one, not all at once. In this way, you can control the upgrade speed and the number of concurrent pods to ensure that services are not interrupted during the upgrade. For example, you can configure the maxSurge and maxUnavailable parameters to control the number of new pods created and the number of old pods deleted concurrently. Ensure that there is always a workload that can provide services during the upgrade.
    The following mechanisms are also required to ensure smooth traffic throughout the upgrade:
    • Startup probe: provides a dedicated startup detection window for slow-starting applications, preventing premature liveness/readiness probe failures and repeated pod restarts.
    • Readiness probe: determines when a pod can receive traffic. Unready pods are removed from Service endpoints so only healthy pods handle requests.
    • readinessGates: ensures a pod is registered with the ELB backend before receiving traffic. In LoadBalancer Services, pod readiness alone does not guarantee ELB registration.
    • Graceful termination (preStop hook + terminationGracePeriodSeconds): allows time to drain established connections (especially persistent connections) before SIGKILL terminates the pod. When a pod is deleted, the preStop hook delays termination to allow established connections (especially persistent connections) to drain. This hook operates within the terminationGracePeriodSeconds window, ensuring the pod is not killed by SIGKILL before completing its shutdown sequence.
  • There are two types of service affinity in a LoadBalancer:
    • Cluster-level service affinity (externalTrafficPolicy: Cluster). In this mode, if there is no pod deployed on a node, the request is forwarded to pods on another node. During the cross-node forwarding, the source IP address may be lost.
    • Node-level service affinity (externalTrafficPolicy: Local). In this mode, requests are directly forwarded to the node where the pod resides. Cross-node forwarding is not involved. Therefore, the source IP address can be preserved. However, if the node where the pod resides changes during the rolling upgrade, the ELB backend server will change accordingly, which may cause service interruption. In this case, you can upgrade pods in place. This ensures that there is at least one pod running properly on the ELB backend node.

The table below lists the solutions to ensure service continuity during a pod upgrade.

Scenario

Service

Deployment

The source IP address does not need to be preserved.

Select the Cluster-level service affinity.

Rolling upgrade + Startup/Liveness/Readiness probes + readinessGates + Graceful termination

The source IP address needs to be preserved.

Select the Node-level service affinity.

Rolling upgrade + Startup/Liveness/Readiness probes + readinessGates + Graceful termination + Node affinity (ensures at least one running pod per node during upgrade)

Traffic Processing During a Rolling Update

  • New pod rollout: Once the startup probe succeeds, the readiness probe begins detecting the pod's state. Concurrently, readinessGates verifies ELB backend registration. The pod is marked Ready and begins receiving traffic only after all checks pass.
  • Old pod removal: After the new pod is ready and maxUnavailable constraints are satisfied, the old pod is removed from endpoints. The preStop hook executes to allow time for traffic rules to propagate. Once the hook completes, SIGTERM is sent to signal graceful shutdown. If the application does not exit within the terminationGracePeriodSeconds window, it is forcibly terminated with SIGKILL.
  • Loop update: After the old pod exits, if additional old pods remain, the cycle repeats. New pods are created until all are replaced.
Figure 1 Rolling upgrade process

Procedure

In this example, a workload with two pods is exposed externally via a LoadBalancer Service. When upgrading workloads associated with LoadBalancer Services or ingresses, cross-service calling is necessary, so it is important to carefully configure the rolling upgrade parameters.

Configuration 1: Startup Probe

A startup probe determines whether an application container has started. For slow-starting applications, configuring liveness or readiness probes directly may cause premature health check failures and repeated restarts before startup completes. The startup probe runs first. Until it succeeds, liveness and readiness probes are disabled, giving the application adequate time to start.

This example uses an HTTP port check. Adjust parameters as needed.

startupProbe:
  httpGet:
    path: /
    port: 80
  failureThreshold: 30   # Maximum 30 attempts; startup timeout: 300s (30 × 10s)
  periodSeconds: 10

(failureThreshold × periodSeconds) determines the maximum allowed startup time of an application.

In this case, 300s (30 × 10s) suits applications with long startup times. Tune these values based on actual startup duration to avoid setting them too short, which may cause repeated pod restarts.

Configuration 2: Readiness Probe

A readiness probe determines whether a pod is ready to receive traffic. If it fails, the pod is removed from Service endpoints and stops receiving new requests, but is not deleted or restarted. This ensures only truly ready pods handle traffic during rolling updates.

This example uses an HTTP port check. Adjust parameters as needed.

readinessProbe:
  httpGet:
    path: /
    port: 80
  initialDelaySeconds: 5  # The readiness probe starts 5 seconds after the container starts.
  periodSeconds: 5        # The probe runs every 5 seconds.
  timeoutSeconds: 2       # The timeout for each check
  successThreshold: 1     # If the probe succeeds once, the container is marked as ready.
  failureThreshold: 3     # If the probe fails three consecutive times, the container is marked as not ready.

The detection period, delay, and timeout interval must be set properly. If intervals are too short for slow-starting applications, the pod may receive traffic before it is ready, causing request failures.

Configuration 3: readinessGates

In LoadBalancer Services, especially when externalTrafficPolicy is set to Local, a pod being ready does not guarantee it is registered with the ELB backend. By default, Kubernetes evaluates readiness based only on the readiness probe. However, even after a pod passes this check, the ELB still requires time to complete its own health checks and backend registration. If traffic is routed to the pod during this window, connections may fail.

readinessGates allows you to define custom readiness conditions. A pod is marked as ready and added to Service endpoints only when both the readiness probe and all readiness gate conditions pass. In CCE, you can configure readinessGates to coordinate with ELB health checks, ensuring a pod receives traffic only after it is registered with the ELB.

readinessGates:
  - conditionType: target-health.elb.k8s.cce/<Service-name>
  • After readinessGates is configured, a pod is marked as Ready only when it satisfies all conditions specified by both the readiness probe and readinessGates.
  • This prevents traffic loss caused by a pod being ready but not yet registered with the ELB, which is especially critical in Local mode.
  • The conditionType format is target-health.elb.k8s.cce/<Service-name>. The prefix target-health.elb.k8s.cce is fixed, and <Service-name> must be replaced with the actual Service name.
  • readinessGates applies only after ELB health checks are enabled on the Service using the annotation kubernetes.io/elb.health-check-flag: 'on'.

Configuration 4: Rolling Update Strategy

Set the strategy to rolling update to gradually replace old pods with new ones.

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxUnavailable: "25%"  # A maximum of 25% of replicas may be unavailable during the update.
    maxSurge: "25%"        # A maximum of 25% of replicas may be created above the desired count during the update.

maxUnavailable and maxSurge control the rolling update pace. They work with the readiness probe to ensure sufficient workload capacity remains available throughout the upgrade.

Configuration 5:preStop Hook for Connection Draining

When a pod is deleted, Kubernetes sends SIGTERM to the container and executes the preStop hook. The preStop hook reserves time to drain established connections, especially persistent connections, after the pod is removed from Service endpoints, ensuring in-flight requests complete properly.

Recommended preStop hook configuration:

lifecycle:
  preStop:
    exec:
      # Configure the hook based on your service requirements to allow existing connections to finish before the application stops.
      command: ["sh", "-c", "sleep 30 && /usr/sbin/nginx -s quit"]

When Kubernetes deletes a pod, it performs two actions concurrently:

  1. Removes the pod from Service endpoints.
  2. Sends SIGTERM to the container.

However, there is a delay before kube-proxy updates iptables rules and the ELB removes backend pods. As a result, some in-flight requests or established connections may still be routed to the terminating pod. sleep 30s provides a window for processing these requests.

Persistent connections

If the application uses persistent connections such as WebSocket, the preStop hook should proactively signal the application to close them or wait for natural termination. Example:
lifecycle:
  preStop:
    exec:
      command:
        - /bin/sh
        - -c
        - |
          # Send a graceful termination signal to the application (for example, via its management API).
          curl -X POST http://localhost:8080/admin/shutdown 2>/dev/null || true
          # Wait for established connections to close.
          sleep 30

Configuration 6: TerminationGracePeriodSeconds

Set the termination grace period (terminationGracePeriodSeconds) to specify how long Kubernetes waits before forcefully terminating a pod.

terminationGracePeriodSeconds: 60

terminationGracePeriodSeconds must exceed the preStop hook execution time. Kubernetes terminates a pod in this sequence:

  1. Executes the preStop hook.
  2. Sends SIGTERM.
  3. Waits for terminationGracePeriodSeconds to expire.
  4. Sends SIGKILL to forcefully terminate the pod.

Recommended configuration: terminationGracePeriodSeconds = preStop hook time + Graceful termination time + Buffer

  • Too small: The preStop hook may be interrupted by SIGKILL before completion, causing established connections to drop and requests to fail.
  • Too large: Pod deletion slows, reducing rolling update efficiency.

In this example, the preStop hook runs for 30s and application graceful termination typically takes 10s to 20s. Therefore, set terminationGracePeriodSeconds to 60s.

Configuration 7: Node Affinity (Required in Local Mode)

This configuration is recommended when a Service's Service Affinity is set to Node-level. When defining the scheduling policy, specify the nodes for workload affinity. For details, see Configuring Node Affinity Scheduling (nodeAffinity).

Configuration Examples

This section provides two configuration examples.

Zero-Downtime Workload Example

The following is a complete YAML example that includes a Deployment and Service with all optimizations: rolling updates, health check probes, readinessGates, and graceful termination.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-demo
  # Rolling update policy ensures service continuity during updates.
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: "25%"  # A maximum of 25% of replicas may be unavailable during the update.
      maxSurge: "25%"        # A maximum of 25% of replicas may be created above the desired count during the update.
  template:
    metadata:
      labels:
        app: nginx-demo
    spec:
      # Pod readiness check via ELB integration
      # target-health.elb.k8s.cce is a fixed prefix, and the suffix must match the associated Service name.
      readinessGates:
        - conditionType: target-health.elb.k8s.cce/nginx-demo-service
      # Maximum graceful termination duration, and the pod is forcibly terminated if the duration is exceeded.
      # The value must exceed the preStop hook duration for connection draining.
      terminationGracePeriodSeconds: 60
      containers:
      - name: nginx
        image: nginx:perl
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
          limits:
            cpu: 500m
        # Startup probe ensures the application has started before other probes apply.
        # Liveness and readiness probes are disabled until the startup probe succeeds.
        startupProbe:
          httpGet:
            path: /
            port: 80
          failureThreshold: 30   # Maximum 30 attempts; startup timeout: 300s
          periodSeconds: 10
        # Readiness probe determines whether the container is ready to receive traffic.
        # Unready pods are removed from Service endpoints and will not be assigned requests.
        readinessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 5  # The readiness probe starts 5 seconds after the container starts.
          periodSeconds: 5        # The probe runs every 5 seconds.
          timeoutSeconds: 2       # The timeout for each check
          successThreshold: 1     # If the probe succeeds once, the container is marked as ready.
          failureThreshold: 3     # If the probe fails three consecutive times, the pod is marked as not ready.
        # Graceful termination settings
        lifecycle:
          preStop:
            exec:
              # Configure the hook based on your service requirements to allow existing connections to finish before the application stops.
              command: ["sh", "-c", "sleep 30 && /usr/sbin/nginx -s quit"]
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-demo-service
  labels:
    app: nginx-demo
  namespace: default
  annotations:
    kubernetes.io/elb.class: performance  # A dedicated load balancer is used.
    kubernetes.io/elb.id: xxxxxxxxxx  # Replace it with the actual load balancer ID.
    kubernetes.io/elb.health-check-flag: 'on'
    kubernetes.io/elb.health-check-option: '{"protocol":"TCP","delay":"5","timeout":"10","max_retries":"3"}'
spec:
  selector:
    app: nginx-demo
  externalTrafficPolicy: Cluster
  ports:
    - name: cce-service-0
      targetPort: 80
      nodePort: 0
      port: 8080
      protocol: TCP
  type: LoadBalancer
  • In readinessGates, the conditionType format is target-health.elb.k8s.cce/<Service-name>. Replace <Service-name> with the actual name of the associated Service. Enable ELB health checks by setting the annotation kubernetes.io/elb.health-check-flag: 'on'.
  • In the preStop hook, sleep 30 waits for ELB backend removal and iptables rule updates. nginx -s quit gracefully stops Nginx and drains established connections. Replace these commands with those appropriate for your application.
  • terminationGracePeriodSeconds must exceed the preStop hook execution time (sleep 30s + nginx quit in this example). Include a 30-second buffer and set this parameter to 60.

Example of a Workload Without Zero-Downtime Configuration

The following Deployment and Service omit all zero-downtime optimizations. Only basic configurations are included for comparison in subsequent load testing.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-demo2
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-demo2
  template:
    metadata:
      labels:
        app: nginx-demo2
    spec:
      containers:
      - name: nginx
        image: nginx:perl
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
          limits:
            cpu: 500m
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-demo2-service
  labels:
    app: nginx-demo2
  namespace: default
  annotations:
    kubernetes.io/elb.class: performance  # A dedicated load balancer is used.
    kubernetes.io/elb.id: xxxxxxxxxx  # Replace it with the actual load balancer ID.
    kubernetes.io/elb.health-check-flag: 'on'
    kubernetes.io/elb.health-check-option: '{"protocol":"TCP","delay":"5","timeout":"10","max_retries":"3"}'
spec:
  selector:
    app: nginx-demo2
  externalTrafficPolicy: Cluster
  ports:
    - name: cce-service-0
      targetPort: 80
      nodePort: 0
      port: 8082
      protocol: TCP
  type: LoadBalancer

Verifying Zero-Downtime Updates

After completing the above configurations, use a load testing tool to send requests continuously during rolling updates. Test both the optimized and unoptimized workloads to verify the zero-downtime configuration.

Preparations

Load Test for the Optimized Workload

  1. Obtain the Service access address for the optimized workload.

    export NGINX_ENDPOINT=$(kubectl get service nginx-demo-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}{":"}{.spec.ports[0].port}')
    echo $NGINX_ENDPOINT

  2. Perform a load test using hey with 200 concurrent connections and 100,000 total requests.

    hey -c 200 -n 100000 -disable-keepalive http://$NGINX_ENDPOINT

  3. During the test, open a new terminal and trigger a rolling update.

    kubectl rollout restart deployment nginx-demo

  4. Monitor the rolling update status.

    kubectl rollout status deployment nginx-demo

  5. After the test completes, review the hey output.

    Expected result: No traffic interruption.

Load Test for the Unoptimized Workload

  1. Obtain the Service access address for the unoptimized workload.

    export NGINX_ENDPOINT2=$(kubectl get service nginx-demo2-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}{":"}{.spec.ports[0].port}')
    echo $NGINX_ENDPOINT2

  2. Perform a load test using hey with 200 concurrent connections and 100,000 total requests.

    hey -c 200 -n 100000 -disable-keepalive http://$NGINX_ENDPOINT2

  3. During the test, open a new terminal and trigger a rolling update.

    kubectl rollout restart deployment nginx-demo2 

  4. Monitor the rolling update status.

    kubectl rollout status deployment nginx-demo2 

  5. After the test completes, review the hey output.

    Expected result: Traffic interruption occurs.