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 Connecting to a Cluster Using kubectl. After connection, 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.
Getting Started
get
The get command is used to obtain details about one or more resources in a cluster.
This command prints a table of the most important information about all resources, including cluster nodes, running pods, Deployments, and Services.
Many 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 all pods with detailed information:
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 list 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 the information of pods in the YAML format:
kubectl get pod <podname> -o yaml
To obtain the information 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 is used to create cluster resources based on files 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 exposes a resource as a new Kubernetes service. Possible resources include a pod, Service, and Deployment.
kubectl expose deployment <deployname> --port=81 --type=NodePort --target-port=80 --name=<service-name>
The command above creates a Service for the Deployment. The --port parameter specifies the port that the Service will expose, the --type parameter determines the type of the Service, and the --target-port parameter specifies the port of the backend pod associated with the Service. Visiting ClusterIP:port allows you to access the applications in the cluster.
run
The run command runs a particular image in the cluster.
Example:
kubectl run <deployname> --image=nginx:latest
To run a particular image using a specified command:
kubectl run <deployname> --image=busybox --command -- ping example.com
set
The set command configures object resources.
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 edits a resource from the default editor.
Example:
To update a pod:
kubectl edit pod po-nginx-btv4j
The example command yields the same effect as the following command:
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 views documents or reference documents.
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 with minimal delay:
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 particular deployment:
kubectl rollout status deployment/<deployname>
To view the rollout history of a particular deployment:
kubectl rollout history deployment/<deployname>
To roll back to the previous deployment: (by default, a resource is rolled back to the previous version)
kubectl rollout undo deployment/test-nginx
scale
The scale command sets a new size for a resource by adjusting the number of resource replicas.
kubectl scale deployment <deployname> --replicas=<newnumber>
autoscale
The autoscale command automatically adjusts the number of replicas based on the CPU usage of workloads. The autoscale command allows you to define a range of replicas for a workload (such as Deployment, ReplicaSet, StatefulSet, or ReplicationController). During running, the pods will be automatically scaled in or out within this range based on the average CPU usage of all pods. If the target usage is not specified or the parameter 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, 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:
- 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>
The <nodename> in CCE specifies the private network IP address of a node by default.
- 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
By using --ignore-daemonsets, the DaemonSet pods will be ignored. Additionally, --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.
- Perform maintenance operations on the node, such as resetting the node.
- After node maintenance is completed, 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 dump current cluster information to stdout:
kubectl cluster-info dump
top*
The top command shows the usage of resources like CPU, memory, and storage in a cluster. Ensure that the Kubernetes Metrics Server is running properly for this command to work.
taint*
The taint command updates the taints on one or more nodes.
certificate*
The certificate command modifies the 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 detailed information about a resource, while the describe command provides status information about a resource in a cluster. The describe command is similar to the get command, but it does not support the -o option. For resources of the same type, the describe command provides the same output format and content.
If you need specific information about a resource, you can use the get command for more detailed information. On the other hand, 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 detailed status information.
kubectl describe pod <podname>
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 handling multiple containers within a pod, you can use the -c option to specify the desired container.
kubectl exec -it <podname> -- bash kubectl exec -it <podname> -c <containername> -- bash
port-forward*
The port-forward command forwards one or more local ports to a pod.
Example:
To listen to local port 5000 and forward it to port 6000 in 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 remote pod.
auth*
The auth command inspects authorization.
attach*
The attach command is similar to the logs -f command and attaches to a process that is already running inside an existing container. 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 original 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 compared to the patch and edit commands. It allows you to maintain resource configurations in source control. When an update occurs, 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, updating only the changed parts. The apply command works similarly to the replace command, but it does not delete the original resources and 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 without first deleting the container or using the replace command, the patch command is to the rescue. The patch command updates field(s) of a resource using strategic merge patch, a JSON merge patch, or a JSON patch. 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 update labels on a resource.
kubectl label pods my-pod new-label=newlabel
annotate
The annotate command update annotations on a resource.
kubectl annotate pods my-pod icon-url=http://*****
completion
The completion command provides autocompletion for shell.
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 kubeconfig files. An example use case of this command is 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 for the current context.
kubectl version
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot