Create a StatefulSet

更新时间:
复制 MD 格式

Container Service for Kubernetes (ACK) clusters let you create StatefulSets from the console. This example deploys a stateful NGINX application to demonstrate StatefulSet features.

Prerequisites

kubectl is connected to your Kubernetes cluster. Obtain the kubeconfig for a cluster and use kubectl to connect to the cluster.

StatefulSet features

A StatefulSet provides the following features:

Feature

Description

Consistent Pod identity

Provides ordering guarantees (such as startup and shutdown order) and a consistent network identity that stays with the Pod regardless of scheduling.

Stable persistent storage

Creates a PV for each Pod using a VolumeClaimTemplate. Scaling down or deleting replicas does not delete the associated volumes.

Stable network identity

The Pod's hostname follows the pattern: (StatefulSet name)-(ordinal index).

Stable ordering

For a StatefulSet with N replicas, the StatefulSet assigns each Pod a unique ordinal index in the range [0, N).

Steps

Step 1: Configure basic application information

  1. Log on to the ACS console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the name of the target cluster. In the left navigation pane, choose Workloads > StatefulSets.

  3. On the StatefulSets page, click Create from Image.

  4. On the Basic Information page, configure the application.

    Parameter

    Description

    Application Name

    Enter the application name.

    Replicas:

    Number of pods for the application. Default: 2.

    Workloads

    Select StatefulSets.

    Labels

    Label to identify the application.

    Annotations

    Annotation for the application.

    Instance type

    Select a compute type. For details about compute types, see Overview of ACS pod instances.

    QoS Type

    Select a Quality of Service (QoS) class.

    Correspondence Between Computing Type and Computing Power Quality

    Compute class

    Supported QoS class

    general-purpose (general-purpose)

    default (default), best-effort (best-effort)

    performance (performance)

    default (default), best-effort (best-effort)

    GPU-accelerated (gpu)

    default (default), best-effort (best-effort)

    GPU-HPN (gpu-hpn)

    default (default)

    For more information, see QoS class definitions.

  5. Click Next to open the Container page.

Step 2: Configure containers

On the Container wizard page, configure the container image, resources, ports, environment variables, health checks, lifecycle, volumes, and logging.

Note

