All Products
Search
Document Center

Container Service for Kubernetes:Create a stateless application by using a Deployment

Last Updated:Jul 22, 2024

Deployments do not save any data or state, such as NGINX applications. A stateless application can be created by using an image, an orchestration template, or kubectl commands. When you create an application from a private image, you can set a Secret for the private image in the Container Service for Kubernetes (ACK) console to ensure image security. This topic uses an NGINX application as an example to describe how to create a stateless application by using an image, an orchestration template, and kubectl commands.

Prerequisites

Create a Deployment from an image

Step 1: Configure basic settings

  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. In the upper-right corner of the Deployments page, click Create from Image.

  4. On the Basic Information wizard page, configure the basic settings of the application.

    Before you configure a Deployment, you need to select the namespace to which the Deployment belongs in the top navigation bar of the page. In this example, the default namespace is selected and a Deployment is created in the namespace.

    Parameter

    Description

    Name

    The name of the application.

    Replicas

    The number of pods that you want to provision for the application. Default value: 2.

    Type

    The type of the resource object that you want to create. Valid values: Deployment, StatefulSet, Job, CronJob, and DaemonSet.

    Label

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

    Annotations

    The annotations to be added to the application.

    Synchronize Timezone

    Specifies whether to synchronize the time zone between nodes and containers.

  5. Click Next to go to the Container wizard page.

Step 2: Configure containers

On the Container wizard page, configure images, resources, ports, environment variables, health check, lifecycle, volumes, and logs for containers.

Note

