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

Using kubectl to Operate a Cluster

kubectl

kubectl is a command line tool for Kubernetes clusters. You can install kubectl on any node and run kubectl commands to operate your Kubernetes clusters.

For details about how to install kubectl, see Accessing a Cluster Using kubectl. After using kubectl to access a cluster, you can run the kubectl cluster-info command to view the cluster information. The following shows an example:

# kubectl cluster-info
Kubernetes master is running at https://*.*.*.*:5443
CoreDNS is running at https://*.*.*.*:5443/api/v1/namespaces/kube-system/services/coredns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

Run the kubectl get nodes command to view information about nodes in the cluster.

# kubectl get nodes
NAME            STATUS    ROLES     AGE       VERSION
192.168.0.153   Ready     <none>    7m        v1.15.6-r1-20.3.0.2.B001-15.30.2
192.168.0.207   Ready     <none>    7m        v1.15.6-r1-20.3.0.2.B001-15.30.2
192.168.0.221   Ready     <none>    7m        v1.15.6-r1-20.3.0.2.B001-15.30.2

For more kubectl commands, see kubectl Quick Reference.

Basic Commands

get

The get command obtains details about one or more resources in a cluster.

This command obtains details about all resources, including cluster nodes, pods, Deployments, and Services.

Multiple namespaces can be created in a cluster. If no namespace is specified in the command, --namespace=default is used by default, which means resources in the default namespace are obtained.

Examples:

To obtain details of all pods:

kubectl get pod -o wide

To obtain all pods running in all namespaces:

kubectl get pod --all-namespaces

To obtain the labels of all pods running in all namespaces:

kubectl get pod --show-labels

To obtain all namespaces of the node:

kubectl get namespace

Similarly, you can run the kubectl get svc, kubectl get nodes, and kubectl get deploy commands to obtain information about other resources.

To obtain details of pods in the YAML format:

kubectl get pod <podname> -o yaml

To obtain details of pods in the JSON format:

kubectl get pod <podname> -o json
kubectl get pod rc-nginx-2-btv4j -o=custom-columns=LABELS:.metadata.labels.app

LABELS indicates a comma-separated list of user-defined column titles. metadata.labels.app indicates the data to be listed in either YAML or JSON format.

create

The create command creates cluster resources based on a file or input.

If you have a YAML or JSON file that defines the desired resource, you can use the following command to create the resource specified in the file:

kubectl create -f <filename>

expose

The expose command creates a Service for a resource such as a pod or Deployment.

kubectl expose deployment <deployname> --port=81 --type=NodePort --target-port=80 --node-port=31000 --name=<service-name>

The expose command creates a NodePort Service for the Deployment. --port indicates the Service port (used for access inside the cluster), --type indicates the Service type, --target-port indicates the port of the backend pod associated with the Service, and --node-port indicates the node port (used for access outside the cluster). --node-port is optional. If it is not specified, the cluster randomly allocates a port from 30000 to 32767.

run

The run command creates a single pod or Deployment, which is suitable for test environments.

Example:

kubectl run <deployname> --image=nginx:latest

To specify the command that is automatically executed when you create a pod or Deployment:

kubectl run <deployname> --image=busybox --command -- ping example.com

set

The set command configures a function for an object.

Example:

To update the container image of a Deployment to version 1.0 in rolling mode:

kubectl set image deployment/<deployname> <containername>=<containername>:1.0

edit

The edit command provides a way to update a resource.

Example:

To update a pod:

kubectl edit pod po-nginx-btv4j

The example command yields the same effect as the following commands:

kubectl get pod po-nginx-btv4j -o yaml >> /tmp/nginx-tmp.yaml
vim /tmp/nginx-tmp.yaml
# do some changes here 
kubectl replace -f /tmp/nginx-tmp.yaml

explain

The explain command gets documents or other references.

Example:

To get documentation of pods:

kubectl explain pod

delete

The delete command deletes resources by resource name or label.

Example:

To delete a pod immediately:

kubectl delete pod <podname> --now 
kubectl delete -f nginx.yaml
kubectl delete deployment <deployname>

Deployment Commands

rollout

The rollout command manages the rollout of a resource.

Examples:

To check the rollout status of a specific resource:

kubectl rollout status deployment/<deployname>

To view the rollout history of a specific resource:

kubectl rollout history deployment/<deployname>

To roll back a specific resource (by default, a resource is rolled back to the previous version):

kubectl rollout undo deployment/test-nginx

scale

The scale command increases or reduces the number of replicas when the load increases or decreases.

kubectl scale deployment <deployname> --replicas=<newnumber>

autoscale

The autoscale command automatically adjusts the number of replicas based on the CPU utilization of a workload. The autoscale command allows you to define a range of replicas for a workload (such as a Deployment, ReplicaSet, or StatefulSet). The pods will be automatically added or removed within this range based on the average CPU utilization of all pods. If the target utilization is not specified or is set to a negative value, the default auto scaling policy will be applied.

