Common Kubectl Commands
1. Kubectl Command Summary
Basic Commands (Beginner)
| Command | Description |
|---|---|
| kubectl create | Create a resource object from a YAML/JSON file or from standard input. Supports many subcommands such as namespace, pod, deployment, service, etc. |
| kubectl expose | Expose the ports of a resource defined in a YAML/JSON file through a new Service resource object. |
| kubectl run | Create and run one or more container images. |
| kubectl set | Configure specific features on resource objects. |
Basic Commands (Intermediate)
| Command | Description |
|---|---|
| kubectl explain | Show detailed information about a resource object (commonly used as a hint when writing YAML. For example, kubectl explain deployment will show the fields you can write under deployment, their attributes, and can be used hierarchically). |
| kubectl get | Retrieve information about one or more resource objects. |
| kubectl edit | Edit a resource object defined on the server using the default editor. |
| kubectl delete | Delete resources by YAML/JSON file, standard input, resource name, or label selector. |
Deploy Commands
| Command | Description |
|---|---|
| kubectl rollout | Manage the rollout of resources. |
| kubectl rollout-update | Perform a rolling update using an rc (replication controller). |
| kubectl scale | Scale up or down deployments, replicasets, replication controllers, etc. |
| kubectl autoscale | Automatically set the number of running Pods in Kubernetes (horizontal pod autoscaling). |
Cluster Manager Commands
| Command | Description |
|---|---|
| kubectl cetificate | Modify Certificate resources. |
| kubectl cluster-info | Display cluster information. |
| kubectl top | Show CPU, memory, and storage usage. |
| kubectl cordon | Mark a node as unschedulable. |
| kubectl uncordon | Mark a node as schedulable. |
| kubectl drain | Safely evict all Pods from a node. |
| kubectl taint | Add taints to one or more nodes. |
Troubleshooting and Debugging Commands
| Command | Description |
|---|---|
| kubectl describe | Display detailed information about one or more resource objects. |
| kubectl logs | Print the logs of a single container in a Pod. |
| kubectl attach | Attach to a running container. |
| kubectl exec | Execute a command in a specified container. |
| kubectl port-forward | Forward a local port to a port on a Pod. |
| kubectl proxy | Forward a local port to the kube-apiserver. |
| kubectl cp | Copy files between a Pod and the host. |
| kubectl auth | Inspect authorization. |
Advanced Commands
| Command | Description |
|---|---|
| kubectl diff | Compare local YAML/JSON files against the configurations running in the kube-apiserver and show differences. |
| kubectl apply | Configure or create resources from YAML/JSON files or standard input. |
| kubectl patch | Modify resource fields using a patch (patch-style update). |
| kubectl replace | Replace a resource object by providing a YAML/JSON file or from standard input. |
| kubectl wait | Wait for conditions on one or more resources to be met. |
| kubectl convert | Convert YAML/JSON files to different resource versions. |
| kubectl kustomize | Customize Kubernetes configurations. |
Settings Commands
| Command | Description |
|---|---|
| kubectl label | Add, update, or remove labels on resources. |
| kubectl annotate | Update annotations on one or more resource objects. |
| kubectl completion | Shell command auto-completion. |
Other Commands
| Command | Description |
|---|---|
| kubectl config | Manage kubeconfig configuration files. |
| kubectl plugin | Run kubectl CLI plugins. |
| kubectl version | Show client and server version information. |
| kubectl api-versions | List the API groups and versions supported by the current Kubernetes cluster, in the form /. |
| kubectl api-resources | List the resource types supported by the current Kubernetes cluster. |
| kubectl options | Show the list of supported global command-line options. |
2. Common RESOURCE_NAME Values
| Name | Abbreviation |
|---|---|
| all | |
| certificatesigningrequests | (abbr csr) |
| clusterrolebindings | |
| clusterrol | |
| componentstatuses | (abbr cs) |
| configmaps | (abbr cm) |
| controllerrevisions | |
| cronjobs | |
| customresourcedefinition | (abbr crd) |
| daemonsets | (abbr ds) |
| deployments | (abbr deploy) |
| endpoints | (abbr ep) |
| events | (abbr ev) |
| horizontalpodautoscalers | (abbr hpa) |
| ingresses | (abbr ing) |
| jobs | |
| limitranges | (abbr limits) |
| namespaces | (abbr ns) |
| networkpolicies | (abbr netpol) |
| nodes | (abbr no) |
| persistentvolumeclaims | (abbr pvc) |
| persistentvolumes | (abbr pv) |
| poddisruptionbudgets | (abbr pdb) |
| podpreset | |
| pods | (abbr po) |
| podsecuritypolicies | (abbr psp) |
| podtemplates | |
| replicasets | (abbr rs) |
| replicationcontrollers | (abbr rc) |
| resourcequotas | (abbr quota) |
| rolebindings | |
| roles | |
| secrets | |
| serviceaccounts | (abbr sa) |
| services | (abbr svc) |
| statefulsets | (abbr sts) |
| storageclasses | (abbr sc) |
3. Detailed Explanation of Important kubectl Commands
kubectl create
Create a cluster resource object from a configuration file or from stdin. Supports JSON and YAML files.
Syntax:
kubectl create -f FILENAMEExamples:
# Create a Pod from pod.ymlkubectl create -f ./pod.yml
# Create a Pod from YAML via stdincat pod.yml | kubectl create -f -
# Grant the cluster-admin role to gitlab-runner in the namespacekubectl create rolebinding deploy-runner --clusterrole=cluster-admin --serviceaccount=deploy:default --namespace=hsh-pre-servicekubectl expose
Expose a resource as a new Kubernetes Service. Specify a deployment, service, replica set, replication controller, or pod, and use that resource’s selector as the selector of the new Service on the specified port. Deployment or replica set can only be exposed as a new Service when their selector can be converted into a selector supported by Service, i.e., when the selector only contains matchLabels.
Syntax:
kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]Examples:
# Create a Service for nginx rc and forward Service port 80 to container port 8000kubectl expose rc nginx --port=80 --target-port=8000
# Create a Service for the rc identified by type and name in "nginx-controller.yml",# forwarding Service port 80 to container port 8000kubectl expose -f nginx-controller.yml --port=80 --target-port=8000kubectl get
Retrieve information about one or more resource objects.
Syntax:
kubectl get RESOURCE_NAMEExamples:
# View master statuskubectl get componentstatuses
# List all namespaceskubectl get namespaces
# List all Podskubectl get pods
# Show more information about Pods (e.g., Pod IP and Node)kubectl get pods -o wide
# List the rc named webkubectl get replicationcontroller web
# Get information about Pod web-pod-13cd8 and output it in JSON formatkubectl get -o json pod web-pod-13cd8
# Find Pods defined in pod.yaml and output them in JSON formatkubectl get -f pod.yaml -o json
# Get the status of a Podkubectl get -o template pod/kube-dns-795f5f6f9c-ldxxs --template {{.status.phase}}
# List all rc and serviceskubectl get rc,services
# Get all rc, svc, and Pod resources that match the criteriakubectl get rc/web service/frontend pods/web-pod-13cd8
# Get all resourceskubectl get allkubectl edit
Edit a resource defined on the server using the default editor. Any resource retrievable via the command line can be edited using edit. The edit command opens the editor defined by the KUBE_EDITOR, GIT_EDITOR, or EDITOR environment variables. You can edit multiple resources at once, but changes are submitted in a single operation. Besides command arguments, edit also accepts filenames. YAML is the default output format; use -o json to edit in JSON.
Syntax:
kubectl edit (RESOURCE/NAME | -f FILENAME)Examples:
# Edit the Service named "docker-registry"kubectl edit svc/docker-registry
# Use an alternative editorKUBE_EDITOR="nano" kubectl edit svc/docker-registry
# Edit deployment "mydeployment" in YAML format and save the changed config into annotationskubectl edit deployment/mydeployment -o yaml --save-configkubectl delete
Delete resources by configuration file, stdin, resource names, or label selectors. Supports JSON and YAML files. You can only specify one type of parameter at a time: filenames, resource names, or label selectors.
Note: delete does not check resource versions. If an update occurs while a delete is in progress, that update will be deleted along with the resource.
Syntax:
kubectl delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])Examples:
# Delete the Pod specified by type and name in pod.ymlkubectl delete -f ./pod.yml
# Delete the Pod specified by type and name in the YAML from stdincat pod.json | kubectl delete -f -
# Delete Pods and Services named "foo" and "bar"kubectl delete pod,service foo bar
# Delete Pods and Services whose label name=myLabelkubectl delete pods,services -l name=myLabel
# Force delete Pods on a dead nodekubectl delete pod foo --grace-period=0 --force
# Delete all Podskubectl delete pods --allkubectl rollout
Manage the rollout of resources. Supported resources: deployments, daemonsets.
Subcommands:
- history (show rollout history)
- pause (pause a resource)
- resume (resume a paused resource)
- status (show rollout status)
- undo (roll back to a previous revision)
Syntax:
kubectl rollout SUBCOMMANDExamples:
# Show the rollout history of a deploymentkubectl rollout history deployment/abc
# Show details of daemonset revision=3kubectl rollout history daemonset/abc --revision=3
# Mark a deployment as paused. While paused, updates to the deployment have no effect.kubectl rollout pause deployment/nginx
# Resume a paused deploymentkubectl rollout resume deployment/nginx
# Show the rollout status of a deploymentkubectl rollout status deployment/nginx
# Roll back a deployment to the previous revisionkubectl rollout undo deployment/abckubectl rollout undo --dry-run=true deployment/abc
# Roll back a daemonset to revision 3kubectl rollout undo daemonset/abc --to-revision=3
# Set the number of replicas in the ReplicaSet named foo to 3kubectl scale --replicas=3 rs/foo
# Set the number of Pod replicas defined in foo.yaml to 3kubectl scale --replicas=3 -f foo.yaml
# If mysql currently has 2 replicas, scale it to 3kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
# Set the number of Pod replicas in multiple RCskubectl scale --replicas=5 rc/foo rc/barkubectl describe
Print detailed information about one or more specified resources. This command combines multiple API calls and outputs a detailed description of the specified resource(s).
Syntax:
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)Examples:
# Describe a nodekubectl describe nodes kubernetes-minion-emt8.c.myproject.internal
# Describe a Podkubectl describe pods/nginx
# Describe the Pod specified by type and name in pod.ymlkubectl describe -f pod.yml
# Describe all Podskubectl describe pods
# Describe all Pods with label name=myLabelkubectl describe po -l name=myLabel
# Describe all Pods managed by the replication controller "frontend"# (Pods created by an rc use the rc name as prefix)kubectl describe pods frontendkubectl logs
Print the logs of a container in a Pod. If the Pod has only one container, the container name can be omitted.
Syntax:
kubectl logs [-f] [-p] POD [-c CONTAINER]Examples:
# Return a snapshot of logs from Pod nginx (with a single container)kubectl logs nginx
# Return a snapshot of logs from the previously terminated container web-1 in Pod rubykubectl logs -p -c ruby web-1
# Stream logs from container web-1 in Pod rubykubectl logs -f -c ruby web-1
# Show only the last 20 log lines from Pod nginxkubectl logs --tail=20 nginx
# Show all logs generated in the last hour from Pod nginxkubectl logs --since=1h nginxkubectl exec
Execute a command inside a container.
Syntax:
kubectl exec POD [-c CONTAINER] -- COMMAND [args...]Examples:
# Run "date" in the first container of Pod 123456-abcd and print the outputkubectl exec 123456-abcd date
# Run "date" in container ruby-container of Pod 123456-abcd and print the outputkubectl exec 123456-abcd -c ruby-container date
# Start an interactive shell by sending console input to the "bash" command# in ruby-container of Pod 123456-abcd and forwarding stdout/stderr backkubectl exec 123456-abcd -c ruby-container -i -t -- bash -ilkubectl apply
Create or update a cluster resource object from a configuration file or stdin. Supports JSON and YAML files.
Syntax:
kubectl apply -f FILENAMEExamples:
# Create a Pod from pod.ymlkubectl apply -f ./pod.yml
# Create a Pod from YAML via stdincat pod.yml | kubectl apply -f -Differences between creating resources with kubectl create and kubectl apply:
| kubectl apply | kubectl create |
|---|---|
| Directly updates existing resources in the cluster based on the fields present in the YAML file (the YAML can contain only the fields you want to change). | First deletes all existing resources in the cluster, then recreates new resources from the YAML file (which must contain the full configuration). |
| The YAML can be partial and only contain required fields. | The YAML must contain a complete set of configuration fields. |
kubectl apply only operates on the fields that have changed in the YAML file. | kubectl create operates on all fields in the YAML file. |
When only some declarations in the YAML file are changed instead of all of them, you can use kubectl apply. | If there are no changes in the YAML file, running kubectl replace with the same YAML will fail because there is no change information. |
kubectl label
Update (add, modify, or remove) labels on resources. Labels must start with a letter or number, can contain letters, numbers, dashes, dots, and underscores, and must be no longer than 63 characters. If --overwrite is true, existing labels can be overwritten; otherwise, attempts to overwrite labels will fail. If --resource-version is specified, the update will use that resource version; otherwise, the existing resource version is used.
Syntax:
kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]Examples:
# Add label unhealthy=true to Pod fookubectl label pods foo unhealthy=true
# Overwrite label 'status' on Pod foo with value 'unhealthy'kubectl label --overwrite pods foo status=unhealthy
# Add a label to all Pods in the namespacekubectl label pods --all status=unhealthy
# Update the label on Pod foo only if resource-version=1kubectl label pods foo status=unhealthy --resource-version=1
# Delete label "bar" from Pod foo (use a trailing minus sign)kubectl label pods foo bar-