Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Using kubectl to Operate a Cluster

Updated on 2024-12-26 GMT+08:00

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.

NOTICE:

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
NOTE:

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
NOTE:

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>
NOTE:

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:

  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>

    The <nodename> in CCE 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

    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.

  3. Perform maintenance operations on the node, such as resetting the node.
  4. 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.

NOTE:

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>
NOTICE:

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

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback