Kubernetes Kubectl Commands
Kubernetes Kubectl Commands
• create
• get
• run
• expose
• delete
• APP MANAGEMENT
• apply
• annotate
• autoscale
• debug
• diff
• edit
• kustomize
• label
• patch
• replace
• rollout
• scale
• set
• wait
• attach
• auth
• cp
• describe
• exec
• logs
• port-forward
• proxy
• top
• CLUSTER MANAGEMENT
• api-versions
• certificate
• cluster-info
• cordon
• drain
• taint
• uncordon
• alpha
• api-resources
• completion
• config
• explain
• options
• plugin
• version
• example
GETTING STARTED
This section contains the most basic commands for getting a workload running on your cluster.
• run will start running 1 or more instances of a container image on your cluster.
• expose will load balance traffic across the running instances, and can create a HA proxy
for accessing the containers from outside the 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
Edit the data in docker-registry.yaml in JSON then create the resource using the
edited data
Usage
Flags
clusterrole
Create a cluster role named "pod-reader" that allows user to perform "get", "watch"
and "list" on pods
Usage
Flags
Usage
Flags
Create a new config map named my-config with specified keys instead of file
basenames on disk
Create a new config map named my-config with key1=config1 and key2=config2
Create a new config map named my-config from the key=value pairs in the file
When creating a config map based on a file, the key will default to the basename of the file, and
the value will default to the file content. If the basename is an invalid key, you may specify an
alternate key.
When creating a config map based on a directory, each file whose basename is a valid key in
the directory will be packaged into the config map. Any directory entries except regular files
are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).
Usage
Flags
cronjob
Create a cron job
Usage
deployment
Create a deployment named my-dep that runs the busybox image
Create a deployment named my-dep that runs the nginx image with 3 replicas
Create a deployment named my-dep that runs the busybox image and expose port
5701
Usage
Flags
ingress
Create a single ingress called 'simple' that directs requests to foo.com/bar to svc #
svc1:8080 with a tls secret "my-cert"
Create a catch all ingress of "/path" pointing to service svc:port and Ingress Class as
"otheringress"
Create an ingress with TLS enabled using the default ingress certificate and
different path types
Create an ingress with TLS enabled using a specific secret and pathType as Prefix
Usage
Flags
job
Create a job
Usage
namespace
Create a new namespace named my-namespace
Usage
Flags
poddisruptionbudget
Create a pod disruption budget named my-pdb that will select all pods with the
app=rails label # and require at least one of them being available at any point in
time
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
Create a pod disruption budget with the specified name, selector, and desired minimum
available pods.
Usage
Flags
priorityclass
Create a priority class named high-priority
Create a priority class named high-priority that cannot preempt pods with lower
priority
Usage
Flags
Create a resource quota with the specified name, hard limits, and optional scopes.
Usage
Flags
Usage
Flags
rolebinding
Create a role binding for user1, user2, and group1 using the admin cluster role
Usage
Flags
secret
Create a secret using specified subcommand.
Usage
secret docker-registry
If you don't already have a .dockercfg file, you can create a dockercfg secret directly
by using:
When using the Docker command line to push images, you can authenticate to a given registry
by running: '$ docker login DOCKER_REGISTRY_SERVER --username=DOCKER_USER --
password=DOCKER_PASSWORD --email=DOCKER_EMAIL'.
That produces a ~/.dockercfg file that is used by subsequent 'docker push' and 'docker pull'
commands to authenticate to the registry. The email address is optional.
When creating applications, you may have a Docker registry that requires authentication. In
order for the nodes to pull images on your behalf, they must have the credentials. You can
provide this information by creating a dockercfg secret and attaching it to your service account.
Usage
Flags
secret generic
Create a new secret named my-secret with keys for each file in folder bar
Create a new secret named my-secret with specified keys instead of names on disk
Create a new secret named my-secret using a combination of a file and a literal
When creating a secret based on a file, the key will default to the basename of the file, and the
value will default to the file content. If the basename is an invalid key or you wish to chose
your own, you may specify an alternate key.
When creating a secret based on a directory, each file whose basename is a valid key in the
directory will be packaged into the secret. Any directory entries except regular files are ignored
(e.g. subdirectories, symlinks, devices, pipes, etc).
Usage
Flags
secret tls
Create a new TLS secret named tls-secret with the given key pair
The public/private key pair must exist beforehand. The public key certificate must be .PEM
encoded and match the given private key.
Usage
Flags
service
Create a service using a specified subcommand.
Usage
service clusterip
Create a new ClusterIP service named my-cs
kubectl create service clusterip my-cs --tcp=5678:8080
Usage
Flags
service externalname
Create a new ExternalName service named my-ns
ExternalName service references to an external DNS address instead of only pods, which will
allow application authors to reference services that exist off platform, on other clusters, or
locally.
Usage
Flags
service loadbalancer
Create a new LoadBalancer service named my-lbs
Flags
service nodeport
Create a new NodePort service named my-ns
Usage
serviceaccount
Create a new service account named my-service-account
Usage
Flags
get
List all pods in ps output format
List all pods in ps output format with more information (such as node name)
List deployments in JSON output format, in the "v1" version of the "apps" API
group
List a pod identified by type and name specified in "pod.yaml" in JSON output
format
Prints a table of the most important information about the specified resources. You can filter the
list using a label selector and the --selector flag. If the desired resource type is namespaced you
will only see results in your current namespace unless you pass --all-namespaces.
By specifying the output as 'template' and providing a Go template as the value of the --
template flag, you can filter the attributes of the fetched resources.
Usage
Flags
run
Start a nginx pod
Start a hazelcast pod and let the container expose port 5701
Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the container
Dry run; print the corresponding API objects without creating them
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 a busybox pod and keep it in the foreground, don't restart it if it exits
Start the nginx pod using the default command, but use custom arguments (arg1 ..
argN) for that command
Start the nginx pod using a different command and custom arguments
Usage
Flags
expose
Create a service for a replicated nginx, which serves on port 80 and connects to the
containers on 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
Create a service for a pod valid-pod, which serves on port 444 with the name
"frontend"
Create a second service based on the above service, exposing the container port
8443 as port 443 with the name "nginx-https"
Create a service for a replicated streaming application on port 4100 balancing UDP
traffic and named '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
Create a service for an nginx deployment, which serves on port 80 and connects to
the containers on port 8000
Looks up a deployment, service, replica set, replication controller or pod by name and uses the
selector for that resource as the selector for a new service on the specified port. A deployment
or replica set will be exposed as a service only if its selector is convertible to a selector that
service supports, i.e. when the selector contains only the matchLabels component. Note that if
no port is specified via --port and the exposed resource has multiple ports, all will be re-used by
the new service. Also if no labels are specified, the new service will re-use the labels from the
resource it exposes.
pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)
Usage
Flags
delete
Delete a pod using the type and name specified in pod.json
kubectl delete -f ./pod.json
Delete a pod based on the type and name in the JSON passed into stdin
Delete pods and services with same names "baz" and "foo"
Delete resources by file names, stdin, resources and names, or by resources and label selector.
JSON and YAML formats are accepted. Only one type of argument may be specified: file names,
resources and names, or resources and label selector.
Some resources, such as pods, support graceful deletion. These resources define a default period
before they are forcibly terminated (the grace period) but you may override that value with the
--grace-period flag, or pass --now to set a grace-period of 1. Because these resources often
represent entities in the cluster, deletion may not be acknowledged immediately. If the node
hosting a pod is down or cannot reach the API server, termination may take significantly longer
than the grace period. To force delete a resource, you must specify the --force flag. Note: only a
subset of resources support graceful deletion. In absence of the support, the --grace-period flag
is ignored.
IMPORTANT: Force deleting pods does not wait for confirmation that the pod's processes have
been terminated, which can leave those processes running until the node detects the deletion
and completes graceful deletion. If your processes use shared storage or talk to a remote API
and depend on the name of the pod to identify themselves, force deleting those pods may result
in multiple processes running on different machines using the same identification which may
lead to data corruption or inconsistency. Only force delete pods when you are sure the pod is
terminated, or if your application can tolerate multiple copies of the same pod running at once.
Also, if you force delete pods, the scheduler may place new pods on those nodes before the
node has released those resources and causing those pods to be evicted immediately.
Note that the delete command does NOT do resource version checks, so if someone submits an
update to a resource right when you submit a delete, their update will be lost along with the
rest of the resource.
Usage
$ kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)])
Flags
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
Apply the configuration in manifest.yaml and delete all the other config maps that
are not in the file
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'.
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
Flags
edit-last-applied
Edit the last-applied-configuration annotations by type/name in YAML
Edit the latest last-applied-configuration annotations of resources from the default editor.
The edit-last-applied command allows you to directly edit any API resource you can retrieve via
the command-line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR
environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. You can edit
multiple objects, although changes are applied one at a time. The command accepts file names
as well as command-line arguments, although the files you point to must be previously saved
versions of resources.
In the event an error occurs while updating, a temporary file will be created on disk that
contains your unapplied changes. The most common error when updating a resource is another
editor changing the resource on the server. When this occurs, you will have to apply your
changes to the newer version of the resource, or update your temporary saved copy to include
the latest resource version.
Usage
Flags
Set the latest last-applied-configuration annotations by setting it to match the contents of a file.
This results in the last-applied-configuration being updated as though 'kubectl apply -f ' was
run, without updating any other parts of the object.
Usage
Flags
view-last-applied
View the last-applied-configuration annotations by type/name in YAML
kubectl apply view-last-applied deployment/nginx
The default output will be printed to stdout in YAML format. You can use the -o option to
change the output format.
Usage
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
Update pod 'foo' with the annotation 'description' and the value 'my frontend
running nginx', overwriting any existing value
All Kubernetes objects support the ability to store additional data with the object as
annotations. Annotations are key/value pairs that can be larger than labels and include
arbitrary string values such as structured JSON. Tools and system extensions may use
annotations to store their own data.
Attempting to set an annotation that already exists will fail unless --overwrite is set. If --
resource-version is specified and does not match the current resource version on the server the
command will fail.
Usage
Flags
autoscale
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
Auto scale a replication controller "foo", with the number of pods between 1 and 5,
target CPU utilization at 80%
Creates an autoscaler that automatically chooses and sets the number of pods that run in a
Kubernetes cluster.
Looks up a deployment, replica set, stateful set, or replication controller by name and creates an
autoscaler that uses the given resource as a reference. An autoscaler can automatically increase
or decrease number of pods deployed within the system as needed.
Usage
Flags
debug
Create an interactive debugging session in pod mypod and immediately attach to it.
# (requires the EphemeralContainers feature to be enabled in the cluster)
Create a copy of mypod adding a debug container and changing container images
'debug' provides automation for common debugging tasks for cluster objects identified by
resource and name. Pods will be used by default if no resource is specified.
The action taken by 'debug' varies depending on what resource is specified. Supported actions
include:
• Workload: Create a copy of an existing pod with certain attributes changed, for example
changing the image tag to a new version.
• Workload: Add an ephemeral container to an already running pod, for example to add
debugging utilities without restarting the pod.
• Node: Create a new pod that runs in the node's host namespaces and can access the
node's filesystem.
Usage
Flags
diff
Diff resources included in pod.json
kubectl diff -f pod.json
Diff configurations specified by file name or stdin between the current online configuration,
and the configuration as it would be if applied.
By default, the "diff" command available in your path will be run with the "-u" (unified diff) and
"-N" (treat absent files as empty) options.
Exit status: 0 No differences were found. 1 Differences were found. >1 Kubectl or diff failed with
an error.
Usage
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
The edit command allows you to directly edit any API resource you can retrieve via the
command-line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR
environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. You can edit
multiple objects, although changes are applied one at a time. The command accepts file names
as well as command-line arguments, although the files you point to must be previously saved
versions of resources.
Editing is done with the API version used to fetch the resource. To edit using a specific API
version, fully-qualify the resource, version, and group.
The flag --windows-line-endings can be used to force Windows line endings, otherwise the
default for your operating system will be used.
In the event an error occurs while updating, a temporary file will be created on disk that
contains your unapplied changes. The most common error when updating a resource is another
editor changing the resource on the server. When this occurs, you will have to apply your
changes to the newer version of the resource, or update your temporary saved copy to include
the latest resource version.
Usage
Flags
kustomize
Build the current working directory
kubectl kustomize
Build a set of KRM resources using a 'kustomization.yaml' file. The DIR argument must be a
path to a directory containing 'kustomization.yaml', or a git repository URL with a path suffix
specifying same with respect to the repository root. If DIR is omitted, '.' is assumed.
Usage
Flags
label
Update pod 'foo' with the label 'unhealthy' and the value 'true'
Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any
existing value
Update pod 'foo' by removing a label named 'bar' if it exists # Does not require the
--overwrite flag
• 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
patch
Partially update a node using a strategic merge patch, specifying the patch as JSON
Partially update a node using a strategic merge patch, specifying the patch as
YAML
Partially update a node identified by the type and name specified in "node.json"
using strategic merge patch
Update fields of a resource using strategic merge patch, a JSON merge patch, or a JSON patch.
Usage
Flags
replace
Replace a pod using the data in pod.json
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
JSON and YAML formats are accepted. If replacing an existing resource, the complete resource
spec must be provided. This can be obtained by
Usage
Flags
• deployments
• daemonsets
• statefulsets
Usage
history
View the rollout history of a deployment
Usage
Flags
pause
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
Paused resources will not be reconciled by a controller. Use "kubectl rollout resume" to resume
a paused resource. Currently only deployments support being paused.
Usage
Flags
restart
Restart a deployment
Restart a resource.
Usage
Flags
resume
Resume an already paused deployment
Usage
Flags
By default 'rollout status' will watch the status of the latest rollout until it's done. If you don't
want to wait for the rollout to finish then you can use --watch=false. Note that if a new rollout
starts in-between, then 'rollout status' will continue watching the latest revision. If you want to
pin to a specific revision and abort if it is rolled over by another revision, use --revision=N
where N is the revision you need to watch for.
Usage
Flags
undo
Roll back to the previous deployment
Flags
scale
Scale a replica set named 'foo' to 3
Set a new size for a deployment, replica set, replication controller, or stateful set.
Scale also allows users to specify one or more preconditions for the scale action.
Usage
Flags
set
Configure application resources.
Usage
env
Update deployment 'registry' with a new environment variable
Output modified deployment in YAML, and does not alter the object on the server
Update all containers in all replication controllers in the project to have ENV=prod
Remove the environment variable ENV from container 'c1' in all deployment
configs
Remove the environment variable ENV from a deployment definition on disk and #
update the deployment config on the server
Set some of the local shell environment into a deployment config on the server
List environment variable definitions in one or more pods, pod templates. Add, update, or
remove container environment variable definitions in one or more pod templates (within
replication controllers or deployment configurations). View or modify the environment variable
definitions on all containers in the specified pods or pod templates, or just those that match a
wildcard.
If "--env -" is passed, environment variables can be read from STDIN using the standard env
syntax.
pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), statefulset (sts),
cronjob (cj), replicaset (rs)
Usage
Flags
image
Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container
image to 'busybox'
Print result (in yaml format) of updating nginx container image from local file,
without hitting the server
pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), statefulset (sts),
cronjob (cj), replicaset (rs)
Usage
Flags
resources
Set a deployments nginx container cpu limits to "200m" and memory to "512Mi"
Set the resource request and limits for all containers in nginx
Print the result (in yaml format) of updating nginx container limits from a local,
without hitting the server
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
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 - environm
ent=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
Flags
serviceaccount
Set deployment nginx-deployment's service account to serviceaccount1
Print the result (in YAML format) of updated nginx deployment with the service
account from local file, without hitting the API server
replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs), statefulset
Usage
Flags
subject
Update a cluster role binding for serviceaccount1
Print the result (in YAML format) of updating rolebinding subjects from a local,
without hitting the server
Update the user, group, or service account in a role binding or cluster role binding.
Usage
$ kubectl set subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--
serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]
Flags
wait
Wait for the pod "busybox1" to contain the status condition of type "Ready"
The default value of status condition is true; you can set it to false
The command takes multiple resources and waits until the specified condition is seen in the
Status field of every given resource.
Alternatively, the command can wait for the given set of resources to be deleted by providing
the "delete" keyword as the value to the --for flag.
A successful message will be printed to stdout indicating when the specified condition has been
met. You can use -o option to change to output destination.
Usage
Flags
• 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
Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod
mypod # and sends stdout/stderr from 'bash' back to the client
Get output from the first pod of a replica set named nginx
Usage
auth
Inspect authorization
Usage
$ kubectl auth
can-i
Check to see if I can create pods in any namespace
Check to see if I can get the job named "bar" in namespace "foo"
VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc. TYPE is a Kubernetes
resource. Shortcuts and groups will be resolved. NONRESOURCEURL is a partial URL that
starts with "/". NAME is the name of a particular Kubernetes resource.
Usage
Flags
reconcile
Reconcile RBAC resources from a file
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
Flags
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
Usage
Flags
describe
Describe a node
Describe a pod
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)
will first check for an exact match on TYPE and NAME_PREFIX. If no such resource exists, it
will output details for every resource that has a name prefixed with NAME_PREFIX.
Usage
Flags
exec
Get output from running the 'date' command from pod mypod, using the first
container by default
Get output from running the 'date' command in ruby-container from pod mypod
Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod
mypod # and sends stdout/stderr from 'bash' back to the client
Get output from running 'date' command from the first pod of the deployment
mydeployment, using the first container by default
Get output from running 'date' command from the first pod of the service
myservice, using the first container by default
Usage
Flags
logs
Return snapshot logs from pod nginx with only one container
Return snapshot logs from all containers in pods defined by label app=nginx
Begin streaming the logs from all containers in pods defined by label app=nginx
Show all logs from pod nginx written in the last hour
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
Flags
port-forward
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000
in the pod
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000
in a pod selected by the deployment
Listen on port 8443 locally, forwarding to the targetPort of the service's port named
"https" in a pod selected by the service
Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
If there are multiple pods matching the criteria, a pod will be selected automatically. The
forwarding session ends when the selected pod terminates, and a rerun of the command is
needed to resume forwarding.
Usage
Flags
proxy
To proxy all of the Kubernetes API and nothing else
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'
To proxy the entire Kubernetes API at a different root # You can get pods info with
'curl localhost:8001/custom/api/v1/pods'
Run a proxy to the Kubernetes API server on port 8011, serving static content from
./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/
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
Flags
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
The top-node command allows you to see the resource consumption of nodes.
Usage
Flags
pod
Show metrics for all pods in the default namespace
The 'top pod' command allows you to see the resource consumption of pods.
Due to the metrics pipeline delay, they may be unavailable for a few minutes since pod creation.
Usage
Flags
CLUSTER MANAGEMENT
api-versions
Print the supported API versions
kubectl api-versions
Print the supported API versions on the server, in the form of "group/version".
Usage
$ kubectl api-versions
certificate
Modify certificate resources.
Usage
approve
Approve CSR 'csr-sqgzp'
kubectl certificate approve allows a cluster admin to approve a certificate signing request (CSR).
This action tells a certificate signing controller to issue a certificate to the requestor with the
attributes requested in the CSR.
SECURITY NOTICE: Depending on the requested attributes, the issued certificate can
potentially grant a requester access to cluster resources or to authenticate as a requested
identity. Before approving a CSR, ensure you understand what the signed certificate can do.
Usage
Flags
deny
Deny CSR 'csr-sqgzp'
kubectl certificate deny allows a cluster admin to deny a certificate signing request (CSR). This
action tells a certificate signing controller to not to issue a certificate to the requestor.
Usage
Flags
cluster-info
Print the address of the control plane and cluster services
kubectl cluster-info
Display addresses of the control plane and services with label kubernetes.io/cluster-
service=true. To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
Usage
$ kubectl cluster-info
dump
Dump current cluster state to stdout
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
cordon
Mark node "foo" as unschedulable
Usage
Flags
As above, but abort if there are pods not managed by a replication controller,
replica set, job, daemon set or stateful set, and use a grace period of 15 minutes
The given node will be marked unschedulable to prevent new pods from arriving. 'drain' evicts
the pods if the API server supports https://kubernetes.io/docs/concepts/workloads/pods/
disruptions/ . Otherwise, it will use normal DELETE to delete the pods. The 'drain' evicts or
deletes all pods except mirror pods (which cannot be deleted through the API server). If there
are daemon set-managed pods, drain will not proceed without --ignore-daemonsets, and
regardless it will not delete any daemon set-managed pods, because those pods would be
immediately replaced by the daemon set controller, which ignores unschedulable markings. If
there are any pods that are neither mirror pods nor managed by a replication controller, replica
set, daemon set, stateful set, or job, then drain will not delete any pods unless you use --force. --
force will also allow deletion to proceed if the managing resource of one or more pods is
missing.
'drain' waits for graceful termination. You should not operate on the machine until the
command completes.
When you are ready to put the node back into service, use kubectl uncordon, which will make
the node schedulable again.
https://kubernetes.io/images/docs/kubectl_drain.svg
Usage
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
Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one
exists
Remove from node 'foo' all the taints with key 'dedicated'
Usage
Flags
uncordon
Mark node "foo" as schedulable
Usage
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
source '$HOME/.kube/completion.bash.inc'
" >> $HOME/.bash_profile
source $HOME/.bash_profile
Load the kubectl completion code for zsh[1] into the current shell
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.
Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2.
Usage
config
Modify kubeconfig files using subcommands like "kubectl config set current-context my-
context"
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
current-context
Display the current-context
Usage
delete-cluster
Delete the minikube cluster
Usage
delete-context
Delete the context for the minikube cluster
Usage
delete-user
Delete the minikube user
Usage
get-clusters
List the clusters that kubectl knows about
Usage
get-contexts
List all the contexts in your kubeconfig file
Usage
Flags
get-users
List the users that kubectl knows about
rename-context
Rename the context 'old-name' to 'new-name' in your kubeconfig file
Note: If the context being renamed is the 'current-context', this field will also be updated.
Usage
set
Set the server field on the my-cluster cluster to https://1.2.3.4
Set the client-key-data field in the cluster-admin user using --set-raw-bytes option
PROPERTY_NAME is a dot delimited name where each token represents either an attribute
name or a map key. Map keys may not contain dots.
PROPERTY_VALUE is the new value you want to set. Binary fields such as 'certificate-
authority-data' expect a base64 encoded string unless the --set-raw-bytes flag is used.
Specifying an attribute name that already exists will merge new fields on top of existing values.
Usage
Flags
set-cluster
Set only the server field on the e2e cluster entry without touching other values
Set custom TLS server name to use for validation for the e2e cluster entry
Specifying a name that already exists will merge new fields on top of existing values for those
fields.
Usage
Flags
set-context
Set the user field on the gce context entry without touching other values
Specifying a name that already exists will merge new fields on top of existing values for those
fields.
Usage
Flags
set-credentials
Set only the "client-key" field on the "cluster-admin" # entry, without touching
other values
Enable the Google Compute Platform auth provider for the "cluster-admin" entry
Enable the OpenID Connect auth provider for the "cluster-admin" entry with
additional args
Remove the "client-secret" config value for the OpenID Connect auth provider for
the "cluster-admin" entry
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
Remove exec auth plugin environment variables for the "cluster-admin" entry
Specifying a name that already exists will merge new fields on top of existing values.
Usage
Flags
unset
Unset the current-context
kubectl config unset current-context
PROPERTY_NAME is a dot delimited name where each token represents either an attribute
name or a map key. Map keys may not contain dots.
Usage
use-context
Use the context for the minikube cluster
Usage
view
Show merged kubeconfig settings
You can use --output jsonpath={...} to extract specific values using a jsonpath expression.
Usage
explain
Get the documentation of the resource and its fields
This command describes the fields associated with each supported API resource. Fields are
identified via a simple JSONPath identifier:
<type>.<fieldName>[.<fieldName>]
Add the --recursive flag to display all of the fields at once without descriptions. Information
about each field is retrieved from the server in OpenAPI format.
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
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
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