Updated on 2026-09-15 GMT+08:00

Creating a StatefulSet

A StatefulSet is an application that needs to retain data or state while running. StatefulSets are ideal for stateful applications, such as databases, cache services, and message queues. Unlike Deployments, StatefulSets have the following features:

  • Fixed identifier: Each pod in a StatefulSet has a fixed identifier, which is associated with the pod name. The identifier is typically in the format of <StatefulSet name>-<Ordinal>. For example, in a StatefulSet named web, the pods would have the names like web-0 and web-1. This naming rule enables each pod to maintain its identity and persistent data even after restart or migration.
  • Ordered deployment and scaling: Pods in a StatefulSet are created, scaled, or deleted sequentially. For example, pods with higher ordinals are prioritized for scale-out and removed first during scale-in, which is critical to stateful applications that need to be started or stopped in sequence and ideal for scenarios like primary-secondary replication of databases.
  • Persistent storage: To ensure data persistence, you can assign stable PVs to each StatefulSet pod by using VolumeClaimTemplate. If a pod is scheduled to other nodes, its original data volume remains intact through the PVC, preventing data loss.

Constraints

  • When you delete or scale a StatefulSet, the system does not delete the storage volumes associated with the StatefulSet to ensure data security.
  • When you delete a StatefulSet, reduce the number of replicas to 0 before deleting the StatefulSet so that pods in the StatefulSet can be stopped in order.
  • When you create a StatefulSet, a headless Service is required for pod access. For details, see Headless Service.

Prerequisites

  • You already have an available cluster before you create a workload. For details about how to create a cluster, see Buying a CCE Autopilot Cluster.
  • You have configured the VPC endpoints for accessing the image center and OBS. When you create a cluster, the system automatically creates VPC endpoints. You can go to the Overview page of the cluster and check whether VPC endpoints have been configured for Image Access in the Networking Configuration area. If no VPC endpoints are configured for the cluster, configure them by following the instructions in Configuring VPC Endpoints for Accessing the Image Center.

Creating a StatefulSet

