Kubectl CLI Reference

Kubectl CLI Reference

Kubectl is a command-line interface for managing Kubernetes clusters. The kubectl version must be within one minor version difference of the Kubernetes cluster. For example, a v1.2 client should work with v1.1, v1.2, and v1.3 masters.

Installation

Kubectl can be installed on Ubuntu, Debian, CentOS, and RedHat operating systems.

Ubuntu / Debian

1sudo apt-get update && sudo apt-get install -y apt-transport-https
2curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
3echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list
4sudo apt-get update
5sudo apt-get install -y kubectl

CentOS / RedHat

For more information about kubectl installation methods, refer to the Kubernetes documentation.

 1cat << EOF > /etc/yum.repos.d/kubernetes.repo
 2[kubernetes]
 3name=Kubernetes
 4baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
 5enabled=1
 6gpgcheck=1
 7repo_gpgcheck=1
 8gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
 9EOF
10yum install -y kubectl

Shell Completion

To easily manage Kubernetes resources via the command line, you can enable shell completion by adding the completion script to your shell profile.

Bash (Linux/macOS)

If running Bash 3.2 (included with macOS):

1brew install bash-completion

For Bash 4.1+:

1brew install bash-completion@2

If kubectl was installed via Homebrew, bash completion should work immediately. Otherwise, add the following to your bash profile:

1kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl

On Linux, load kubectl completion for bash in the current shell:

1source <(kubectl completion bash)

To persist this across sessions, add the completion script to your .bash_profile:

1kubectl completion bash > ~/.kube/completion.bash.inc
2printf "
3# Kubectl shell completion
4source '$HOME/.kube/completion.bash.inc'
5" >> $HOME/.bash_profile
6source $HOME/.bash_profile

Zsh

To load kubectl completion for zsh into the current shell:

1source <(kubectl completion zsh)

Syntax

Kubectl uses a simple syntax to manage objects in a Kubernetes cluster:

1kubectl [command] [TYPE] [NAME] [flags]
  • command: Specifies the operation you want to perform (e.g., create, get, describe, delete).
  • TYPE: The resource type (case-insensitive; supports singular, plural, or abbreviation).
  • NAME: The resource name (case-sensitive). If omitted, details for all resources are shown.
  • flags: Optional flags to modify the command's behavior.

Useful Basic Commands

Create

Create resources from a file or stdin.

1# Create a pod using the configuration in pod.json
2kubectl create -f ./pod.json
3
4# Create all resources in a folder
5kubectl create -f <folder_name>

Delete

Delete resources by filenames, stdin, resource name, or label selector.

1# Delete a pod using the configuration in pod.json
2kubectl delete -f ./pod.json
3
4# Delete a pod with the specified name
5kubectl delete pod <pod_name>
6
7# Delete all pods
8kubectl delete pods --all

Edit

Edit a resource in the default editor.

1# Edit the service named 'docker-registry'
2kubectl edit svc/docker-registry

Expose

Expose a resource as a new Kubernetes service.

1# Expose a replication controller nginx as a service on port 80
2kubectl expose rc nginx --port=80 --target-port=8000

Get

Display information about one or more resources.

1# List all pods
2kubectl get pods
3
4# List pods with additional details (such as node name)
5kubectl get pods -o wide
6
7# Get a single pod in JSON format
8kubectl get pod <pod-name> -o json

Run

Create and run a particular image in the cluster.

1# Run a single instance of nginx
2kubectl run nginx --image=nginx
3
4# Run a replicated instance of nginx
5kubectl run nginx --image=nginx --replicas=5

Set

Configure application resources.

1# Update deployment 'registry' with a new environment variable
2kubectl set env deployment/registry STORAGE_DIR=/local
3
4# Set a deployment's nginx container image to 'nginx:1.9.1'
5kubectl set image deployment/nginx nginx=nginx:1.9.1

Autoscale

Automatically scale the number of pods in a deployment based on resource usage.

1kubectl autoscale deployment foo --min=2 --max=10