To add containers, click Add Container to the right of Container1.

  1. In the General section, configure the basic settings of containers.

    Parameter

    Description

    Image Name

    • Select images

      You can click Select images to select an image. The following types of images are supported:

      • Container Registry Enterprise Edition: Select an image stored in a Container Registry Enterprise Edition instance. You must select the region and the Container Registry instance to which the image belongs. For more information about Container Registry, see What is Container Registry?

      • Container Registry Personal Edition: Select an image stored in a Container Registry Personal Edition instance. You must select the region and the Container Registry instance to which the image belongs.

      • Artifact Center: The artifact center contains base operating system images, base language images, and AI- and big data-related images for application containerization. In this example, an NGINX image is selected. For more information, see Overview of the artifact center.

        Note

        The artifact center of Container Registry provides base images that are updated and patched by Alibaba Cloud or OpenAnolis. If you have other requirements or questions, join the DingTalk group (ID 33605007047) to request technical support.

      You can also enter the address of an image that is stored in a private registry. The image address must be specified in the following format: domainname/namespace/imagename:tag.

    • Image Pull Policy

      The policy for pulling images. Valid values:

      • IfNotPresent: If the image that you want to pull is found on your on-premises machine, the image on your on-premises machine is used. Otherwise, ACK pulls the image from the image registry.

      • Always: ACK pulls the image from Container Registry each time the application is deployed or expanded.

      • Never: ACK uses only images on your on-premises machine.

      Note

      If you select Image Pull Policy, no image pulling policy is applied by default.

    • Set Image Pull Secret

      You can click Set Image Pull Secret to set a Secret for pulling images from a private registry.

    Resource Limit

    The maximum amount of CPU, memory, and ephemeral storage resources that the application can use. The resource limits prevent the application from occupying an excessive amount of resources. For more information about how to configure resource limits, see Resource profiling.

    Required Resources

    The amount of CPU, memory, and ephemeral storage resources that are reserved for the application. These resources are dedicated to the pods of the application and cannot be preempted by other applications. For more information about how to reserve resources, see Resource profiling.

    Container Start Parameter

    • stdin: specifies that start parameters are sent to the container as standard input (stdin).

    • tty: specifies that start parameters defined in a virtual terminal are sent to the container.

    The two options are usually used together. In this case, the virtual terminal (tty) is associated with the stdin of the container. For example, an interactive program receives the stdin from the user and displays the content in the terminal.

    Privileged Container

    • If you select Privileged Container, privileged=true is set for the container and the privilege mode is enabled.

    • If you do not select Privileged Container, privileged=false is set for the container and the privilege mode is disabled.

    Init Containers

    Select this option to create an init container.

    Init containers can be used to block or postpone the startup of application containers. Application containers in a pod concurrently start only after init containers start. For example, you can use init containers to verify the availability of a service on which the application depends. You can run tools or scripts that are not provided by an application image in init containers to initialize the runtime environment for application containers. For example, you can run tools or scripts to configure kernel parameters or generate configuration files. For more information, see Init containers.

  2. Optional: In the Ports section, click Add to add container ports.

    Parameter

    Description

    Name

    The name of the container port.

    Container Port

    The number or name of the container port that you want to expose. Valid values of the port number: 1 to 65535.

    Protocol

    Valid values: TCP and UDP.

  3. Optional: In the Environments section, click Add to add environment variables.

    You can configure environment variables in key-value pairs. Environment variables are used to apply pod configurations to containers. For more information, see Pod variables.

    Parameter

    Description

    Type

    The type of the environment variable that you want to add. Valid values:

    • Custom

    • ConfigMaps

    • Secrets

    • Value/ValueFrom

    • ResourceFieldRef

    If you select ConfigMaps or Secrets, you can pass all data in the selected ConfigMap or Secret to the container environment variables. In this example, Secrets is selected. Select Secrets from the Type drop-down list and select a Secret from the Value/ValueFrom drop-down list. By default, all data in the selected Secret is passed to the environment variable.环境变量

    In this case, the YAML file that is used to deploy the application contains the settings that reference all data in the selected Secret.yaml

    If you select ResourceFieldRef, the resourceFieldRef parameter is specified to reference the resource values from the pod specifications and then pass the resource values to the container as environment variables. The following YAML file provides an example:

    image

    Variable Key

    The name of the environment variable.

    Value/ValueFrom

    The value of the environment variable.

  4. Optional: In the Health Check section, enable Liveness, Readiness, and Startup on demand.

    For more information, see Configure Liveness, Readiness and Startup Probes.

    Parameter

    Request type

    Description

    • Liveness: Liveness probes are used to determine when to restart a container.

    • Readiness: Readiness probes are used to determine whether a container is ready to receive traffic.

    • Startup: Startup probes are used to determine when to start a container.

      Note

      Startup probes are supported only in Kubernetes 1.18 and later.

    HTTP

    Sends an HTTP GET request to the container. You can configure the following parameters:

    • Protocol: the protocol over which the request is sent. Valid values: HTTP and HTTPS.

    • Path: the requested HTTP path on the server.

    • Port: the number or name of the container port that you want to expose. Valid values of the port number: 1 to 65535.

    • HTTP Header: the custom headers in the HTTP request. Duplicate headers are allowed. You can specify HTTP headers in key-value pairs.

    • Initial Delay (s): the initialDelaySeconds field in the YAML file. This field specifies the waiting time before the first probe is performed after the container is started. Default value: 3. Unit: seconds.

    • Period (s): the periodSeconds field in the YAML file. This field specifies the interval at which probes are performed. Default value: 10. Minimum value: 1. Unit: seconds.

    • Timeout (s): the timeoutSeconds field in the YAML file. This field specifies the time period after which a probe times out. Default value: 1. Minimum value: 1. Unit: seconds.

    • Healthy Threshold: the minimum number of consecutive successes that must occur before a container is considered healthy after a failed probe. Default value: 1. Minimum value: 1. For liveness probes, this parameter must be set to 1.

    • Unhealthy Threshold: the minimum number of consecutive failures that must occur before a container is considered unhealthy after a success. Default value: 3. Minimum value: 1.

    TCP

    Sends a TCP socket to the container. kubelet attempts to open the socket on the specified port. If the connection can be established, the container is considered healthy. Otherwise, the container is considered unhealthy. You can configure the following parameters:

    • Port: the number or name of the container port that you want to open. Valid values of the port number: 1 to 65535.

    • Initial Delay (s): the initialDelaySeconds field in the YAML file. This field specifies the waiting time before the first probe is performed after the container is started. Default value: 15. Unit: seconds.

    • Period (s): the periodSeconds field in the YAML file. This field specifies the interval at which probes are performed. Default value: 10. Minimum value: 1. Unit: seconds.

    • Timeout (s): the timeoutSeconds field in the YAML file. This field specifies the time after which a probe times out. Default value: 1. Minimum value: 1. Unit: seconds.

    • Healthy Threshold: the minimum number of consecutive successes that must occur before a container is considered healthy after a failed probe. Default value: 1. Minimum value: 1. For liveness probes, this parameter must be set to 1.

    • Unhealthy Threshold: the minimum number of consecutive failures that must occur before a container is considered unhealthy after a success. Default value: 3. Minimum value: 1.

    Command

    Runs a probe command in the container to check the health status of the container. You can configure the following parameters:

    • Command: the probe command that is run to check the health status of the container.

    • Initial Delay (s): the initialDelaySeconds field in the YAML file. This field specifies the waiting time before the first probe is performed after the container is started. Default value: 5. Unit: seconds.

    • Period (s): the periodSeconds field in the YAML file. This field specifies the interval at which probes are performed. Default value: 10. Minimum value: 1. Unit: seconds.

    • Timeout (s): the timeoutSeconds field in the YAML file. This field specifies the time after which a probe times out. Default value: 1. Minimum value: 1. Unit: seconds.

    • Healthy Threshold: the minimum number of consecutive successes that must occur before a container is considered healthy after a failed probe. Default value: 1. Minimum value: 1. For liveness probes, this parameter must be set to 1.

    • Unhealthy Threshold: the minimum number of consecutive failures that must occur before a container is considered unhealthy after a success. Default value: 3. Minimum value: 1.

  5. Optional: In the Lifecycle section, set the lifecycle of containers.

    You can configure the following parameters for the lifecycle of the container: Start, Post Start, and Pre Stop. For more information, see Attach Handlers to Container Lifecycle Events.生命周期

    Parameter

    Description

    Start

    Specify a command and parameter that takes effect before the container starts.

    Post Start

    Specify a command that takes effect after the container starts.

    Pre Stop

    Specify a command that takes effect before the container stops.

  6. Optional: In the Volume section, add local volumes or persistent volume claims (PVCs).

    Parameter

    Description

    Add Local Storage

    You can select HostPath, ConfigMap, Secret, or EmptyDir from the PV Type drop-down list. Then, configure the Mount Source and Container Path parameters to mount the volume to the container. For more information, see Volumes.

    Add PVC

    You can mount persistent volumes (PVs) by using persistent volume claims (PVCs). You must create a PVC before you can select the PVC to mount a PV. For more information, see Create a PVC.

    In this example, a disk volume is mounted to the /tmp path of containers. 配置数据卷

  7. Optional: In the Log section, configure log collection and add custom tags.

    Important

    Make sure that the Simple Log Service agent is installed in the cluster.

    Parameter

    Description

    Collection Configuration

    Logstore: creates a Logstore in Simple Log Service to store the collected logs.

    Log Path in Container: Specify stdout or a container path to collect log data.

    • Collect stdout files: If you specify stdout, the stdout files are collected.

    • Text Logs: specifies that the logs in the specified path of the container are collected. In this example, /var/log/nginx is specified as the path. Wildcard characters can be used in the path.

    Custom Tag

    You can also add custom tags. The tags are added to the log of the container when the log is collected. Custom tags help filter and analyze the collected logs.

  8. Click Next to go to the Advanced wizard page.