You can create a StatefulSet using the console or kubectl.

  1. Log in to the CCE console.
  2. Click the cluster name to go to the cluster console, choose Workloads in the navigation pane, and then click Create Workload in the upper right corner.
  3. Configure the basic information about the workload.

    Table 1 Basic information about the workload

    Parameter

    Description

    Workload Type

    Select StatefulSet. For details about different workload types, see Workload Overview.

    Workload Name

    Enter a name for the workload. Enter 1 to 63 characters starting with a lowercase letter and ending with a lowercase letter or digit. Only lowercase letters, digits, and hyphens (-) are allowed.

    Namespace

    Select a namespace for the workload. The default value is default. You can also click Create Namespace to create one. For details, see Creating a Namespace.

    Instance Type

    Select the pod type for the workload. The default value is General-computing. For details about pod types, see Specifying the Pod Type.

    Pods

    Enter the number of workload pods.

  4. Configure the container settings for the workload.

    • Image Cache This parameter is optional. If you have created image caches, you can choose to automatically allocate or specify an image cache. For details about the parameters, see Table 2. Image caches accelerate image download and workload startup. For details, see Image Cache Overview. Image caches are supported when the cluster version is v1.28.8, v1.31.4, or later.

      Image caches are supported in some regions. View the regions where image caches are supported on the console.

      Table 2 Image cache parameters

      Option

      Example Value

      Description

      Do not use

      -

      No image cache will be used. The images will be downloaded based on the configuration in Container Settings.

      Auto allocate

      -

      The optimal images will be selected from all available image caches based on:
      • How much the images match the image caches: The images in the most matched image caches will be used.
      • Time when the image caches were created: The images in the latest image cache will be used.

      If no images are matched, no image caches will be used.

      Specify

      autopilot-test

      Select an existing image cache. The image cache must be in the Available state. To create an image cache, click Create Image Cache. For details about the parameters, see Creating an Image Cache.

    • Container Information: Click Add Container on the right to configure multiple containers for the pod.
      • Basic Info: Configure basic information about each container.
        Table 3 Basic container information

        Parameter

        Description

        Container Name

        Enter a name for the container.

        Pull Policy

        Image update or pull policy. If you select Always, the image is pulled from the image repository each time. If you do not select Always, an existing local image is preferentially used. If there is no existing image, an image will be pulled from the image repository.

        If an image cache is used, you are advised not to select Always to avoid repeatedly pulling images from the original image repository.

        Image Name

        Click Select Image and select the image used by the container. To use a third-party image, see Using Third-Party Images.

        If you choose to use an image cache, you need to enter the following information:

        • If you select Auto allocate, you can configure Image Name (Container Information > Basic Info > Image Name). The images are matched based on the matching rules in Table 2. If no images are matched in the image cache, the image cache is no longer used. In this case, the images in the SWR image repository and open-source images are matched in sequence based on the specified image name. If no images are matched, a message is returned indicating that images fail to be pulled.
        • If you select Specify, you need to enter the address of the image to be used in the image cache (Container Information > Basic Info > Image Name).

          To obtain the image path, move the cursor to the specified image cache and view Image in the displayed tip.

        Image Tag

        Select the image tag to be deployed.

        CPU Quota

        CPU limit, which is the maximum CPU available for the container to prevent excessive resource usage.

        Memory Quota

        Memory limit, which is the maximum memory available for the container. When the container's memory usage exceeds the memory limit, the container will be terminated.

        Init Container

        Whether the container will be used as an init container. This parameter is optional. An init container does not support health check.

        An init container is a special container that runs before other app containers in a pod are started. Each pod can contain multiple containers. In addition, a pod can contain one or more init containers. Application containers in a pod are started and run only after the running of all init containers completes. For details, see Init Containers.

        Run Option

        Add run options for the container. This parameter is optional. For details, see Pod. CCE Autopilot supports the following run options:

        • stdin: allows containers to receive input from external sources, such as terminals or other input streams.
        • tty: allocates a pseudo terminal to containers, allowing you to send commands to them as if you were using a local terminal.

          In most cases, tty is enabled along with stdin, indicating that the terminal (tty) is associated with the standard input (stdin) of the container. This allows for interactive operations, similar to the kubectl exec -i -t command. The difference is that this parameter has been configured when the pod is launched.

      • Lifecycle: This parameter is optional. Configure operations to be performed in a specific phase of the container lifecycle, such as startup command, PostStart, and PreStop. For details, see Configuring the Container Lifecycle.
      • Health Check: This parameter is optional. Set the liveness probe, ready probe, and startup probe as needed. For details, see Configuring Health Checks for Containers.
      • Environment Variables: This parameter is optional. Configure variables for the container running environment using key-value pairs. These variables transfer external information to containers running in pods and can be flexibly modified after application deployment. For details, see Configuring Environment Variables.
      • Data Storage: This parameter is optional. Mount local storage or cloud storage to the container. The application scenarios and the ways for mounting the volumes vary with the storage type.
        • StatefulSets allow you to mount storage volumes dynamically.

          Dynamic mounting is achieved by using the volumeClaimTemplates field and depends on the dynamic creation capability of StorageClass. A StatefulSet associates each pod with a PVC using the volumeClaimTemplates field, and the PVC is bound to the corresponding PV. Therefore, after the pod is rescheduled, the original data can still be mounted based on the PVC name.

        • After a workload is created, the storage that is dynamically mounted cannot be updated.
      • Security Context: This parameter is optional. Assign container permissions to protect the system and other containers from being affected. Enter the user ID to assign container permissions and prevent the system and other containers from being affected.
    • Image Access Credential: Select the credential used for accessing the image repository. The default value is default-secret. You can use default-secret to access images in SWR. For details about default-secret, see default-secret.

  5. Configure the headless Service settings for the workload.

    A headless Service is used to solve the problem of mutual access between pods in a StatefulSet. The headless Service provides a fixed access domain name for each pod. For details, see Headless Service.

  6. (Optional) Configure the Service settings for the workload.

    A Service provides external access for pods. With a static IP address, a Service forwards the traffic to pods and automatically balances load for these pods.

    You can also create a Service after creating a workload. For details about Services of different types, see Services.

  7. (Optional) Configure advanced settings for the workload.

    Table 4 Advanced settings for the workload

    Parameter

    Description

    Upgrade

    Specify the upgrade mode and parameters of the workload. Rolling upgrade and Replace upgrade are supported. For details, see Upgrading and Rolling Back a Workload.

    Pod Management Policies

    For some distributed systems, the StatefulSet ordering guarantees are unnecessary and/or undesirable. These systems require only uniqueness and identifiers.

    • OrderedReady: The StatefulSet will deploy, delete, or scale pods in order and one by one. (The StatefulSet continues only after the previous pod is ready or deleted.) This is the default policy.
    • Parallel: The StatefulSet will create pods in parallel to match the desired scale without waiting, and will delete all pods at once.

    Labels and Annotations

    Add labels or annotations for pods using key-value pairs. After you add a label or annotation, click Add. For details about how to use and configure labels and annotations, see Configuring Labels and Annotations.

    DNS

    Configure a DNS policy for the workload. For details, see DNS Configuration.

    APM Settings

    Use APM to provide more accurate problem analysis and locating for Java programs. For details, see Specifying APM Settings.

    Network Configuration

    • Decide whether to enable fixed IP addresses: If this option is selected, the IP address of each pod does not change after the pod restarts. You can also set the interval for reclaiming pod IP addresses. For details, see Configuring a Static IP Address for a Pod.
    • Decide whether to enable the network configuration of a specified container: You can enable the specified container network configuration. The workload is created using the container subnet and security group in the specified container network configuration. For details, see Associating a Subnet and Security Group with a Namespace or Workload Using a Container Network Configuration.
    • Specify the container network configuration name: Only the custom container network configuration whose associated resource type is workload can be selected.

  8. In the Confirm step, confirm the following information:

    1. Confirm the pod resource specification calculation rules.
      • Default configuration: The resource specifications of a pod are based on the CPU and memory quotas needed by all init and regular containers.
      • Custom configuration: If you have configured pod-level resource quotas, the configuration is used as the final pod resource specifications (the priority of the pod-level configuration is higher than that of the container-level configuration).
    2. Ensure that the ephemeral storage of a single pod meets the container requirements. For details, see Increasing the Ephemeral Storage Space of a Pod.
    3. Confirm the billing specifications.
      • The actual billing specifications of a single pod are automatically rounded up to the nearest pod specifications supported by CCE Autopilot. For details about the specifications, see CCE Autopilot Specification Description.
      • If the requested pod resources are lower than the billed amount, you are advised to use the one-click upgrade function to upgrade the specifications and prevent resource waste.
    4. Confirm the information and select I have read and agree to the pricing policy.

  9. In the lower right corner, click Create Workload. After a period of time, the workload enters the Running state.

