Kubectl is a command line interface for running commands against Kubernetes clusters.
Installing
The kubectl version has to 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 master.
Kubectl can be installed on Ubuntu, Debian, CentOS, RedHat, MacOS and Windows operating systems.
# Download the binary
curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl
# Manage the execution right to the binary
chmod +x ./kubectl
# Move the binary to the PATH
sudo mv ./kubectl /usr/local/bin/kubectl
For further information about Kubectl installation method, please refer to the Kubernetes documentation.
Completion
To easy manage the Kubernetes resources thanks to the command line Kubectl, the shell completion can be added to the shell profile to easily navigate in command line.
# Installing bash completion on macOS using homebrew## If running Bash 3.2 included with macOSbrewinstallbash-completion## or, if running Bash 4.1+brewinstallbash-completion@2## If kubectl is installed via homebrew, this should start working immediately.## If you've installed via other means, you may need add the completion to your completion directorykubectlcompletionbash> $(brew--prefix)/etc/bash_completion.d/kubectl# Installing bash completion on Linux## Load the kubectl completion code for bash into the current shellsource<(kubectlcompletionbash)## Write bash completion code to a file and source if from .bash_profilekubectlcompletionbash>~/.kube/completion.bash.incprintf"# Kubectl shell completionsource '$HOME/.kube/completion.bash.inc'">> $HOME/.bash_profilesource $HOME/.bash_profile# Load the kubectl completion code for zsh[1] into the current shellsource<(kubectlcompletionzsh)# Set the kubectl completion code for zsh[1] to autoload on startupkubectlcompletionzsh>"${fpath[1]}/_kubectl"
A project called kube-shell give an alternative to the configuration of the autocompletion of kubectl. Kube-shell integrate shell for working with the Kubernetes CLI. Under the hood kube-shell still calls kubectl. KuIt aims to provide ease-of-use of kubectl and increasing productivity.
Syntax
Kubectl is a powerful tool to manage each object on a Kubernetes cluster. The command has a simple and unique syntax to manage everything :
kubectl [command] [TYPE] [NAME] [flags]
command : specifies the operation that you want to perform on one or more resources (create, get, describe, delete)
type : specifies the resource type. Resource types are case-insensitive and you can specify the singular, plural, or abbreviated forms
name : specifies the name of the resource. Names are case-sensitive. If the name is omitted, details for all resources are displayed
flags : specifies optional flags.
Operations
The following table includes short descriptions and general syntax for all kubectl operations :
Resource Types
The following table includes a list of all the supported resource types and their abbreviated aliases :
Basic commands
Create
Create a resource from a file or from stdin.
# Create a pod using the data in pod.json.kubectlapply-f./pod.json# Create a pod based on the JSON passed into stdin.catpod.json|kubectlapply-f-# Edit the data in docker-registry.yaml in JSON using the v1 API format then create the resource using the edited data.kubectlapply-fdocker-registry.yaml--edit--output-version=v1-ojson
Delete
Delete resources by filenames, stdin, resources and names, or by resources and label selector.
# Delete a pod using the type and name specified in pod.json.kubectldelete-f./pod.json# Delete a pod based on the type and name in the JSON passed into stdin.catpod.json|kubectldelete-f-# Delete pods and services with same names "baz" and "foo"kubectldeletepod,servicebazfoo# Delete pods and services with label name=myLabel.kubectldeletepods,services-lname=myLabel# Delete a pod with minimal delaykubectldeletepodfoo--now# Force delete a pod on a dead nodekubectldeletepodfoo--grace-period=0--force# Delete all podskubectldeletepods--all
Edit
Edit a resource from the default editor.
# Edit the service named 'docker-registry':kubectleditsvc/docker-registry# Use an alternative editorKUBE_EDITOR="nano"kubectleditsvc/docker-registry# Edit the job 'myjob' in JSON using the v1 API format:kubectleditjob.v1.batch/myjob-ojson# Edit the deployment 'mydeployment' in YAML and save the modified config in its annotation:kubectleditdeployment/mydeployment-oyaml--save-config
Expose
Expose a resource as a new Kubernetes service.
# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.kubectlexposercnginx--port=80--target-port=8000# Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml", which serves on port 80 and connects to the containers on port 8000.
kubectlexpose-fnginx-controller.yaml--port=80--target-port=8000# Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"kubectlexposepodvalid-pod--port=444--name=frontend# Create a second service based on the above service, exposing the container port 8443 as port 443 with the name "nginx-https"
kubectlexposeservicenginx--port=443--target-port=8443--name=nginx-https# Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.kubectlexposercstreamer--port=4100--protocol=udp--name=video-stream# Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on port 8000.
kubectlexposersnginx--port=80--target-port=8000# Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.kubectlexposedeploymentnginx--port=80--target-port=8000
Get
Display one or many resources.
# List all pods.kubectlgetpods# List all pods in ps output format with more information (such as node name).kubectlgetpods-owide# List a single replication controller with specified NAME in ps output format.kubectlgetreplicationcontrollerweb# List a single pod in JSON output format.kubectlget-ojsonpod<pod-name># List a pod identified by type and name specified in "pod.yaml" in JSON output format.kubectlget-fpod.yaml-ojson# Return only the phase value of the specified pod.kubectlget-otemplatepod/<pod-name>--template={{.status.phase}}# List all replication controllers and services together in ps output format.kubectlgetrc,services# List one or more resources by their type and names.kubectlgetrc/webservice/frontendpods/<pod-name># List all resources with different types.kubectlgetall
Run
Create and run a particular image, possibly replicated.
# Start a single instance of nginx.kubectlrunnginx--image=nginx# Start a single instance of hazelcast and let the container expose port 5701 .kubectlrunhazelcast--image=hazelcast--port=5701# Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the container.
kubectlrunhazelcast--image=hazelcast--env="DNS_DOMAIN=cluster"--env="POD_NAMESPACE=default"# Start a single instance of hazelcast and set labels "app=hazelcast" and "env=prod" in the container.kubectlrunhazelcast--image=nginx--labels="app=hazelcast,env=prod"# Start a replicated instance of nginx.kubectlrunnginx--image=nginx--replicas=5# Dry run. Print the corresponding API objects without creating them.kubectlrunnginx--image=nginx--dry-run# Start a single instance of nginx, but overload the spec of the deployment with a partial set of values parsed from JSON.
kubectlrunnginx--image=nginx--overrides='{ "apiVersion": "v1", "spec": { ... } }'# Start a pod of busybox and keep it in the foreground, don't restart it if it exits.kubectlrun-i-tbusybox--image=busybox--restart=Never# Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.kubectlrunnginx--image=nginx--<arg1><arg2>...<argN># Start the nginx container using a different command and custom arguments.kubectlrunnginx--image=nginx--command--<cmd><arg1>...<argN># Start the perl container to compute π to 2000 places and print it out.kubectlrunpi--image=perl--restart=OnFailure--perl-Mbignum=bpi-wle'print bpi(2000)'# Start the cron job to compute π to 2000 places and print it out every 5 minutes.kubectlrunpi--schedule="0/5 * * * ?"--image=perl--restart=OnFailure--perl-Mbignum=bpi-wle'print bpi(2000)'
Set
Configure application resources.
# Update deployment 'registry' with a new environment variablekubectlsetenvdeployment/registrySTORAGE_DIR=/local# List the environment variables defined on a deployments 'sample-build'kubectlsetenvdeployment/sample-build--list# List the environment variables defined on all podskubectlsetenvpods--all--list# Output modified deployment in YAML, and does not alter the object on the serverkubectlsetenvdeployment/sample-buildSTORAGE_DIR=/data-oyaml# Update all containers in all replication controllers in the project to have ENV=prodkubectlsetenvrc--allENV=prod# Import environment from a secretkubectlsetenv--from=secret/mysecretdeployment/myapp# Import environment from a config map with a prefixkubectlsetenv--from=configmap/myconfigmap--prefix=MYSQL_deployment/myapp# Remove the environment variable ENV from container 'c1' in all deployment configskubectlsetenvdeployments--all--containers="c1"ENV-# Remove the environment variable ENV from a deployment definition on disk and# update the deployment config on the serverkubectlsetenv-fdeploy.jsonENV-# Set some of the local shell environment into a deployment config on the serverenv|grepRAILS_|kubectlsetenv-e-deployment/registry# Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.kubectlsetimagedeployment/nginxbusybox=busyboxnginx=nginx:1.9.1# Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'kubectlsetimagedeployments,rcnginx=nginx:1.9.1--all# Update image of all containers of daemonset abc to 'nginx:1.9.1'kubectlsetimagedaemonsetabc*=nginx:1.9.1# Print result (in yaml format) of updating nginx container image from local file, without hitting the serverkubectlsetimage-fpath/to/file.yamlnginx=nginx:1.9.1--local-oyaml# Set a deployments nginx container cpu limits to "200m" and memory to "512Mi"kubectlsetresourcesdeploymentnginx-c=nginx--limits=cpu=200m,memory=512Mi# Set the resource request and limits for all containers in nginxkubectlsetresourcesdeploymentnginx--limits=cpu=200m,memory=512Mi--requests=cpu=100m,memory=256Mi# Remove the resource requests for resources on containers in nginxkubectlsetresourcesdeploymentnginx--limits=cpu=0,memory=0--requests=cpu=0,memory=0# Print the result (in yaml format) of updating nginx container limits from a local, without hitting the serverkubectlsetresources-fpath/to/file.yaml--limits=cpu=200m,memory=512Mi--local-oyaml# Set Deployment nginx-deployment's ServiceAccount to serviceaccount1kubectlsetserviceaccountdeploymentnginx-deploymentserviceaccount1# Print the result (in yaml format) of updated nginx deployment with serviceaccount from local file, without hitting apiserver
kubectlsetsa-fnginx-deployment.yamlserviceaccount1--local--dry-run-oyaml
Deploy commands
Autoscale
Creates an autoscaler that automatically chooses and sets the number of pods that run in a kubernetes cluster.
# Auto scale a deployment "foo", with the number of pods between 2 and 10, no target CPU utilization specified so a default autoscaling policy will be used:
kubectlautoscaledeploymentfoo--min=2--max=10# Auto scale a replication controller "foo", with the number of pods between 1 and 5, target CPU utilization at 80%:kubectlautoscalercfoo--max=5--cpu-percent=80
Rollout
Manage the rollout of a resource.
# Rollback to the previous deploymentkubectlrolloutundodeployment/abc# Check the rollout status of a daemonsetkubectlrolloutstatusdaemonset/foo# View the rollout history of a deploymentkubectlrollouthistorydeployment/abc# View the details of daemonset revision 3kubectlrollouthistorydaemonset/abc--revision=3# Mark the nginx deployment as paused. Any current state of# the deployment will continue its function, new updates to the deployment will not# have an effect as long as the deployment is paused.kubectlrolloutpausedeployment/nginx# Resume an already paused deploymentkubectlrolloutresumedeployment/nginx# Watch the rollout status of a deploymentkubectlrolloutstatusdeployment/nginx# Rollback to the previous deploymentkubectlrolloutundodeployment/abc# Rollback to daemonset revision 3kubectlrolloutundodaemonset/abc--to-revision=3# Rollback to the previous deployment with dry-runkubectlrolloutundo--dry-run=truedeployment/abc
Scale
Set a new size for a Deployment, ReplicaSet, Replication Controller, or StatefulSet.
# Scale a replicaset named 'foo' to 3.kubectlscale--replicas=3rs/foo# Scale a resource identified by type and name specified in "foo.yaml" to 3.kubectlscale--replicas=3-ffoo.yaml# If the deployment named mysql's current size is 2, scale mysql to 3.kubectlscale--current-replicas=2--replicas=3deployment/mysql# Scale multiple replication controllers.kubectlscale--replicas=5rc/foorc/barrc/baz# Scale statefulset named 'web' to 3.kubectlscale--replicas=3statefulset/web
Cluster management commands
Cluster-info
Display addresses of the master and services with label kubernetes.io/cluster-service=true To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
# Print the address of the master and cluster serviceskubectlcluster-info
Cordon / Uncordon
Mark node as (un)schedulable.
# Mark node "foo" as unschedulable.kubectlcordonfoo# Mark node "foo" as schedulable.$kubectluncordonfoo
Drain
Drain node in preparation for maintenance.
# Drain node "foo", even if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet on it.
$kubectldrainfoo--force# As above, but abort if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet, and use a grace period of 15 minutes.
$kubectldrainfoo--grace-period=90
Taint
Update the taints on one or more nodes
# Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'.# If a taint with that key and effect already exists, its value is replaced as specified.kubectltaintnodesfoodedicated=special-user:NoSchedule# Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists.kubectltaintnodesfoodedicated:NoSchedule-# Remove from node 'foo' all the taints with key 'dedicated'kubectltaintnodesfoodedicated-# Add a taint with key 'dedicated' on nodes having label mylabel=Xkubectltaintnode-lmyLabel=Xdedicated=foo:PreferNoSchedule
Top
Display Resource (CPU/Memory/Storage) usage.
# Show metrics for all nodeskubectltopnode# Show metrics for a given nodekubectltopnodeNODE_NAME# Show metrics for all pods in the default namespacekubectltoppod# Show metrics for all pods in the given namespacekubectltoppod--namespace=NAMESPACE# Show metrics for a given pod and its containerskubectltoppodPOD_NAME--containers# Show metrics for the pods defined by label name=myLabelkubectltoppod-lname=myLabel
Troubleshooting and debugging commands
Describe
Show details of a specific resource or group of resources.
# Describe a nodekubectldescribenodeskubernetes-node-emt8.c.myproject.internal# Describe a podkubectldescribepods/<pod-name># Describe a pod identified by type and name in "pod.json"kubectldescribe-fpod.json# Describe all podskubectldescribepods# Describe pods by label name=myLabelkubectldescribepo-lname=myLabel# Describe all pods managed by the 'frontend' replication controller (rc-created pods# get the name of the rc as a prefix in the pod the name).kubectldescribepodsfrontend
Exec
Execute a command in a container.
# Get output from running 'date' from pod 123456-7890, using the first container by defaultkubectlexec123456-7890date# Get output from running 'date' in ruby-container from pod 123456-7890kubectlexec123456-7890-cruby-containerdate# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890# and sends stdout/stderr from 'bash' back to the clientkubectlexec123456-7890-cruby-container-i-t--bash-il# List contents of /usr from the first container of pod 123456-7890 and sort by modification time.# If the command you want to execute in the pod has any flags in common (e.g. -i),# you must use two dashes (--) to separate your command's flags/arguments.# Also note, do not surround your command and its flags/arguments with quotes# unless that is how you would execute it normally (i.e., do ls -t /usr, not "ls -t /usr").kubectlexec123456-7890-i-t--ls-t/usr
Logs
Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.
# Return snapshot logs from pod nginx with only one containerkubectllogsnginx# Return snapshot logs for the pods defined by label app=nginxkubectllogs-lapp=nginx# Return snapshot of previous terminated ruby container logs from pod web-1kubectllogs-p-crubyweb-1# Begin streaming the logs of the ruby container in pod web-1kubectllogs-f-crubyweb-1# Display only the most recent 20 lines of output in pod nginxkubectllogs--tail=20nginx# Show all logs from pod nginx written in the last hourkubectllogs--since=1hnginx# Return snapshot logs from first container of a job named hellokubectllogsjob/hello# Return snapshot logs from container nginx-1 of a deployment named nginxkubectllogsdeployment/nginx-cnginx-1
Proxy
Creates a proxy server or application-level gateway between localhost and the Kubernetes API Server. It also allows serving static content over specified 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.
# To proxy all of the kubernetes api and nothing else, use:$kubectlproxy--api-prefix=/# To proxy only part of the kubernetes api and also some static files:$kubectlproxy--www=/my/files--www-prefix=/static/--api-prefix=/api/# The above lets you 'curl localhost:8001/api/v1/pods'.# To proxy the entire kubernetes api at a different root, use:$kubectlproxy--api-prefix=/custom/# The above lets you 'curl localhost:8001/custom/api/v1/pods'# Run a proxy to kubernetes apiserver on port 8011, serving static content from ./local/www/kubectlproxy--port=8011--www=./local/www/# Run a proxy to kubernetes apiserver on an arbitrary local port.# The chosen port for the server will be output to stdout.kubectlproxy--port=0
Advanced commands
Apply
Apply a configuration to a resource by filename or stdin. The resource name must be specified. 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-config'.
# Apply the configuration in pod.json to a pod.kubectlapply-f./pod.json# Apply the JSON passed into stdin to a pod.catpod.json|kubectlapply-f-# Note: --prune is still in Alpha# Apply the configuration in manifest.yaml that matches label app=nginx and delete all the other resources that are not in the file and match label app=nginx.
kubectlapply--prune-fmanifest.yaml-lapp=nginx# Apply the configuration in manifest.yaml and delete all the other configmaps that are not in the file.kubectlapply--prune-fmanifest.yaml--all--prune-whitelist=core/v1/ConfigMap
Settings commands
Label
Update the labels on a resource.
# Update pod 'foo' with the label 'unhealthy' and the value 'true'.kubectllabelpodsfoounhealthy=true# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value.kubectllabel--overwritepodsfoostatus=unhealthy# Update all pods in the namespacekubectllabelpods--allstatus=unhealthy# Update a pod identified by the type and name in "pod.json"kubectllabel-fpod.jsonstatus=unhealthy# Update pod 'foo' only if the resource is unchanged from version 1.kubectllabelpodsfoostatus=unhealthy--resource-version=1# Update pod 'foo' by removing a label named 'bar' if it exists.# Does not require the --overwrite flag.kubectllabelpodsfoobar-
Other commands
Config
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context".
# Display the current-contextkubectlconfigcurrent-context# Delete the minikube clusterkubectlconfigdelete-clusterminikube# Delete the context for the minikube clusterkubectlconfigdelete-contextminikube# List the clusters kubectl knows aboutkubectlconfigget-clusters# List the context kubectl knows aboutkubectlconfigget-contexts# Rename the context 'old-name' to 'new-name' in your kubeconfig filekubectlconfigrename-contextold-namenew-name# Set only the server field on the e2e cluster entry without touching other values.kubectlconfigset-clustere2e--server=https://1.2.3.4# Embed certificate authority data for the e2e cluster entrykubectlconfigset-clustere2e--certificate-authority=~/.kube/e2e/kubernetes.ca.crt# Disable cert checking for the dev cluster entrykubectlconfigset-clustere2e--insecure-skip-tls-verify=true# Set the user field on the gce context entry without touching other valueskubectlconfigset-contextgce--user=cluster-admin# Use the context for the minikube clusterkubectlconfiguse-contextminikube
Version
Print the client and server version information for the current context.
# Print the client and server versions for the current contextkubectlversion
Customization
Kubectl has some limitation when we talk about management of multiple clusters with multiple context with multiple namespace. Sometimes it is more convenient to be faster in the command line.
Namespace reminder
Some tools have been developed to let the terminal remember the current namespace where the kubectl command has to be execute. Here are convenient helper tools :
kubensx a simple tool to easily switch between context, user and namespace in command line.
change-ns is a plugin that can be installed with the kubectl Krew package manager to remember the current namespace.
Manage aliases
Like each command line, the autocompletion sometimes is not enough to be faster as possible in the maintenance of the cluster objects.
Manage some Kubectl aliases can be a good alternative to the autocompletion. This Github project defined automatically some useful aliases to easily manage the Kubernetes objects.
Here are some example of aliases :
alias k=kubectlalias kg='kubectl get'alias kl='kubectl logs 'alias kx='kubectl exec -it'
Highlighter
Customize the bash or zsh prompt can be useful to easily get information without executing commands.
The project kube-ps1 is a script that adds the current Kubernetes context and namespace configured on kubectl to the Bash/Zsh prompt strings.
Here is an example of that useful tool :
Plugins
Google has developed an extension to the Kubectl command to easily manage his plugin as apt or yum can do on a Linux operating system.
Krew is a tool that makes it easy to use kubectl plugins. It helps to discover plugins, install and manage them on a machine. It is similar to tools like apt, dnf or brew.
Krew is only compatible with kubectl v1.12 or higher.
Krew can be installed on Linux, Mac and Windows, everything is explain on the Github web page.
Here are some example of using Kubectl to manage plugins :
# Show all pluginskubectlkrewsearch# Install a plugin named "change-ns"kubectlkrewinstallchange-ns# Use the pluginkubectlchange-ns# Upgrade installed pluginskubectlkrewupgrade# Uninstall a pluginkubectlkrewremovechange-ns
External documentation
To go further in the management of Kubectl, please refer to these documentations :