Step 3: Configure advanced settings

On the Advanced wizard page, configure the following settings: access control, scaling, scheduling, annotations, and labels.

  1. In the Access Control section, you can configure access control settings for exposing backend pods.

    Note

    You can configure the following access control settings based on your business requirements:

    • Internal applications: For applications that provide services within the cluster, you can create a ClusterIP or NodePort Service to enable internal communication.

    • External applications: For applications that are exposed to the Internet, you can configure access control by using one of the following methods:

      • Create a LoadBalancer Service. When you create a Service, set the Type parameter to Server Load Balancer. You can select or create a Server Load Balancer (SLB) instance for the Service and use the Service to expose your application to the Internet.

      • Create an Ingress and use it to expose your application to the Internet. For more information, see Ingress.

    You can also specify how backend pods are exposed to the Internet. In this example, a ClusterIP Service and an Ingress are created to expose the NGINX application to the Internet.

    • To create a Service, click Create on the right side of Services. In the Create dialog box, set the parameters.

      Parameter

      Description

      Name

      The name of the Service.

      Service Type

      The type of the Service. This parameter specifies how the Service is accessed. Valid values:

      Cluster IP

      A Cluster IP Service. This type of Service is exposed by using an internal IP address of the cluster. If you select this type, the Service is accessible only within the cluster. This is the default type. 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.

      Server Load Balancer.

      Note

      A LoadBalancer Service. The Create SLB Instance and Use Existing SLB Instance features are in canary release. You can submit a ticket to apply for using the features.

      This type of Service exposes applications in clusters by using a Classic Load Balancer (CLB) or a Network Load Balancer (NLB) instance.What is SLB? Compared with the Node Port method, the availability and performance of applications exposed by using this method are significantly improved. The following types of are supported:

      • CLB: For more information, see CLB.

      • NLB: For more information, see NLB.

      Node Port

      A NodePort Service. This type of Service allows external users to access Services in a cluster by using the IP address and specified port of a node. You can access an address in the <NodeIP>:<NodePort> format to connect to the NodePort Service. However, you must manually complete the configurations for load balancing.

      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.

      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.

      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.

      Annotations

      The annotations to be added to the Service to configure the SLB instance. For more information, see Add annotations to the YAML file of a Service to configure CLB instances and Configure NLB instances by using annotations.

      Important

      Do not reuse the SLB instance of the API server of the cluster. Otherwise, access to the cluster may become abnormal.

      Label

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

    • To create an Ingress, click Create on the right side of Ingresses. In the Create dialog box, set the parameters.

      Parameter

      Description

      Name

      The name of the Ingress.

      Rules

      Ingress rules are used to enable access to specified Services in a cluster. For more information, see Create an NGINX Ingress.

      • Domain Name: Enter the domain name of the Ingress.

      • Path: Enter the Service URL. The default path is the root path /. In this example, the default path is used. Each path is associated with a backend Service. SLB forwards traffic to a backend Service only when inbound requests match the domain name and path.

      • Service: Select a Service and a Service port.

      • TLS Settings: Select this check box to enable TLS. For more information, see Advanced NGINX Ingress configurations.

      Canary Release

      Specifies whether to enable the canary release feature. We recommend that you select Open Source Solution.

      Ingress Class

      The class of the Ingress.

      Annotations

      You can add custom annotations or select existing annotations. For more information about Ingress annotations, see Annotations.

      Click Add Annotation to add annotations. You can add an unlimited number of annotations.

      Labels

      The labels that describe the characteristics of the Ingress.

      Click Add Label to add labels. You can add an unlimited number of labels.

    In the Access Control section, you can view existing Services and Ingresses. You can also click Update or Delete to update or delete Services and Ingresses.

  2. Optional: In the Scaling section, enable HPA and CronHPA on demand to meet the requirements of different applications.

    • HPA can automatically scale the number of pods in an ACK cluster based on the CPU and memory usage metrics.

      Note

      To enable HPA, you must configure resources required by each container. Otherwise, HPA does not take effect.

      Parameter

      Description

      Metric

      Select CPU Usage or Memory Usage. The selected resource type must be the same as that specified in the Required Resources field.

      Condition

      The resource usage threshold. The Horizontal Pod Autoscaling (HPA) feature triggers scale-out events when the threshold is exceeded.

      Max. Replicas

      The maximum number of replicated pods to which the application can be scaled.

      Min. Replicas

      The minimum number of replicated pods that must run.

    • CronHPA can scale an ACK cluster at a scheduled time. Before you enable CronHPA, you must install ack-kubernetes-cronhpa-controller. For more information about CronHPA, see Create CronHPA jobs.

  3. Optional: In the Scheduling section, specify Update Method, Node Affinity, Pod Affinity, and Pod Anti-affinity. For more information, see Affinity and anti-affinity.

    Note

    Pod scheduling based on node affinity and pod affinity relies on node labels and pod labels. You can add node labels and pod labels that are provided by Kubernetes to configure node affinity and pod affinity. You can also add custom labels to nodes and pods, and then configure node affinity and pod affinity based on these custom labels.

    Parameter

    Description

    Update Method

    The update method. Valid values: Rolling Update and OnDelete. For more information, see Deployments.

    Node Affinity

    Set the Node Affinity parameter by selecting worker node labels as selectors.

    Node affinity supports required and preferred rules, and various operators such as In, NotIn, Exists, DoesNotExist, Gt, and Lt.

    • Required: Specify the rules that must be matched for pod scheduling. In the YAML file, these rules are defined by the requiredDuringSchedulingIgnoredDuringExecution affinity. These rules have the same effect as the NodeSelector parameter. In this example, pods can be scheduled only to nodes with the specified labels. You can create multiple required rules. However, only one of them must be met.

    • Optional: Specify the rules that are optional to be matched for pod scheduling. In the YAML file, these rules are defined by the preferredDuringSchedulingIgnoredDuringExecution affinity. If you specify an optional rule, the scheduler attempts to schedule a pod to a node that matches the optional rule. You can also set weights for optional rules. If multiple nodes match the rule, the node with the highest weight is preferred. You can create multiple optional rules. However, all of them must be met before the pod can be scheduled.

    Pod Affinity

    Pod affinity rules specify how pods are deployed relative to other pods in the same topological domain. For example, you can use pod affinity to deploy services that communicate with each other to the same topological domain, such as a host. This reduces the network latency between these services.

    Pod affinity enables you to specify the node to which pods can be scheduled based on the labels of the pods. Pod affinity supports required and preferred rules, and the following operators: In, NotIn, Exists, and DoesNotExist.

    • Required: Specify the rules that must be matched for pod scheduling. In the YAML file, these rules are defined by the requiredDuringSchedulingIgnoredDuringExecution affinity. A node must match the required rules before pods can be scheduled to the node.

      • Namespace: Specify the namespace to apply the required rule. Pod affinity rules are defined based on the labels that are added to pods and therefore must be scoped to a namespace.

      • Topological Domain: Set the topologyKey. This specifies the key for the node label that the system uses to denote the topological domain. For example, if you set the parameter to kubernetes.io/hostname, topologies are determined by nodes. If you set the parameter to beta.kubernetes.io/os, topologies are determined by the operating systems of nodes.

      • Selector: Click Add to add pod labels.

      • View Applications: Click View Applications and set the Namespace and Application parameters in the dialog box that appears. You can view the pod labels of the selected application and add these labels as selectors.

      • Required rules: Specify labels of existing applications, the operator, and the label value. In this example, the required rule specifies that the application to be created is scheduled to a host that runs applications with the app:nginx label.

    • Optional: Specify the rules that are optional to be matched for pod scheduling. In the YAML file, these rules are defined by the preferredDuringSchedulingIgnoredDuringExecution affinity. If you specify an optional rule, the scheduler attempts to schedule the pod to a node that matches the optional rule. You can set weights for optional rules. The other parameters are the same as those of required rules.

      Note

      Weight: Set the weight of an optional rule to a value from 1 to 100. The scheduler calculates the weight of each node that meets the optional rule based on an algorithm, and then schedules the pod to the node with the highest weight.

    Pod Anti-affinity

    Pod anti-affinity rules specify that pods are not scheduled to topological domains where pods with matching labels are deployed. Pod anti-affinity rules apply to the following scenarios:

    • Schedule the pods of an application to different topological domains, such as multiple hosts. This allows you to enhance the stability of your service.

    • Grant a pod exclusive access to a node. This enables resource isolation and ensures that no other pods can share the resources of the specified node.

    • Schedule pods of an application to different hosts if the pods may interfere with each other.

    Note

    The parameters of pod anti-affinity rules are the same as those of pod affinity rules. Create rules based on scenarios.

    Toleration

    The tolerations that allow pods to be scheduled to nodes with matching taints. For more information about the configurations of taints (such as key, value and taint effect) and tolerations, see the official Kubernetes documentation Taints and Tolerations.

    Schedule to Virtual Nodes

    Specifies whether to schedule pods to virtual nodes. Only ACK Pro clusters support this parameter. This parameter is unavailable if the cluster does not contain a virtual node. For more information about how to schedule pods to virtual nodes, see the Use only elastic container instances section of the "Configure resource allocation based on ECS instances and elastic container instances" topic.

  4. Optional: In the Labels,Annotations section, click Add to add labels and annotations to pods.

    Parameter

    Description

    Pod Labels

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

    Pod Annotations

    The annotations to be added to the pod.

  5. Click Create.