To add multiple containers to the pod, click Add Container next to the Container 1 tab.

  1. In the General section, complete the basic container configuration.

    configuration item

    Description

    Image Name

    • Select an image

      Click Select Image to choose the required image.

      • Container Registry Enterprise Edition: Select an Enterprise Edition image hosted in Alibaba Cloud Container Registry (ACR). You must select the region and ACR instance where the image resides. For more information about ACR, see What is Container Registry?.

      • Container Registry Personal Edition (must be activated first): Select a Personal Edition image hosted in ACR. You must select the region and ACR instance where the image resides.

      • Artifact center: Includes base OS images for containerized applications, language runtime images, and AI/big data-related images. This example uses an Nginx image from Artifact Center. For more information, see Artifact Center.

    • (Optional) Set the image pull policy

      From the Image Pull Policy drop-down list, select a pull policy. By default, no policy is set, and Kubernetes uses IfNotPresent.

      • IfNotPresent: If the image already exists locally (previously pulled to the host), it will not be pulled again. Otherwise, the image will be pulled.

      • Always: Always pull the image during deployment or scale-out, ignoring any local copy.

      • Never: Use only the local image.

    • (Optional) Set an image pull secret

      Click Set Image Pull Secret to securely access private images.

      • For ACR Personal Edition instances, you can pull container images by setting an image pull secret. For more information, see Manage secrets.

      • For ACR Enterprise Edition instances, you can pull images without passwords using the passwordless component. For details, see Pull ACR images without passwords.

    Required Resources

    Set resource quotas for the container.

    • CPU: Specify CPU request and limit values. By default, the request equals the limit, and billing uses the pay-as-you-go method. If you set a different limit via YAML, the request will be overwritten to match the limit. For details, see Resource specifications.

    • Memory: Specify memory request and limit values. By default, the request equals the limit, and billing uses the pay-as-you-go method. If you set a different limit via YAML, the request will be overwritten to match the limit. For details, see Resource specifications.

    Interactive Session

    (Optional) Configure container startup options.

    • stdin: Send console input to the container.

    • tty: Attach the standard input console as the container's console input.

    Note

    Typically, both stdin and tty are selected together to bind the terminal (tty) to the container's standard input (stdin). For example, an interactive program reads user input from stdin and displays output on the terminal.

    Init Containers

    (Optional) Select this option to create an init container.

    Init containers provide a mechanism to block or delay the startup of application containers until they succeed. After successful execution, application containers in the pod start in parallel. For example, you can use init containers to check the availability of dependent services. Init containers can include utilities or installation scripts not present in the application image to initialize the runtime environment—for example, setting kernel parameters or generating configuration files. For more information, see Init Containers.

  2. (Optional) In the Ports section, click Add to configure container ports.

    configuration item

    Description

    Name

    Specify a name for the container port.

    Container Port

    Specify the exposed container access port. The port number must be between 1 and 65535.

    Protocol

    Supported protocols are TCP and UDP.

  3. (Optional) In the Environments section, click Add to configure environment variables.

    You can configure environment variables for the pod using key-value pairs to add environment flags or pass configuration. For more information, see Pod Environment Variables.

    Parameter

    Description

    Type

    Set the environment variable type:

    • Custom

    • ConfigMaps

    • Secrets

    • Value/ValueFrom

    • ResourceFieldRef

    ConfigMap and Secret support referencing entire files.

    This example uses a Secret. When you select the Secrets type and choose a target Secret, all files in that Secret are referenced by default. After selecting Secret, enter a Variable Name and select the corresponding Secret name and key from the two drop-down lists on the right.

    The corresponding YAML references the entire Secret:

    envFrom:
      - secretRef:
          name: test

    Variable Key

    Set the environment variable name.

    Value/ValueFrom

    Set the referenced variable value.

  4. (Optional) In the Health Check section, enable Liveness, Readiness, and Startup as needed.

    • Liveness probe: A liveness probe checks if a container is running. If the probe fails multiple times, the kubelet restarts the container. This can help resolve issues like deadlocks where the container is running but unable to make progress.

    • Readiness probe: A readiness probe checks if a container is ready to accept traffic. A Pod is added as a backend to a Service only after its readiness probe succeeds.

    • Startup Probes: These probes are executed only when a container starts to check if it has started successfully. The Liveness Probes and Readiness Probes are executed only after the startup probe succeeds.

    For more information, see Configure liveness, readiness, and startup probes.

    Parameter

    Description

    HTTP

    Sends an HTTP GET request to the container. Supported parameters include the following:

    • Protocol: HTTP or HTTPS.

    • Path: The path to access the HTTP server.

    • Port: The exposed container port or port name. The port number must be between 1 and 65535.

    • HTTP Header: Custom request headers in the HTTP request. HTTP allows duplicate headers. Configure them as key-value pairs.

    • Initial Delay (s): The initialDelaySeconds parameter specifies how many seconds to wait after the container starts before performing the first probe. Default is 3 seconds.

    • Period (s): The periodSeconds parameter specifies the time interval between probes. Default is 10 seconds. Minimum is 1 second.

    • Timeout (s): The timeoutSeconds parameter specifies the probe timeout duration. Default is 1 second. Minimum is 1 second.

    • Healthy Threshold: The minimum number of consecutive successful probes required after a failure to mark the container as healthy. Default is 1. Minimum is 1. For liveness probes, this must be 1.

    • Unhealthy Threshold: The minimum number of consecutive failed probes required after success to mark the container as unhealthy. Default is 3. Minimum is 1.

    TCP

    Opens a TCP socket to the container. Kubelet attempts to open a socket on the specified port. If successful, the container is considered healthy; otherwise, it is marked as failed. Supported parameters include the following:

    • Port: The exposed container port or port name. The port number must be between 1 and 65535.

    • Initial Delay (s): The initialDelaySeconds parameter specifies how many seconds to wait after the container starts before performing the first probe. Default is 15 seconds.

    • Period (s): The periodSeconds parameter specifies the time interval between probes. Default is 10 seconds. Minimum is 1 second.

    • Timeout (s): The timeoutSeconds parameter specifies the probe timeout duration. Default is 1 second. Minimum is 1 second.

    • Healthy Threshold: The minimum number of consecutive successful probes required after a failure to mark the container as healthy. Default is 1. Minimum is 1. For liveness probes, this must be 1.

    • Unhealthy Threshold: The minimum number of consecutive failed probes required after success to mark the container as unhealthy. Default is 3. Minimum is 1.

    Command

    Runs a command inside the container to check its health. Supported parameters include the following:

    • Command: The command used to check container health.

    • Initial Delay (s): The initialDelaySeconds parameter specifies how many seconds to wait after the container starts before performing the first probe. Default is 5 seconds.

    • Period (s): The periodSeconds parameter specifies the time interval between probes. Default is 10 seconds. Minimum is 1 second.

    • Timeout (s): The timeoutSeconds parameter specifies the probe timeout duration. Default is 1 second. Minimum is 1 second.

    • Healthy Threshold: The minimum number of consecutive successful probes required after a failure to mark the container as healthy. Default is 1. Minimum is 1. For liveness probes, this must be 1.

    • Unhealthy Threshold: The minimum number of consecutive failed probes required after success to mark the container as unhealthy. Default is 3. Minimum is 1.

  5. (Optional) In the Lifecycle section, configure the container lifecycle.

    You can configure pre-start commands, post-start handlers, and pre-stop handlers for the container lifecycle. For details, see Configure lifecycle.

    Parameter

    Description

    Start

    Specify a command and its arguments to run before the container starts.

    Post-start Hook

    Specify a command to run after the container starts.

    Pre-stop Hook

    Specify a command to run before the container terminates.

  6. (Optional) In the Volume section, mount volumes to the container.

    • Local storage: Mount ConfigMaps, Secrets, or temporary directories to container paths. For more information, see volumes.

    • Cloud storage: Supports cloud disks, NAS, and more. For details, see Storage overview.

  7. (Optional) In the Log section, configure Collection Configuration and Custom Tag.

    Parameter

    Description

    Collection Settings

    • Logstore: Creates a corresponding Logstore in Simple Log Service to store collected logs.

    • Log Path in Container (Can be set to stdout): Supports stdout and text logs.

      • Stdout: Collects standard output logs from the container.

      • Text logs: Collects logs from a specified path inside the container. This example collects all text logs under /var/log/nginx and supports wildcard characters.

    Custom Tags

    You can also set custom tags. When configured, these tags are included with the container logs. Custom tags help you categorize logs for easier statistics and filtering during analysis.

  8. Click Next to go to the Advanced wizard.