Rollout

Manage the rollout of a deployment.

1# Rollback to the previous deployment
2kubectl rollout undo deployment/abc

Scale

Set a new size for a Deployment, ReplicaSet, or StatefulSet.

1# Scale a deployment named 'nginx' to 3 replicas
2kubectl scale --replicas=3 deployment/nginx

Useful Cluster Management Commands

Cluster Info

Display the addresses of the master and Kubernetes services.

1kubectl cluster-info

Cordon / Uncordon

Mark a node as schedulable or unschedulable.

1# Mark node "foo" as unschedulable
2kubectl cordon foo
3
4# Mark node "foo" as schedulable
5kubectl uncordon foo

Drain

Prepare a node for maintenance by evicting all its pods.

Taint

Apply taints to a node.

Update the taints on one or more nodes.

1# Drain node "foo", even if there are pods not managed by a ReplicationController, R
2$ kubectl drain foo --force
3
4# As above, but abort if there are pods not managed by a ReplicationController, Repl
5$ kubectl drain foo --grace-period = 90
6
7#Drain node by ignoring Deamonsets
8kubectl drain <node_name> --ignore-daemonsets

Top

Display Resource (CPU/Memory/Storage) usage.

 1# Show metrics for all nodes
 2kubectl top node
 3
 4# Show metrics for a given node
 5kubectl top node NODE_NAME
 6
 7# Show metrics for all pods in the default namespace
 8kubectl top pod
 9
10# Show metrics for all pods in the given namespace
11kubectl top pod --namespace = NAMESPACE
12
13# Show metrics for a given pod and its containers
14kubectl top pod POD_NAME --containers
15
16# Show metrics for the pods defined by label name=myLabel
17kubectl top pod -l name = myLabel

Useful troubleshooting and debugging commands

Describe

Show details of a specic resource or group of resources.

 1# Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and e
 2# If a taint with that key and effect already exists, its value is replaced as speci
 3kubectl taint nodes foo dedicated = special-user:NoSchedule
 4
 5# Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if o
 6kubectl taint nodes foo dedicated:NoSchedule-
 7
 8# Remove from node 'foo' all the taints with key 'dedicated'
 9kubectl taint nodes foo dedicated-
10
11# Add a taint with key 'dedicated' on nodes having label mylabel=X
12kubectl taint node -l myLabel = X dedicated = foo:PreferNoSchedule

Exec

Execute a command in a container.

Logs

container name is optional.

 1# Describe a node
 2kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
 3
 4# Describe a pod
 5kubectl describe pods/<pod-name>
 6
 7# Describe a pod identified by type and name in "pod.json"
 8kubectl describe -f pod.json
 9
10# Describe all pods
11kubectl describe pods
12
13# Describe pods by label name=myLabel
14kubectl describe po -l name = myLabel
15
16# Describe all pods managed by the 'frontend' replication controller (rc-created pod
17# get the name of the rc as a prefix in the pod the name).
18kubectl describe pods frontend
19
20# Get output from running 'date' from pod 123456-7890, using the first container by
21kubectl exec 123456-7890 date
22
23# Get output from running 'date' in ruby-container from pod 123456-
24kubectl exec 123456-7890 -c ruby-container date
25
26# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 1234
27# and sends stdout/stderr from 'bash' back to the client
28kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il
 1# Return snapshot logs from pod nginx with only one container
 2kubectl logs nginx
 3
 4# Return snapshot logs for the pods defined by label app=nginx
 5kubectl logs -lapp = nginx
 6
 7# Return snapshot of previous terminated ruby container logs from pod web-
 8kubectl logs -p -c ruby web-
 9
10# Begin streaming the logs of the ruby container in pod web-
11kubectl logs -f -c ruby web-
12
13# Display only the most recent 20 lines of output in pod nginx
14kubectl logs --tail = 20 nginx
15
16# Show all logs from pod nginx written in the last hour
17kubectl logs --since = 1h nginx
18
19# Return snapshot logs from first container of a job named hello
20kubectl logs job/hello
21
22# Return snapshot logs from container nginx-1 of a deployment named nginx
23kubectl logs deployment/nginx -c nginx-

