Kubectl Commands
Kubectl Commands
This section contains the most basic commands for getting a workload
running on your cluster.
Once your workloads are running, you can use the commands in the WORKING
WITH APPS section to inspect them.
create
Create a pod using the data in pod.json
kubectl create -f ./pod.json
Usage
$ kubectl create -f FILENAME
Flags
Shorth Defau
Name and lt Usage
clusterrole
Create a cluster role named "pod-reader" that allows user to perform "get",
"watch" and "list" on pods
kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods
Usage
$ kubectl create clusterrole NAME --verb=verb --resource=resource.group [--
resource-name=resourcename] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
templatefile|jsonpath|jsonpath-as-
json|jsonpath-file.
clusterrolebinding
Create a cluster role binding for user1, user2, and group1 using the
cluster-admin cluster role
kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin
--user=user1 --user=user2 --group=group1
Usage
$ kubectl create clusterrolebinding NAME --clusterrole=NAME [--
user=username] [--group=groupname] [--
serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
future.
configmap
Create a new config map named my-config based on folder bar
kubectl create configmap my-config --from-file=path/to/bar
Create a new config map named my-config with specified keys instead of file
basenames on disk
kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt
--from-file=key2=/path/to/bar/file2.txt
Create a new config map named my-config with key1=config1 and key2=config2
kubectl create configmap my-config --from-literal=key1=config1 --from-
literal=key2=config2
Create a new config map named my-config from the key=value pairs in the
file
kubectl create configmap my-config --from-file=path/to/bar
Usage
$ kubectl create configmap NAME [--from-file=[key=]source] [--from-
literal=key1=value1] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
cronjob
Create a cron job
kubectl create cronjob my-job --image=busybox --schedule="*/1 * * * *"
Usage
$ kubectl create cronjob NAME --image=image --schedule='0/5 * * * ?' --
[COMMAND] [args...]
Flags
Shorth Defau
Name and lt Usage
deployment
Create a deployment named my-dep that runs the busybox image
kubectl create deployment my-dep --image=busybox
Create a deployment named my-dep that runs the nginx image with 3 replicas
kubectl create deployment my-dep --image=nginx --replicas=3
Create a deployment named my-dep that runs the busybox image and expose
port 5701
kubectl create deployment my-dep --image=busybox --port=5701
Flags
Shorth Defau
Name and lt Usage
ingress
Create a single ingress called 'simple' that directs requests to
foo.com/bar to svc # svc1:8080 with a tls secret "my-cert"
kubectl create ingress simple --rule="foo.com/bar=svc1:8080,tls=my-cert"
Create an ingress with TLS enabled using the default ingress certificate
and different path types
kubectl create ingress ingtls --class=default \
--rule="foo.com/=svc:https,tls" \
--rule="foo.com/path/subpath*=othersvc:8080"
Create an ingress with TLS enabled using a specific secret and pathType as
Prefix
kubectl create ingress ingsecret --class=default \
--rule="foo.com/*=svc:8080,tls=secret1"
Usage
$ kubectl create ingress NAME --rule=host/path=service:port[,tls[=secret]]
Flags
Shorth Defau
Name and lt Usage
Usage
$ kubectl create job NAME --image=image [--from=cronjob/name] -- [COMMAND]
[args...]
Flags
Shorth Defau
Name and lt Usage
namespace
Create a new namespace named my-namespace
kubectl create namespace my-namespace
Usage
$ kubectl create namespace NAME [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
Create a pod disruption budget named my-pdb that will select all pods with
the app=nginx label # and require at least half of the pods selected to be
available at any point in time
kubectl create pdb my-pdb --selector=app=nginx --min-available=50%
Create a pod disruption budget with the specified name, selector, and
desired minimum available pods.
Usage
$ kubectl create poddisruptionbudget NAME --selector=SELECTOR --min-
available=N [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
priorityclass
Create a priority class named high-priority
kubectl create priorityclass high-priority --value=1000 --description="high
priority"
Create a priority class named default-priority that is considered as the
global default priority
kubectl create priorityclass default-priority --value=1000 --global-
default=true --description="default priority"
Create a priority class named high-priority that cannot preempt pods with
lower priority
kubectl create priorityclass high-priority --value=1000 --description="high
priority" --preemption-policy="Never"
Create a priority class with the specified name, value, globalDefault and
description.
Usage
$ kubectl create priorityclass NAME --value=VALUE --global-default=BOOL [--
dry-run=server|client|none]
Flags
Short
Name hand Default Usage
quota
Create a new resource quota named my-quota
kubectl create quota my-quota --
hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequo
tas=1,secrets=5,persistentvolumeclaims=10
Create a new resource quota named best-effort
kubectl create quota best-effort --hard=pods=100 --scopes=BestEffort
Create a resource quota with the specified name, hard limits, and optional
scopes.
Usage
$ kubectl create quota NAME [--hard=key1=value1,key2=value2] [--
scopes=Scope1,Scope2] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
role
Create a role named "pod-reader" that allows user to perform "get", "watch"
and "list" on pods
kubectl create role pod-reader --verb=get --verb=list --verb=watch --
resource=pods
Usage
$ kubectl create role NAME --verb=verb
--resource=resource.group/subresource [--resource-name=resourcename] [--
dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
rolebinding
Create a role binding for user1, user2, and group1 using the admin cluster
role
kubectl create rolebinding admin --clusterrole=admin --user=user1 --
user=user2 --group=group1
Usage
$ kubectl create rolebinding NAME --clusterrole=NAME|--role=NAME [--
user=username] [--group=groupname] [--
serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
secret
Create a secret using specified subcommand.
Usage
$ kubectl create secret
secret docker-registry
If you don't already have a .dockercfg file, you can create a dockercfg
secret directly by using:
kubectl create secret docker-registry my-secret --docker-
server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-
password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
Usage
$ kubectl create secret docker-registry NAME --docker-username=user --
docker-password=password --docker-email=email [--docker-server=string] [--
from-file=[key=]source] [--dry-run=server|client|none]
Flags
Short
Name hand Default Usage
the resource.
secret generic
Create a new secret named my-secret with keys for each file in folder bar
kubectl create secret generic my-secret --from-file=path/to/bar
Create a new secret named my-secret with specified keys instead of names on
disk
kubectl create secret generic my-secret --from-
file=ssh-privatekey=path/to/id_rsa --from-
file=ssh-publickey=path/to/id_rsa.pub
Usage
$ kubectl create generic NAME [--type=string] [--from-file=[key=]source]
[--from-literal=key1=value1] [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
jsonpath-file.
secret tls
Create a new TLS secret named tls-secret with the given key pair
kubectl create secret tls tls-secret --cert=path/to/tls.cert --
key=path/to/tls.key
Usage
$ kubectl create secret tls NAME --cert=path/to/cert/file
--key=path/to/key/file [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
service
Create a service using a specified subcommand.
Usage
$ kubectl create service
service clusterip
Create a new ClusterIP service named my-cs
kubectl create service clusterip my-cs --tcp=5678:8080
Usage
$ kubectl create service clusterip NAME [--tcp=<port>:<targetPort>] [--dry-
run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
templates [http://golang.org/pkg/text/te
mplate/#pkg-overview].
service externalname
Create a new ExternalName service named my-ns
kubectl create service externalname my-ns --external-name bar.com
Usage
$ kubectl create service externalname NAME --external-name external.name
[--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
service loadbalancer
Create a new LoadBalancer service named my-lbs
kubectl create service loadbalancer my-lbs --tcp=5678:8080
Usage
$ kubectl create service loadbalancer NAME [--tcp=port:targetPort] [--dry-
run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
'<port>:<targetPort>'.
service nodeport
Create a new NodePort service named my-ns
kubectl create service nodeport my-ns --tcp=5678:8080
Usage
$ kubectl create service nodeport NAME [--tcp=port:targetPort] [--dry-
run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
the resource.
Usage
$ kubectl create serviceaccount NAME [--dry-run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
get
List all pods in ps output format
kubectl get pods
List all pods in ps output format with more information (such as node name)
kubectl get pods -o wide
List deployments in JSON output format, in the "v1" version of the "apps"
API group
kubectl get deployments.v1.apps -o json
Usage
$ kubectl get [(-o|--output=)json|yaml|name|go-template|go-template-file|
template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|custom-
columns|custom-columns-file|wide] (TYPE[.VERSION][.GROUP] [NAME | -l label]
| TYPE[.VERSION][.GROUP]/NAME ...) [flags]
Flags
Short Defa
Name hand ult Usage
run
Start a nginx pod
kubectl run nginx --image=nginx
Start a hazelcast pod and let the container expose port 5701
kubectl run hazelcast --image=hazelcast/hazelcast --port=5701
Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the
container
kubectl run hazelcast --image=hazelcast/hazelcast --
labels="app=hazelcast,env=prod"
Dry run; print the corresponding API objects without creating them
kubectl run nginx --image=nginx --dry-run=client
Start a nginx pod, but overload the spec with a partial set of values
parsed from JSON
kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec":
{ ... } }'
Start the nginx pod using the default command, but use custom arguments
(arg1 .. argN) for that command
kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>
Start the nginx pod using a different command and custom arguments
kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
Usage
$ kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-
run=server|client] [--overrides=inline-json] [--command] -- [COMMAND]
[args...]
Flags
Shorth Defau
Name and lt Usage
deletion).
Create a service for a pod valid-pod, which serves on port 444 with the
name "frontend"
kubectl expose pod valid-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"
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-
https
Create a service for a replicated nginx using replica set, which serves on
port 80 and connects to the containers on port 8000
kubectl expose rs nginx --port=80 --target-port=8000
Usage
$ kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|
UDP|SCTP] [--target-port=number-or-name] [--name=name] [--external-
ip=external-ip-of-service] [--type=type]
Flags
Shorth Defau
Name and lt Usage
Delete a pod based on the type and name in the JSON passed into stdin
cat pod.json | kubectl delete -f -
Delete pods and services with same names "baz" and "foo"
kubectl delete pod,service baz foo
Usage
$ kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label |
--all)])
Flags
delete.
APP MANAGEMENT
This section contains commands for creating, updating, deleting, and
viewing your workloads in a Kubernetes cluster.
apply
Apply the configuration in pod.json to a pod
kubectl apply -f ./pod.json
Apply the configuration in manifest.yaml and delete all the other config
maps that are not in the file
kubectl apply --prune -f manifest.yaml --all --
prune-whitelist=core/v1/ConfigMap
Apply a configuration to a resource by file name 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'.
JSON and YAML formats are accepted.
Alpha Disclaimer: the --prune functionality is not yet complete. Do not use
unless you are aware of what the current state is.
See https://issues.k8s.io/34274.
Usage
$ kubectl apply (-f FILENAME | -k DIRECTORY)
Flags
Shorth Defau
Name and lt Usage
edit-last-applied
Edit the last-applied-configuration annotations by type/name in YAML
kubectl apply edit-last-applied deployment/nginx
Usage
$ kubectl apply edit-last-applied (RESOURCE/NAME | -f FILENAME)
Flags
Shorth Defau
Name and lt Usage
golang
templates [http://golang.org/pkg/text/te
mplate/#pkg-overview].
set-last-applied
Set the last-applied-configuration of a resource to match the contents of a
file
kubectl apply set-last-applied -f deploy.yaml
Usage
$ kubectl apply set-last-applied -f FILENAME
Flags
Shorth Defau
Name and lt Usage
view-last-applied
View the last-applied-configuration annotations by type/name in YAML
kubectl apply view-last-applied deployment/nginx
Usage
$ kubectl apply view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f
FILENAME)
Flags
annotate
Update pod 'foo' with the annotation 'description' and the value 'my
frontend' # If the same annotation is set multiple times, only the last
value will be applied
kubectl annotate pods foo description='my frontend'
Update pod 'foo' with the annotation 'description' and the value 'my
frontend running nginx', overwriting any existing value
kubectl annotate --overwrite pods foo description='my frontend running
nginx'
Usage
$ kubectl annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ...
KEY_N=VAL_N [--resource-version=version]
Flags
Shorth Defau
Name and lt Usage
es all namespaces.
templatefile|jsonpath|jsonpath-as-json|
jsonpath-file.
Auto scale a replication controller "foo", with the number of pods between
1 and 5, target CPU utilization at 80%
kubectl autoscale rc foo --max=5 --cpu-percent=80
Usage
$ kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS]
--max=MAXPODS [--cpu-percent=CPU]
Flags
Shorth Defau
Name and lt Usage
debug
Create an interactive debugging session in pod mypod and immediately attach
to it. # (requires the EphemeralContainers feature to be enabled in the
cluster)
kubectl debug mypod -it --image=busybox
Usage
$ kubectl debug (POD | TYPE[[.VERSION].GROUP]/NAME) [ -- COMMAND
[args...] ]
Flags
diff
Diff resources included in pod.json
kubectl diff -f pod.json
Usage
$ kubectl diff -f FILENAME
Flags
edit
Edit the service named 'docker-registry'
kubectl edit svc/docker-registry
Edit the deployment 'mydeployment' in YAML and save the modified config in
its annotation
kubectl edit deployment/mydeployment -o yaml --save-config
Usage
$ kubectl edit (RESOURCE/NAME | -f FILENAME)
Flags
Shorth Defau
Name and lt Usage
kustomize
Build the current working directory
kubectl kustomize
Usage
$ kubectl kustomize DIR
Flags
Shorthan
Name d Default Usage
generator.
label
Update pod 'foo' with the label 'unhealthy' and the value 'true'
kubectl label pods foo unhealthy=true
Update pod 'foo' with the label 'status' and the value 'unhealthy',
overwriting any existing value
kubectl label --overwrite pods foo status=unhealthy
Update pod 'foo' by removing a label named 'bar' if it exists # Does not
require the --overwrite flag
kubectl label pods foo bar-
A label key and value must begin with a letter or number, and may
contain letters, numbers, hyphens, dots, and underscores, up to 63
characters each.
Optionally, the key can begin with a DNS subdomain prefix and a
single '/', like example.com/my-app.
If --overwrite is true, then existing labels can be overwritten,
otherwise attempting to overwrite a label will result in an error.
If --resource-version is specified, then updates will use this
resource version, otherwise the existing resource-version will be
used.
Usage
$ kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ...
KEY_N=VAL_N [--resource-version=version]
Flags
Shorth Defau
Name and lt Usage
patch
Partially update a node using a strategic merge patch, specifying the patch
as JSON
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
Partially update a node using a strategic merge patch, specifying the patch
as YAML
kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'
Usage
$ kubectl patch (-f FILENAME | TYPE NAME) [-p PATCH|--patch-file FILE]
Flags
Shorth Defau
Name and lt Usage
replace
Replace a pod using the data in pod.json
kubectl replace -f ./pod.json
Usage
$ kubectl replace -f FILENAME
Flags
Shorth Defau
Name and lt Usage
rollout
Rollback to the previous deployment
kubectl rollout undo deployment/abc
deployments
daemonsets
statefulsets
Usage
$ kubectl rollout SUBCOMMAND
history
View the rollout history of a deployment
kubectl rollout history deployment/abc
Usage
$ kubectl rollout history (TYPE NAME | TYPE/NAME) [flags]
Flags
Shorth Defau
Name and lt Usage
Usage
$ kubectl rollout pause RESOURCE
Flags
Shorth Defau
Name and lt Usage
restart
Restart a deployment
kubectl rollout restart deployment/nginx
Restart a resource.
Resource rollout will be restarted.
Usage
$ kubectl rollout restart RESOURCE
Flags
Shorth Defau
Name and lt Usage
resume
Resume an already paused deployment
kubectl rollout resume deployment/nginx
Usage
$ kubectl rollout resume RESOURCE
Flags
Shorth Defau
Name and lt Usage
status
Watch the rollout status of a deployment
kubectl rollout status deployment/nginx
Usage
$ kubectl rollout status (TYPE NAME | TYPE/NAME) [flags]
Flags
undo
Roll back to the previous deployment
kubectl rollout undo deployment/abc
Usage
$ kubectl rollout undo (TYPE NAME | TYPE/NAME) [flags]
Flags
Shorth Defau
Name and lt Usage
scale
Scale a replica set named 'foo' to 3
kubectl scale --replicas=3 rs/foo
Usage
$ kubectl scale [--resource-version=version] [--current-replicas=count] --
replicas=COUNT (-f FILENAME | TYPE NAME)
Flags
Shorth Defau
Name and lt Usage
set
Configure application resources.
These commands help you make changes to existing application resources.
Usage
$ kubectl set SUBCOMMAND
env
Update deployment 'registry' with a new environment variable
kubectl set env deployment/registry STORAGE_DIR=/local
Output modified deployment in YAML, and does not alter the object on the
server
kubectl set env deployment/sample-build STORAGE_DIR=/data -o yaml
Remove the environment variable ENV from container 'c1' in all deployment
configs
kubectl set env deployments --all --containers="c1" ENV-
Set some of the local shell environment into a deployment config on the
server
env | grep RAILS_ | kubectl set env -e - deployment/registry
Usage
$ kubectl set env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N
Flags
Shorth Defau
Name and lt Usage
image
Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox
container image to 'busybox'
kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
Print result (in yaml format) of updating nginx container image from local
file, without hitting the server
kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml
Usage
$ kubectl set image (-f FILENAME | TYPE NAME)
CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
Flags
Shorth Defau
Name and lt Usage
resources
Set a deployments nginx container cpu limits to "200m" and memory to
"512Mi"
kubectl set resources deployment nginx -c=nginx --
limits=cpu=200m,memory=512Mi
Set the resource request and limits for all containers in nginx
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --
requests=cpu=100m,memory=256Mi
Print the result (in yaml format) of updating nginx container limits from a
local, without hitting the server
kubectl set resources -f path/to/file.yaml --limits=cpu=200m,memory=512Mi
--local -o yaml
Specify compute resource requirements (CPU, memory) for any resource that
defines a pod template. If a pod is successfully scheduled, it is
guaranteed the amount of resource requested, but may burst up to its
specified limits.
For each compute resource, if a limit is specified and a request is
omitted, the request will default to the limit.
Possible resources include (case insensitive): Use "kubectl api-resources"
for a complete list of supported resources..
Usage
$ kubectl set resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --
requests=REQUESTS]
Flags
Shorth Defau
Name and lt Usage
selector
Set the labels and selector before creating a deployment/service pair
kubectl create service clusterip my-svc --clusterip="None" -o yaml --dry-
run=client | kubectl set selector --local -f - 'environment=qa' -o yaml |
kubectl create -f -
kubectl create deployment my-dep -o yaml --dry-run=client | kubectl label
--local -f - environment=qa -o yaml | kubectl create -f -
Set the selector on a resource. Note that the new selector will overwrite
the old selector if the resource had one prior to the invocation of 'set
selector'.
A selector must begin with a letter or number, and may contain letters,
numbers, hyphens, dots, and underscores, up to 63 characters. If --
resource-version is specified, then updates will use this resource version,
otherwise the existing resource-version will be used. Note: currently
selectors can only be set on Service objects.
Usage
$ kubectl set selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-
version=version]
Flags
Shorth Defau
Name and lt Usage
serviceaccount
Set deployment nginx-deployment's service account to serviceaccount1
kubectl set serviceaccount deployment nginx-deployment serviceaccount1
Print the result (in YAML format) of updated nginx deployment with the
service account from local file, without hitting the API server
kubectl set sa -f nginx-deployment.yaml serviceaccount1 --local --dry-
run=client -o yaml
Usage
$ kubectl set serviceaccount (-f FILENAME | TYPE NAME) SERVICE_ACCOUNT
Flags
Shorth Defau
Name and lt Usage
subject
Update a cluster role binding for serviceaccount1
kubectl set subject clusterrolebinding admin --
serviceaccount=namespace:serviceaccount1
Print the result (in YAML format) of updating rolebinding subjects from a
local, without hitting the server
kubectl create rolebinding admin --role=admin --user=admin -o yaml --dry-
run=client | kubectl set subject --local -f - --user=foo -o yaml
Usage
$ kubectl set subject (-f FILENAME | TYPE NAME) [--user=username] [--
group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-
run=server|client|none]
Flags
Shorth Defau
Name and lt Usage
wait
Wait for the pod "busybox1" to contain the status condition of type "Ready"
kubectl wait --for=condition=Ready pod/busybox1
The default value of status condition is true; you can set it to false
kubectl wait --for=condition=Ready=false pod/busybox1
Wait for the pod "busybox1" to be deleted, with a timeout of 60s, after
having issued the "delete" command
kubectl delete pod/busybox1
kubectl wait --for=delete pod/busybox1 --timeout=60s
Usage
$ kubectl wait ([-f FILENAME] | resource.group/resource.name |
resource.group [(-l label | --all)]) [--for=delete|--for
condition=available]
Flags
Shorth Defau
Name and lt Usage
templatefile|jsonpath|jsonpath-as-json|
jsonpath-file.
logs will print the logs from the specified pod + container.
exec can be used to get an interactive shell on a pod + container.
describe will print debug information about the given resource.
attach
Get output from running pod mypod; use the 'kubectl.kubernetes.io/default-
container' annotation # for selecting the container to be attached or the
first container in the pod will be chosen
kubectl attach mypod
Get output from the first pod of a replica set named nginx
kubectl attach rs/nginx
Usage
$ kubectl attach (POD | TYPE/NAME) -c CONTAINER
Flags
Usage
$ kubectl auth
can-i
Check to see if I can create pods in any namespace
kubectl auth can-i create pods --all-namespaces
Check to see if I can get the job named "bar" in namespace "foo"
kubectl auth can-i list jobs.batch/bar -n foo
Usage
$ kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL]
Flags
Name Shorthand Default Usage
reconcile
Reconcile RBAC resources from a file
kubectl auth reconcile -f my-rbac-rules.yaml
Reconciles rules for RBAC role, role binding, cluster role, and cluster
role binding objects.
Missing objects are created, and the containing namespace is created for
namespaced objects, if required.
Existing roles are updated to include the permissions in the input objects,
and remove extra permissions if --remove-extra-permissions is specified.
Existing bindings are updated to include the subjects in the input objects,
and remove extra subjects if --remove-extra-subjects is specified.
This is preferred to 'apply' for RBAC resources so that semantically-aware
merging of rules and subjects is done.
Usage
$ kubectl auth reconcile -f FILENAME
Flags
Shorth Defau
Name and lt Usage
cp
!!!Important Note!!! # Requires that the 'tar' binary is present in your
container # image. If 'tar' is not present, 'kubectl cp' will fail. # # For
advanced use cases, such as symlinks, wildcard expansion or # file mode
preservation, consider using 'kubectl exec'. # Copy /tmp/foo local file
to /tmp/bar in a remote pod in namespace
tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar
xf - -C /tmp/bar
Usage
$ kubectl cp <file-spec-src> <file-spec-dest>
Flags
Name Shorthand Default Usage
describe
Describe a node
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
Describe a pod
kubectl describe pods/nginx
Usage
$ kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] |
TYPE/NAME)
Flags
Get output from running the 'date' command in ruby-container from pod mypod
kubectl exec mypod -c ruby-container -- date
List contents of /usr from the first container of pod mypod 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")
kubectl exec mypod -i -t -- ls -t /usr
Get output from running 'date' command from the first pod of the deployment
mydeployment, using the first container by default
kubectl exec deploy/mydeployment -- date
Get output from running 'date' command from the first pod of the service
myservice, using the first container by default
kubectl exec svc/myservice -- date
Usage
$ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND
[args...]
Flags
logs
Return snapshot logs from pod nginx with only one container
kubectl logs nginx
Return snapshot logs from all containers in pods defined by label app=nginx
kubectl logs -l app=nginx --all-containers=true
Return snapshot of previous terminated ruby container logs from pod web-1
kubectl logs -p -c ruby web-1
Begin streaming the logs from all containers in pods defined by label
app=nginx
kubectl logs -f -l app=nginx --all-containers=true
Print the logs for a container in a pod or specified resource. If the pod
has only one container, the container name is optional.
Usage
$ kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]
Flags
port-forward
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000
and 6000 in the pod
kubectl port-forward pod/mypod 5000 6000
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000
and 6000 in a pod selected by the deployment
kubectl port-forward deployment/mydeployment 5000 6000
Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the
pod
kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
Usage
$ kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...
[LOCAL_PORT_N:]REMOTE_PORT_N]
Flags
proxy
To proxy all of the Kubernetes API and nothing else
kubectl proxy --api-prefix=/
To proxy only part of the Kubernetes API and also some static files # You
can get pods info with 'curl localhost:8001/api/v1/pods'
kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
To proxy the entire Kubernetes API at a different root # You can get pods
info with 'curl localhost:8001/custom/api/v1/pods'
kubectl proxy --api-prefix=/custom/
Run a proxy to the Kubernetes API server on port 8011, serving static
content from ./local/www/
kubectl proxy --port=8011 --www=./local/www/
Run a proxy to the Kubernetes API server on an arbitrary local port # The
chosen port for the server will be output to stdout
kubectl proxy --port=0
Run a proxy to the Kubernetes API server, changing the API prefix to k8s-
api # This makes e.g. the pods API available at
localhost:8001/k8s-api/v1/pods/
kubectl proxy --api-prefix=/k8s-api
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.
Usage
$ kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--
api-prefix=prefix]
Flags
Shorth
Name and Default Usage
top
Display Resource (CPU/Memory) usage.
The top command allows you to see the resource consumption for nodes or
pods.
This command requires Metrics Server to be correctly configured and working
on the server.
Usage
$ kubectl top
node
Show metrics for all nodes
kubectl top node
Usage
$ kubectl top node [NAME | -l label]
Flags
Usage
$ kubectl top pod [NAME | -l label]
Flags
CLUSTER MANAGEMENT
api-versions
Print the supported API versions
kubectl api-versions
Usage
$ kubectl api-versions
certificate
Modify certificate resources.
Usage
$ kubectl certificate SUBCOMMAND
approve
Approve CSR 'csr-sqgzp'
kubectl certificate approve csr-sqgzp
Usage
$ kubectl certificate approve (-f FILENAME | NAME)
Flags
Shorth Defau
Name and lt Usage
deny
Deny CSR 'csr-sqgzp'
kubectl certificate deny csr-sqgzp
Usage
$ kubectl certificate deny (-f FILENAME | NAME)
Flags
Shorth Defau
Name and lt Usage
cluster-info
Print the address of the control plane and cluster services
kubectl cluster-info
Usage
$ kubectl cluster-info
dump
Dump current cluster state to stdout
kubectl cluster-info dump
Dump cluster information out suitable for debugging and diagnosing cluster
problems. By default, dumps everything to stdout. You can optionally
specify a directory with --output-directory. If you specify a directory,
Kubernetes will build a set of files in that directory. By default, only
dumps things in the current namespace and 'kube-system' namespace, but you
can switch to a different namespace with the --namespaces flag, or specify
--all-namespaces to dump all namespaces.
The command also dumps the logs of all of the pods in the cluster; these
logs are dumped into different directories based on namespace and pod name.
Usage
$ kubectl cluster-info dump
Flags
Shorth Defau
Name and lt Usage
es --namespaces is ignored.
cordon
Mark node "foo" as unschedulable
kubectl cordon foo
Usage
$ kubectl cordon NODE
Flags
drain
Drain node "foo", even if there are pods not managed by a replication
controller, replica set, job, daemon set or stateful set on it
kubectl drain foo --force
Usage
$ kubectl drain NODE
Flags
taint
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
kubectl taint nodes foo dedicated=special-user:NoSchedule
Remove from node 'foo' the taint with key 'dedicated' and effect
'NoSchedule' if one exists
kubectl taint nodes foo dedicated:NoSchedule-
Remove from node 'foo' all the taints with key 'dedicated'
kubectl taint nodes foo dedicated-
Usage
$ kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ...
KEY_N=VAL_N:TAINT_EFFECT_N
Flags
Shorth Defau
Name and lt Usage
uncordon
Mark node "foo" as schedulable
kubectl uncordon foo
Usage
$ kubectl uncordon NODE
Flags
alpha
These commands correspond to alpha features that are not enabled in
Kubernetes clusters by default.
Usage
$ kubectl alpha
api-resources
Print the supported API resources
kubectl api-resources
Usage
$ kubectl api-resources
Flags
completion
Installing bash completion on macOS using homebrew ## If running Bash 3.2
included with macOS
brew install bash-completion
brew install bash-completion@2
kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl
Load the kubectl completion code for zsh[1] into the current shell
source <(kubectl completion zsh)
Output shell completion code for the specified shell (bash or zsh). The
shell code must be evaluated to provide interactive completion of kubectl
commands. This can be done by sourcing it from the .bash_profile.
Detailed instructions on how to do this are available here:
for macOS: https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/
#enable-shell-autocompletion
for linux: https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
#enable-shell-autocompletion
for windows: https://kubernetes.io/docs/tasks/tools/install-kubectl-
windows/#enable-shell-autocompletion
Note for zsh users: [1] zsh completions are only supported in versions of
zsh >= 5.2.
Usage
$ kubectl completion SHELL
config
Modify kubeconfig files using subcommands like "kubectl config set current-
context my-context"
The loading order follows these rules:
1. If the --kubeconfig flag is set, then only that file is loaded. The
flag may only be set once and no merging takes place.
2. If $KUBECONFIG environment variable is set, then it is used as a list
of paths (normal path delimiting rules for your system). These paths
are merged. When a value is modified, it is modified in the file that
defines the stanza. When a value is created, it is created in the
first file that exists. If no files in the chain exist, then it
creates the last file in the list.
3. Otherwise, ${HOME}/.kube/config is used and no merging takes place.
Usage
$ kubectl config SUBCOMMAND
current-context
Display the current-context
kubectl config current-context
Usage
$ kubectl config current-context
delete-cluster
Delete the minikube cluster
kubectl config delete-cluster minikube
Usage
$ kubectl config delete-cluster NAME
delete-context
Delete the context for the minikube cluster
kubectl config delete-context minikube
Usage
$ kubectl config delete-context NAME
delete-user
Delete the minikube user
kubectl config delete-user minikube
Usage
$ kubectl config delete-user NAME
get-clusters
List the clusters that kubectl knows about
kubectl config get-clusters
Usage
$ kubectl config get-clusters
get-contexts
List all the contexts in your kubeconfig file
kubectl config get-contexts
Usage
$ kubectl config get-contexts [(-o|--output=)name)]
Flags
get-users
List the users that kubectl knows about
kubectl config get-users
Usage
$ kubectl config get-users
rename-context
Rename the context 'old-name' to 'new-name' in your kubeconfig file
kubectl config rename-context old-name new-name
Usage
$ kubectl config rename-context CONTEXT_NAME NEW_NAME
set
Set the server field on the my-cluster cluster to https://1.2.3.4
kubectl config set clusters.my-cluster.server https://1.2.3.4
Usage
$ kubectl config set PROPERTY_NAME PROPERTY_VALUE
Flags
set-cluster
Set only the server field on the e2e cluster entry without touching other
values
kubectl config set-cluster e2e --server=https://1.2.3.4
Embed certificate authority data for the e2e cluster entry
kubectl config set-cluster e2e --embed-certs --certificate-
authority=~/.kube/e2e/kubernetes.ca.crt
Set custom TLS server name to use for validation for the e2e cluster entry
kubectl config set-cluster e2e --tls-server-name=my-cluster-name
Usage
$ kubectl config set-cluster NAME [--server=server] [--certificate-
authority=path/to/certificate/authority] [--insecure-skip-tls-verify=true]
[--tls-server-name=example.com]
Flags
set-context
Set the user field on the gce context entry without touching other values
kubectl config set-context gce --user=cluster-admin
Usage
$ kubectl config set-context [NAME | --current] [--
cluster=cluster_nickname] [--user=user_nickname] [--namespace=namespace]
Flags
Name Shorthand Default Usage
set-credentials
Set only the "client-key" field on the "cluster-admin" # entry, without
touching other values
kubectl config set-credentials cluster-admin --client-key=~/.kube/admin.key
Enable the Google Compute Platform auth provider for the "cluster-admin"
entry
kubectl config set-credentials cluster-admin --auth-provider=gcp
Enable the OpenID Connect auth provider for the "cluster-admin" entry with
additional args
kubectl config set-credentials cluster-admin --auth-provider=oidc --auth-
provider-arg=client-id=foo --auth-provider-arg=client-secret=bar
Remove the "client-secret" config value for the OpenID Connect auth
provider for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --auth-provider=oidc --auth-
provider-arg=client-secret-
Define new exec auth plugin args for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-arg=arg1 --exec-
arg=arg2
Create or update exec auth plugin environment variables for the "cluster-
admin" entry
kubectl config set-credentials cluster-admin --exec-env=key1=val1 --exec-
env=key2=val2
Remove exec auth plugin environment variables for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-env=var-to-remove-
Usage
$ kubectl config set-credentials NAME
[--client-certificate=path/to/certfile] [--client-key=path/to/keyfile] [--
token=bearer_token] [--username=basic_user] [--password=basic_password] [--
auth-provider=provider_name] [--auth-provider-arg=key=value] [--exec-
command=exec_command] [--exec-api-version=exec_api_version] [--exec-
arg=arg] [--exec-env=key=value]
Flags
unset
Unset the current-context
kubectl config unset current-context
Usage
$ kubectl config unset PROPERTY_NAME
use-context
Use the context for the minikube cluster
kubectl config use-context minikube
Usage
$ kubectl config use-context CONTEXT_NAME
view
Show merged kubeconfig settings
kubectl config view
Usage
$ kubectl config view
Flags
Shorth Defau
Name and lt Usage
explain
Get the documentation of the resource and its fields
kubectl explain pods
Usage
$ kubectl explain RESOURCE
Flags
Name Shorthand Default Usage
options
Print flags inherited by all commands
kubectl options
Usage
$ kubectl options
plugin
Provides utilities for interacting with plugins.
Plugins provide extended functionality that is not part of the major
command-line distribution. Please refer to the documentation and examples
for more information about how write your own plugins.
The easiest way to discover and install plugins is via the kubernetes sub-
project krew. To install krew, visit https://krew.sigs.k8s.io/docs/user-
guide/setup/install/
Usage
$ kubectl plugin [flags]
list
List all available plugin files on a user's PATH.
Available plugin files are those that are: - executable - anywhere on the
user's PATH - begin with "kubectl-"
Usage
$ kubectl plugin list
Flags
version
Print the client and server versions for the current context
kubectl version
Print the client and server version information for the current context.
Usage
$ kubectl version
Flags