Step 4: Check the application

On the Complete wizard page, you can view the application.

  1. Click View Details below Creation Task Submitted.

    查看详情

    The nginx-deployment details page appears.

    Note

    You can also perform the following steps to create an Ingress and Service: Go to the Access Method tab of the application details page, as shown in the preceding figure.

    • Click Create on the right side of Services to create a Service.

    • Click Create on the right side of Ingresses to create an Ingress.

  2. In the left-side navigation pane, choose Ingresses and Load Balancing > Ingresses. Then, you can find an Ingress in the list.

    路由规则

  3. Enter the domain name of the Ingress into the address bar of a browser to access the NGINX welcome page.

    访问nginx

What to do next

View stateless application details

In the left-side navigation pane of the ACK console, click Clusters. Click the name of the cluster where the application is deployed or click Details in the Actions column. Choose Workloads > Deployments. On the Deployments page, click the name of the deployed application or click Details in the Actions column.

Note

In the Deployment list, click the Label column, enter a label key and label value, and click OK to list applications that have the specified label.

On the details page of the application, you can view the YAML file of the application. You can also modify, scale, redeploy, and refresh the application.

Operation

Description

Edit

On the details page of the application, click Edit in the upper-right corner of the page to modify the application configurations.

Scale

On the details page of the application, click Scale in the upper-right corner of the page to scale the application to a required number of pods.