Proxy

Creates a proxy server or application-level gateway between localhost and the Kubernetes API

Server. It also allows serving static content over specied HTTP path. All incoming data enters

through one port and gets forwarded to the remote kubernetes API Server port, except for the path

matching the static content path.

 1# To proxy all of the kubernetes api and nothing else, use:
 2$ kubectl proxy --api-prefix = /
 3
 4# To proxy only part of the kubernetes api and also some static files:
 5$ kubectl proxy --www = /my/files --www-prefix = /static/ --api-prefix = /api/
 6# The above lets you 'curl localhost:8001/api/v1/pods'.
 7
 8# To proxy the entire kubernetes api at a different root, use:
 9$ kubectl proxy --api-prefix = /custom/
10# The above lets you 'curl localhost:8001/custom/api/v1/pods'
11
12# Run a proxy to kubernetes apiserver on port 8011, serving static content from ./lo
13kubectl proxy --port = 8011 --www = ./local/www/

Useful advanced commands

Apply

Apply a conguration to a resource by lename or stdin. The resource name must be specied. This

resource will be created if it doesn’t exist yet. To use ‘apply’, always create the resource initially with

either ‘apply’ or ‘create –save-cong’.

Useful settings commands

label

Update the labels on a resource.

 1# Run a proxy to kubernetes apiserver on an arbitrary local port.
 2# The chosen port for the server will be output to stdout.
 3kubectl proxy --port = 0
 4
 5# Apply the configuration in pod.json to a pod.
 6kubectl apply -f ./pod.json
 7
 8# Apply the JSON passed into stdin to a pod.
 9cat pod.json | kubectl apply -f -
10
11# Note: --prune is still in Alpha
12# Apply the configuration in manifest.yaml that matches label app=nginx and delete a
13kubectl apply --prune -f manifest.yaml -l app = nginx
14
15# Apply the configuration in manifest.yaml and delete all the other configmaps that
16kubectl apply --prune -f manifest.yaml --all --prune-whitelist = core/v1/ConfigMap
17
18# Update pod 'foo' with the label 'unhealthy' and the value 'true'.
19kubectl label pods foo unhealthy = true
20
21# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting an
22kubectl label --overwrite pods foo status = unhealthy
23
24# Update all pods in the namespace
25kubectl label pods --all status = unhealthy
26
27# Update a pod identified by the type and name in "pod.json"

Useful other commands

Config

Modify kubeconfig files

 1kubectl label -f pod.json status = unhealthy
 2
 3# Update pod 'foo' only if the resource is unchanged from version 1.
 4kubectl label pods foo status = unhealthy --resource-version = 1
 5
 6# Update pod 'foo' by removing a label named 'bar' if it exists.
 7# Does not require the --overwrite flag.
 8kubectl label pods foo bar-
 9
10# Display the current-context
11kubectl config current-context
12
13# Delete the minikube cluster
14kubectl config delete-cluster minikube
15
16# Delete the context for the minikube cluster
17kubectl config delete-context minikube
18
19# List the clusters kubectl knows about
20kubectl config get-clusters
21
22# List the context kubectl knows about
23kubectl config get-contexts
24
25# Rename the context 'old-name' to 'new-name' in your kubeconfig file
26kubectl config rename-context old-name new-name
27
28# Set only the server field on the e2e cluster entry without touching other values.
29kubectl config set-cluster e2e --server = https://1.2.3.
30
31# Embed certificate authority data for the e2e cluster entry
32kubectl config set-cluster e2e --certificate-authority = ~/.kube/e2e/kubernetes.ca.crt
33
34# Disable cert checking for the dev cluster entry
35kubectl config set-cluster e2e --insecure-skip-tls-verify = true
36
37# Set the user field on the gce context entry without touching other values
38kubectl config set-context gce --user = cluster-admin