Step 3: Complete advanced configuration

On the Advanced wizard page, configure access, scaling, scheduling, and labels/annotations.

  1. In the Access Control section, configure how to expose backend pods.

    This example uses ClusterIP and Ingress to create a publicly accessible Nginx application.

    • Configure a Service: Click Create next to Services to set up service parameters.

      Expand to view service configuration details

      configuration item

      Description

      Name

      Enter a service name. This example uses nginx-svc.

      Type

      Select the service type, which determines how the service is accessed. This example selects Cluster IP.

      • Cluster IP: Exposes the service on an internal IP within the cluster. Services of this type are only accessible from within the cluster. This is the default ServiceType.

        Note

        When the service type is Cluster IP, you can configure a Headless Service.

      • Server Load Balancer: Uses Alibaba Cloud Server Load Balancer (SLB) to expose the service. You can choose public or internal-facing access. Alibaba Cloud SLB routes traffic to ClusterIP services.

        • Create new SLB: Click Modify to change SLB specifications.

        • Use existing SLB: Select an SLB instance from the list.

        Note

        The LoadBalancer type supports creating a new SLB or reusing an existing one, but with the following limitations:

        • Using an existing SLB instance overwrites its current listeners.

        • SLB instances created by Kubernetes through Services cannot be reused (to prevent accidental deletion). Only SLB instances manually created in the console (or via OpenAPI) can be reused.

        • Multiple Services reusing the same SLB must not share the same frontend listener port to avoid conflicts.

        • When reusing an SLB, Kubernetes uses listener names and vServer group names as unique identifiers. Do not modify these names.

        • Reusing SLB across clusters is not supported.

      Port Mapping

      Add service and container ports. The container port must match the port exposed by backend pods.

      External Traffic Policy

      • Local: Routes traffic only to pods on the same node.

      • Cluster: Routes traffic to pods on any node.

      Note

      You can set the External Traffic Policy only when the service type is Server Load Balancer.

      Annotations

      Add an annotation to configure SLB parameters. For example, setting service.beta.kubernetes.io/alicloud-loadbalancer-bandwidth: 20 limits the service bandwidth to 20 Mbit/s to control traffic.

      Label

      Add a label to identify this service.

    • Configure Ingress: Click Create next to Ingresses to set routing rules for backend pods.

      Expand to view Ingress configuration details

      Note

      When creating an application from an image, you can create only one Ingress per service. This example uses a virtual hostname as a test domain. Add a domain mapping (Ingress endpoint + Ingress domain) to your Hosts file. In production, use an ICP filed domain.

      101.37.XX.XX   foo.bar.com    # Ingress IP.

      Parameter

      Description

      Name

      Enter an Ingress name. This example uses alb-ingress.

      Rule

      Ingress rules define how inbound traffic reaches cluster services. For more information, see ALB Ingress Quick Start.

      • Domain Name: Enter the Ingress domain.

      • Path: Specify the URL path for service access. The default is the root path /. Each path maps to a backend service. Alibaba Cloud SLB forwards traffic only if inbound requests match both the domain and the path.

      • Services: Select the service name and port.

      • TLS: Configure secure routing.

      This example uses the test domain foo.bar.com and sets the service to nginx-svc.

      Canary Release

      Enable canary release. We recommend selecting Open Source Solution because the Alibaba Cloud edition is no longer maintained.

      Ingress Class

      Specify a custom Ingress class.

      Annotations

      Define custom annotation keys and values, or search for annotations by name. Click Add to enter annotation key-value pairs. For Ingress annotations, see Annotations.

      Label

      Click Add to enter label keys and values that identify characteristics of this Ingress.

  2. (Optional) In the Scaling section, enable HPA to meet varying load demands.

    • Container Compute Service supports autoscaling based on pod CPU and memory usage.

      Note

      To enable autoscaling, you must specify requested resources for the container. Otherwise, autoscaling will not work.

      configuration item

      Description

      Metric

      Supports CPU and memory. Must match the requested resource type.

      Trigger Condition

      The threshold for resource usage percentage. When exceeded, the system scales out.

      Max. Replicas

      The maximum number of containers that can be scaled out for this payload type.

      Min. Replicas

      The lower limit for scaling in this workload.

    • Container Compute Service also supports scheduled scaling (CronHPA) to automatically scale Kubernetes clusters at specific times. Before enabling scheduled scaling, install the ack-kubernetes-cronhpa-controller component. For details, see Scheduled scaling (CronHPA).

  1. (Optional) In the Labels,Annotations section, click Add to set pod labels and annotations.

  2. Click Create.

Step 4: View the application

After creation, a confirmation page is displayed. Click View Details to open the details page for the StatefulSet.

Alternatively, on the Deployments page, click the StatefulSet name or click Details in the Actions column.