View in YAML

On the details page of the application, click View in YAML to update or download the YAML file. You can also click Save As to save the file as a different name.

Redeploy

On the details page of the application, click Redeploy in the upper-right corner of the page to redeploy the application.

Refresh

On the details page of the application, click Refresh in the upper-right corner of the page to refresh the application details page.

Modify an existing Deployment

On the Deployments page, select a Deployment and click More in the Actions column to perform the following operations.

Operation

Description

View in YAML

View the YAML file of the application.

Redeploy

Redeploy the application.

Edit Label

Configure application labels.

Edit Annotations

Add annotations to the application.

Node Affinity

Configure node affinity rules. For more information, see Scheduling.

Scaling

Configure scaling settings. For more information, see Implement horizontal pod autoscaling and Implement CronHPA.

Toleration

Configure toleration rules. For more information, see Scheduling.

Upgrade policy

Configure the update policy.

  • Rolling Update: Pods are updated in a rolling update manner.

  • OnDelete: All existing pods are deleted before new pods are created.

Clone

Create a new application by using the same container settings as the current application.

Roll Back

Roll back the application to a previous version.

Logs

View the application log.

Delete

Delete the application.

Batch redeploy applications

In the lower part of the Deployments page, click Batch Redeploy to redeploy multiple applications at a time.