Node affinity and anti-affinity are not available for CCE Autopilot clusters. When you use kubectl to create a workload, do not configure the affinity field to prevent pod creation failures.

  1. Use kubectl to access the cluster. For details, see Accessing a Cluster Using kubectl.
  2. Create and edit the nginx-statefulset.yaml file.

    nginx-statefulset.yaml is an example file name. You can change it as needed.

    vi nginx-statefulset.yaml

    The following provides an example of the file contents. For more information on StatefulSet, see the Kubernetes documentation.

    apiVersion: apps/v1
    kind: StatefulSet
    metadata:
      name: nginx
    spec:
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
            - name: container-1
              image: nginx:latest
              imagePullPolicy: IfNotPresent
              resources:
                requests:
                  cpu: 250m
                  memory: 512Mi
                limits:
                  cpu: 250m
                  memory: 512Mi
          imagePullSecrets:
            - name: default-secret
          dnsPolicy: ClusterFirst
      serviceName: nginx-svc
      replicas: 2
      updateStrategy:
        type: RollingUpdate

    vi nginx-headless.yaml

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx-svc
      namespace: default
      labels:
        app: nginx
    spec:
      selector:
        app: nginx
        version: v1
      clusterIP: None
      ports:
        - name: nginx
          targetPort: 80
          nodePort: 0
          port: 80
          protocol: TCP
      type: ClusterIP

  3. Create a workload and the corresponding headless service.

    kubectl create -f nginx-statefulset.yaml

    If information similar to the following is displayed, the StatefulSet has been successfully created:

    statefulset.apps/nginx created

    kubectl create -f nginx-headless.yaml

    If information similar to the following is displayed, the headless service has been successfully created:

    service/nginx-svc created

  4. If the workload will be accessed (either within the cluster or from the external network), set the corresponding workload access type. For details, see Services.

Helpful Links