kubectl autoscale deployment <deployname> --min=<minnumber> --max=<maxnumber> --cpu-percent=<cpu>

Cluster Management Commands

cordon, drain, and uncordon

If you need to upgrade a node or if a node becomes unavailable due to a breakdown, you can use these commands to reschedule the pods running on that node to other nodes. The procedure is as follows:

  1. Run the cordon command to mark a node as unschedulable. This means that new pods will not be scheduled to that node.

    kubectl cordon <nodename>

    In CCE, <nodename> specifies the private network IP address of a node by default.

  2. Run the drain command to evict pods on the node and smoothly migrate these pods to other nodes:

    kubectl drain <nodename> --ignore-daemonsets --delete-emptydir-data

    --ignore-daemonsets means DaemonSet pods will be ignored. --delete-emptydir-data ensures that if there are pods using emptyDir, the node will continue to be drained, and any local data associated with the node will be deleted.

  3. Perform maintenance operations on the node, for example, resetting the node.
  4. Run the uncordon command to mark the node as schedulable.

    kubectl uncordon <nodename>

cluster-info

To display the add-ons running in the cluster:

kubectl cluster-info

To view details:

kubectl cluster-info dump

top*

The top command shows the usages of resources like CPU, memory, and storage in a cluster. Ensure that the Kubernetes Metrics Server is running normally, or this command may not work.

taint*

The taint command updates the taints on one or more nodes.

certificate*

The certificate command modifies certificate resources.

Fault Diagnosis and Debugging Commands

describe

The describe command is similar to the get command. The main distinction is that the get command provides details about a resource, while the describe command only provides status information about a resource in a cluster. In addition, the describe command does not support the -o flag. For resources of the same type, the describe command provides the same output format and content.

kubectl describe pod <podname>

If you need details about a resource, you can use the get command for more information. If you want to check the status of a resource, such as a pod that is not in the running state, you can use the describe command to obtain more status information.

logs

The logs command prints the standard output of programs running inside a container during pod execution. To display logs in the tail -f mode, run this command with the -f flag.

kubectl logs -f <podname>

exec

The kubectl exec command functions similarly to the Docker exec usage. When multiple containers run in a pod, you can use the -c flag to specify the desired container.

kubectl exec -it <podname> -- bash
kubectl exec -it <podname> -c <containername> -- bash

port-forward*

The port-forward command forwards requests from one or more local ports to a pod port.

Example:

To listen to local port 5000 and forward requests to port 6000 used by a pod created in <my-deployment>:

kubectl port-forward deploy/my-deployment 5000:6000

cp

To copy files or directories and paste them to a container:

kubectl cp /tmp/foo <podname>:/tmp/bar -c <containername>

The local files in /tmp/foo are copied and pasted to the /tmp/bar directory of a specific container in a pod.

auth*

The auth command checks authorization.

attach*

The attach command is similar to the logs -f command. To exit, run the ctrl-c command. If a pod contains multiple containers, to view the output of a specific container, use -c <containername> following <podname> to specify a container.

kubectl attach <podname> -c <containername>

Advanced Commands

replace

The replace command updates or replaces an existing resource. If you need to modify certain attributes of a resource, you can directly edit the YAML file and use the replace command to make changes such as adjusting the number of replicas, adding or modifying labels, changing the image version, or modifying the port.

kubectl replace -f <filename>

Resource names cannot be updated.

apply*

The apply command offers stricter control over resource updates than the patch and edit commands. It allows you to maintain resource configurations in source control. When there is an update, the configuration file is pushed to the server, and the kubectl apply command applies the latest configuration to the resource. Kubernetes compares the current configuration file with the applied configuration before applying the update, and then updates only the changed parts. The apply command works similarly to the replace command, but it does not delete the original resources or recreate new ones. Instead, it updates the existing resources. Additionally, kubectl apply adds a comment to the resource, marking the current apply operation, similar to a Git operation.

kubectl apply -f <filename>

patch

If you want to modify attributes of a running container but you do not want to delete the container first or use the replace command, a patch command is the rescue. This command changes settings for a running pod. For example, to change a pod label from app=nginx1 to app=nginx2 while the pod is running:

kubectl patch pod <podname> -p '{"metadata":{"labels":{"app":"nginx2"}}}'

convert*

The convert command converts configuration files between different API versions.

Configuration Commands

label

The label command updates labels on a resource.

kubectl label pods my-pod new-label=newlabel

annotate

The annotate command updates annotations on a resource.

kubectl annotate pods my-pod icon-url=http://*****

completion

The completion command provides autocompletion for kubectl.

Other Commands

api-versions

The api-versions command prints the supported API versions.

kubectl api-versions

api-resources

The api-resources command prints the supported API resources.

kubectl api-resources

config*

The config command modifies the kubeconfig file that is used to access APIs. For example, use this command to configure authentication information in API calls.

help

The help command gets all command references.

version

The version command prints the client and server version information.

kubectl version