Create a Linux application by using an orchestration template

In an orchestration template, you must define the resource objects that are required for running an application and configure mechanisms such as label selectors to manage the resource objects that make up the application.

This section describes how to use an orchestration template to create an NGINX application that consists of a Deployment and a Service. The Deployment provisions pods for the application and the Service manages access to the backend pods.

  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 YAML in the upper-right corner.

  4. Configure the parameters and click Create.

    • Sample Template: ACK provides YAML templates of various resource types. This simplifies the deployment of resource objects. You can also create a custom template based on YAML syntax to define the resources that you want to create.

    • Create Workload: You can quickly define a YAML template.

    • Use Existing Template: You can import an existing template.

    • Save Template: You can save the template that you have configured.

    The following sample template is based on an orchestration template provided by ACK. You can use this template to create a Deployment to run an NGINX application.

    Note
    • ACK supports Kubernetes YAML. You can use three hyphens (---) to separate resource objects. This allows you to define multiple resource objects in one template.

    • Optional: By default, when you mount a volume to an application, the files in the mount target are overwritten. To avoid overwriting the existing files, you can add the subPath parameter.

    apiVersion: apps/v1 
    kind: Deployment
    metadata:
        name: nginx-deployment-basic
        labels:
          app: nginx
    spec:
        replicas: 2
        selector:
          matchLabels:
            app: nginx
        template:
          metadata:
            labels:
              app: nginx
          spec:
            containers:
            - name: nginx
              image: nginx:1.7.9 # replace it with your exactly <image_name:tags>
              ports:
              - containerPort: 80
              volumeMounts:
              - name: nginx-config
                mountPath: /etc/nginx/nginx.conf 
                subPath: nginx.conf   # Set the subPath parameter.     
            volumes:
            - name: nginx-config
              configMap:
                name: nginx-conf
    ---
    
    apiVersion: v1     
    kind: Service
    metadata:
       name: my-service1        #TODO: to specify your service name
       labels:
         app: nginx
    spec:
       selector:
         app: nginx             #TODO: change label selector to match your backend pod
       ports:
       - protocol: TCP
         name: http
         port: 30080            #TODO: choose an unique port on each node to avoid port conflict
         targetPort: 80
       type: LoadBalancer        ##In this example, the type is changed from Nodeport to LoadBalancer. 
    ---
    
    # The ConfigMap of the mounted volume.
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: nginx-conf
      namespace: default
    data:
      nginx.conf: |-
       user  nginx;
       worker_processes  1;
       error_log  /var/log/nginx/error.log warn;
       pid        /var/run/nginx.pid;
       events {
            worker_connections  1024;
        }
        http {
            include       /etc/nginx/mime.types;
            default_type  application/octet-stream;
            log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                              '$status $body_bytes_sent "$http_referer" '
                              '"$http_user_agent" "$http_x_forwarded_for"';
            access_log  /var/log/nginx/access.log  main;
            sendfile        on;
            #tcp_nopush     on;
            keepalive_timeout  65;
            #gzip  on;
            include /etc/nginx/conf.d/*.conf;
        } 
  5. After you click Create, a message that indicates the deployment status appears.

Use kubectl to manage applications

You can use kubectl to create applications or view application pods.

Use kubectl to create applications

  1. Run the following kubectl command to start a pod. An NGINX web server is used in this example.

    • If the Kubernetes version of your cluster is later than 1.18, run the following command:

      kubectl create deployment nginx --image=registry.aliyuncs.com/spacexnice/netdia:latest
    • If the Kubernetes version of your cluster is earlier than 1.18, run the following command:

       kubectl run -it nginx --image=registry.aliyuncs.com/spacexnice/netdia:latest
  2. Run the following command to create an Ingress for the pod and specify --type=LoadBalancer to use a load balancer provided by Alibaba Cloud.

    kubectl expose deployment nginx --port=80 --target-port=80 --type=LoadBalancer

Use kubectl to view pods

Run the following command to view all running pods in the default namespace:

kubectl get pods

Expected output:

NAME                                   READY     STATUS    RESTARTS   AGE
nginx-2721357637-d****                 1/1       Running   1          9h

Create an application by using an image pull Secret

ACK allows you to use image pull Secrets in the ACK console. You can create an image pull Secret or use an existing image pull Secret.

To ensure the security of images, when you create an application from a private image, you usually need to set a Secret for the image. You can use a docker-registry Secret to synchronize the identity authentication information required by a private image repository to Kubernetes in 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, select the namespace and click Create from Image in the upper-right corner of the page.

  4. On the Basic Information wizard page, set the parameters. For more information, see Configure basic settings.

  5. Configure containers.

    The following example describes how to configure an image pull Secret. For more information about container configurations, see Basic container configurations.

    1. On the Container wizard page, enter the address of the private image in the Image Name field in the domainname/namespace/imagename format.

      Note

      Public images do not require Secrets.

    2. Enter the image version that you want to use in the Image Version field.

      A Tomcat private image is used in this example.

      容器配置

    3. Click Set Image Pull Secret, and create a Secret or select an existing Secret in the dialog box that appears.

      • You can select New Secret. If you select New Secret, set the following parameters:

        Parameter

        Description

        Name (regsecret)

        The key name of the Secret. You can enter a custom name.

        Repository Domain (docker-server)

        The address of the specified Docker repository. If you use an image repository in Container Registry, the address of the image repository is automatically displayed.

        Username (docker-username)

        The username used to log on to the Docker repository. If you use an image repository in Container Registry, your account name is used as the username. Alibaba Cloud accounts and Resource Access Management (RAM) users are supported.

        Password (docker-password)

        The password used to log on to the Docker repository. If you use an image repository in Container Registry, the password is the logon password of Container Registry.

        Email (docker-email)

        The email address. This parameter is optional.

        Click OK. Then, you can find the Secret.

        设置密钥

      • You can also click Existing Secret. You can use kubectl or YAML files to create image pull Secrets in advance. For more information, see How do I use private images in Kubernetes clusters? and Create an application by using a private image repository.

        已有密钥

  6. Configure other parameters based on your requirements. Then, click Create.

    For more information, see Configure advanced settings.

  7. In the left-side navigation pane of the ACK console, click Clusters.

  8. On the Clusters page, find the cluster that you want to manage and click the name of the cluster or click Details in the Actions column. The details page of the cluster appears.

  9. In the left-side navigation pane of the details page, choose Workloads > Deployments.

  10. On the Deployments page, you can view the status of the application that you created.

    If the Tomcat application is running, this indicates that the Tomcat private image is successfully pulled with the Secret.

References