GETTING STARTED

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

Create a pod based on the JSON passed into stdin.

cat pod.json | kubectl create -f -

Edit the data in docker-registry.yaml in JSON then create the resource using the edited data.

kubectl create -f docker-registry.yaml --edit -o json

Create a resource from a file or from stdin.

JSON and YAML formats are accepted.

Usage

$ create -f FILENAME

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
edit false Edit the API resource before creating
filename f [] Filename, directory, or URL to files to use to create the resource
output o Output format. One of: json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath|jsonpath-file.
raw Raw URI to POST to the server. Uses the transport specified by the kubeconfig file.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it
windows-line-endings false Only relevant if --edit=true. Defaults to the line ending native to your platform.

configmap

Create a new configmap named my-config based on folder bar

kubectl create configmap my-config --from-file=path/to/bar

Create a new configmap 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 configmap 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 configmap named my-config from the key=value pairs in the file

kubectl create configmap my-config --from-file=path/to/bar

Create a new configmap named my-config from an env file

kubectl create configmap my-config --from-env-file=path/to/bar.env

Create a configmap based on a file, directory, or specified literal value.

A single configmap may package one or more key/value pairs.

When creating a configmap 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 configmap based on a directory, each file whose basename is a valid key in the directory will be packaged into the configmap. Any directory entries except regular files are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).

Usage

$ configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
append-hash false Append a hash of the configmap to its name.
dry-run false If true, only print the object that would be sent, without sending it.
from-env-file Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).
from-file [] Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key.
from-literal [] Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)
generator configmap/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

secret

Create a secret using specified subcommand.

Usage

$ 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

Create a new secret for use with Docker registries.

Dockercfg secrets are used to authenticate against Docker registries.

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 have to have the credentials. You can provide this information by creating a dockercfg secret and attaching it to your service account.

Usage

$ docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
append-hash false Append a hash of the secret to its name.
docker-email Email for Docker registry
docker-password Password for Docker registry authentication
docker-server https://index.docker.io/v1/ Server location for Docker registry
docker-username Username for Docker registry authentication
dry-run false If true, only print the object that would be sent, without sending it.
from-file [] Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.
generator secret-for-docker-registry/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

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=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub

Create a new secret named my-secret with key1=supersecret and key2=topsecret

kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret

Create a new secret named my-secret using a combination of a file and a literal

kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-literal=passphrase=topsecret

Create a new secret named my-secret from an env file

kubectl create secret generic my-secret --from-env-file=path/to/bar.env

Create a secret based on a file, directory, or specified literal value.

A single secret may package one or more key/value pairs.

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

$ generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
append-hash false Append a hash of the secret to its name.
dry-run false If true, only print the object that would be sent, without sending it.
from-env-file Specify the path to a file to read lines of key=val pairs to create a secret (i.e. a Docker .env file).
from-file [] Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.
from-literal [] Specify a key and literal value to insert in secret (i.e. mykey=somevalue)
generator secret/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
type The type of secret to create
validate false If true, use a schema to validate the input before sending it

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

Create a TLS secret from the given public/private key pair.

The public/private key pair must exist before hand. The public key certificate must be .PEM encoded and match the given private key.

Usage

$ tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
append-hash false Append a hash of the secret to its name.
cert Path to PEM encoded public key certificate.
dry-run false If true, only print the object that would be sent, without sending it.
generator secret-for-tls/v1 The name of the API generator to use.
key Path to private key associated with given certificate.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

service

Create a service using specified subcommand.

Usage

$ service


service clusterip

Create a new ClusterIP service named my-cs

kubectl create service clusterip my-cs --tcp=5678:8080

Create a new ClusterIP service named my-cs (in headless mode)

kubectl create service clusterip my-cs --clusterip="None"

Create a ClusterIP service with the specified name.

Usage

$ clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
clusterip Assign your own ClusterIP or set to 'None' for a 'headless' service (no loadbalancing).
dry-run false If true, only print the object that would be sent, without sending it.
generator service-clusterip/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
tcp [] Port pairs can be specified as ':'.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

service externalname

Create a new ExternalName service named my-ns

kubectl create service externalname my-ns --external-name bar.com

Create an ExternalName service with the specified name.

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

$ externalname NAME --external-name external.name [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
external-name External name of service
generator service-externalname/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
tcp [] Port pairs can be specified as ':'.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

service loadbalancer

Create a new LoadBalancer service named my-lbs

kubectl create service loadbalancer my-lbs --tcp=5678:8080

Create a LoadBalancer service with the specified name.

Usage

$ loadbalancer NAME [--tcp=port:targetPort] [--dry-run]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
generator service-loadbalancer/v1 The name of the API generator to use.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
tcp [] Port pairs can be specified as ':'.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

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 a single replication controller with specified NAME in ps output format.

kubectl get replicationcontroller web

List deployments in JSON output format, in the "v1" version of the "apps" API group:

kubectl get deployments.v1.apps -o json

List a single pod in JSON output format.

kubectl get -o json pod web-pod-13je7

List a pod identified by type and name specified in "pod.yaml" in JSON output format.

kubectl get -f pod.yaml -o json

Return only the phase value of the specified pod.

kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

List all replication controllers and services together in ps output format.

kubectl get rc,services

List one or more resources by their type and names.

kubectl get rc/web service/frontend pods/web-pod-13je7

Display one or many resources

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.

Uninitialized objects are not shown unless --include-uninitialized is passed.

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.

Use "kubectl api-resources" for a complete list of supported resources.

Usage

$ get [(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags]

Flags

Name Shorthand Default Usage
all-namespaces false If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
chunk-size 500 Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future.
export false If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information.
field-selector Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.
filename f [] Filename, directory, or URL to files identifying the resource to get from a server.
ignore-not-found false If the requested object does not exist the command will return exit code 0.
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
label-columns L [] Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag options like -L label1 -L label2...
no-headers false When using the default or custom-column output format, don't print headers (default print headers).
output o Output format. One of: json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath].
raw Raw URI to request from the server. Uses the transport specified by the kubeconfig file.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
server-print true If true, have the server return the appropriate table output. Supports extension APIs and CRDs.
show-all a true When printing, show all resources (default show all pods including terminated one.)
show-kind false If present, list the resource type for the requested object(s).
show-labels false When printing, show all labels as the last column (default hide labels column)
sort-by If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
use-openapi-print-columns false If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource.
watch w false After listing/getting the requested object, watch for changes. Uninitialized objects are excluded if no object name is provided.
watch-only false Watch for changes to the requested object(s), without listing/getting first.

run

Start a single instance of nginx.

kubectl run nginx --image=nginx

Start a single instance of hazelcast and let the container expose port 5701 .

kubectl run hazelcast --image=hazelcast --port=5701

Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the container.

kubectl run hazelcast --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.

kubectl run hazelcast --image=nginx --labels="app=hazelcast,env=prod"

Start a replicated instance of nginx.

kubectl run nginx --image=nginx --replicas=5

Dry run. Print the corresponding API objects without creating them.

kubectl run nginx --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.

kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'

Start a pod of busybox and keep it in the foreground, don't restart it if it exits.

kubectl run -i -t busybox --image=busybox --restart=Never

Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.

kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>

Start the nginx container using a different command and custom arguments.

kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>

Start the perl container to compute π to 2000 places and print it out.

kubectl run pi --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.

kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

Create and run a particular image, possibly replicated.

Creates a deployment or job to manage the created container(s).

Usage

$ run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
cascade true If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.
command false If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default.
dry-run false If true, only print the object that would be sent, without sending it.
env [] Environment variables to set in the container
expose false If true, a public, external service is created for the container(s) which are run
filename f [] to use to replace the resource.
force false Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
generator The name of the API generator to use, see http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list.
grace-period -1 Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
image The image for the container to run.
image-pull-policy The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server
labels l Comma separated labels to apply to the pod(s). Will override previous values.
limits The resource requirement limits for this container. For example, 'cpu=200m,memory=512Mi'. Note that server side components may assign limits depending on the server configuration, such as limit ranges.
output o Output format. One of: json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
overrides An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.
pod-running-timeout 1m0s The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running
port The port that this container exposes. If --expose is true, this is also the port used by the service that is created.
quiet false If true, suppress prompt messages.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
replicas r 1 Number of replicas to create for this container. Default is 1.
requests The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.
restart Always The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created, if set to 'OnFailure' a job is created, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always', for CronJobs Never.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
schedule A schedule in the Cron format the job should be run with.
service-generator service/v2 The name of the generator to use for creating a service. Only used if --expose is true
service-overrides An inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true.
stdin i false Keep stdin open on the container(s) in the pod, even if nothing is attached.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
timeout 0s The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object
tty t false Allocated a TTY for each container in the pod.

expose

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 an nginx deployment, which serves on port 80 and connects to the containers on port 8000.

kubectl expose deployment nginx --port=80 --target-port=8000

Expose a resource as a new Kubernetes service.

Looks up a deployment, service or pod by name and uses the selector for that resource as the selector for a new service on the specified port. A deployment 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.

Possible resources include (case insensitive):

pod (po), service (svc), deployment (deploy)

Usage

$ expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
cluster-ip ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create a headless service.
container-port Synonym for --target-port
dry-run false If true, only print the object that would be sent, without sending it.
external-ip Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP is routed to a node, the service can be accessed by this IP in addition to its generated service IP.
filename f [] Filename, directory, or URL to files identifying the resource to expose a service
generator service/v2 The name of the API generator to use. There are 2 generators: 'service/v1' and 'service/v2'. The only difference between them is that service port in v1 is named 'default', while it is left unnamed in v2. Default is 'service/v2'.
labels l Labels to apply to the service created by this call.
load-balancer-ip IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used (cloud-provider specific).
name The name for the newly created object.
output o Output format. One of: json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath-file|jsonpath.
overrides An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.
port The port that the service should serve on. Copied from the resource being exposed, if unspecified
protocol The network protocol for the service to be created. Default is 'TCP'.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
selector A label selector to use for this service. Only equality-based selector requirements are supported. If empty (the default) infer the selector from the replication controller or replica set.)
session-affinity If non-empty, set the session affinity for the service to this; legal values: 'None', 'ClientIP'
target-port Name or number for the port on the container that the service should direct traffic to. Optional.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
type Type for this service: ClusterIP, LoadBalancer, or ExternalName. Default is 'ClusterIP'.

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.

cat pod.json | kubectl delete -f -

Delete pods and services with same names "baz" and "foo"

kubectl delete pod,service baz foo

Delete pods and services with label name=myLabel.

kubectl delete pods,services -l name=myLabel

Delete a pod with minimal delay

kubectl delete pod foo --now

Force delete a pod on a dead node

kubectl delete pod foo --grace-period=0 --force

Delete all pods

kubectl delete pods --all

Delete resources by filenames, stdin, resources and names, or by resources and label selector.

JSON and YAML formats are accepted. Only one type of the arguments may be specified: filenames, 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 pass a grace period of 0 and specify the --force flag.

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

$ delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])

Flags

Name Shorthand Default Usage
all false Delete all resources, including uninitialized ones, in the namespace of the specified resource types.
cascade true If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.
field-selector Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.
filename f [] containing the resource to delete.
force false Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
grace-period -1 Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
ignore-not-found false Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified.
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
now false If true, resources are signaled for immediate shutdown (same as --grace-period=1).
output o Output mode. Use "-o name" for shorter output (resource/name).
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, not including uninitialized ones.
timeout 0s The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object

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 JSON passed into stdin to a pod.

cat pod.json | kubectl apply -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.

kubectl apply --prune -f manifest.yaml -l app=nginx

Apply the configuration in manifest.yaml and delete all the other configmaps 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 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'.

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

$ apply -f FILENAME

Flags

Name Shorthand Default Usage
all false Select all resources in the namespace of the specified resource types.
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
cascade true If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] that contains the configuration to apply
force false Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
grace-period -1 Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
openapi-patch true If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
overwrite true Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration
prune false Automatically delete resource objects, including the uninitialized ones, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all.
prune-whitelist [] Overwrite the default whitelist with for --prune
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
timeout 0s The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object
validate false If true, use a schema to validate the input before sending it

edit-last-applied

Edit the last-applied-configuration annotations by type/name in YAML.

kubectl apply edit-last-applied deployment/nginx

Edit the last-applied-configuration annotations by file in JSON.

kubectl apply edit-last-applied -f deploy.yaml -o json

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 filenames as well as command line arguments, although the files you point to must be previously saved versions of resources.

The default format is YAML. To edit in JSON, specify "-o json".

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

$ edit-last-applied (RESOURCE/NAME | -f FILENAME)

Flags

Name Shorthand Default Usage
filename f [] Filename, directory, or URL to files to use to edit the resource
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
output o yaml Output format. One of: yaml|json.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
windows-line-endings false Defaults to the line ending native to your platform.

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

Execute set-last-applied against each configuration file in a directory.

kubectl apply set-last-applied -f path/

Set the last-applied-configuration of a resource to match the contents of a file, will create the annotation if it does not already exist.

kubectl apply set-last-applied -f deploy.yaml --create-annotation=true

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

$ set-last-applied -f FILENAME

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
create-annotation false Will create 'last-applied-configuration' annotations if current objects doesn't have one
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] Filename, directory, or URL to files that contains the last-applied-configuration annotations
output o Output format. One of: json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath|jsonpath-file.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

view-last-applied

View the last-applied-configuration annotations by type/name in YAML.

kubectl apply view-last-applied deployment/nginx

View the last-applied-configuration annotations by file in JSON

kubectl apply view-last-applied -f deploy.yaml -o json

View the latest last-applied-configuration annotations by type/name or file.

The default output will be printed to stdout in YAML format. One can use -o option to change output format.

Usage

$ view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)

Flags

Name Shorthand Default Usage
all false Select all resources in the namespace of the specified resource types
filename f [] Filename, directory, or URL to files that contains the last-applied-configuration annotations
output o yaml Output format. Must be one of yaml|json
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)

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 a pod identified by type and name in "pod.json"

kubectl annotate -f pod.json 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'

Update all pods in the namespace

kubectl annotate pods --all description='my frontend running nginx'

Update pod 'foo' only if the resource is unchanged from version 1.

kubectl annotate pods foo description='my frontend running nginx' --resource-version=1

Update pod 'foo' by removing an annotation named 'description' if it exists. # Does not require the --overwrite flag.

kubectl annotate pods foo description-

Update the annotations on one or more resources

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.

Use "kubectl api-resources" for a complete list of supported resources.

Usage

$ annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]

Flags

Name Shorthand Default Usage
all false Select all resources, including uninitialized ones, in the namespace of the specified resource types.
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
field-selector Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.
filename f [] Filename, directory, or URL to files identifying the resource to update the annotation
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
local false If true, annotation will NOT contact api-server but run locally.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath.
overwrite false If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
resource-version If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.
selector l Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

convert

Convert 'pod.yaml' to latest version and print to stdout.

kubectl convert -f pod.yaml

Convert the live state of the resource specified by 'pod.yaml' to the latest version # and print to stdout in JSON format.

kubectl convert -f pod.yaml --local -o json

Convert all files under current directory to latest version and create them all.

kubectl convert -f . | kubectl create -f -

Convert config files between different API versions. Both YAML and JSON formats are accepted.

The command takes filename, directory, or URL as input, and convert it into format of version specified by --output-version flag. If target version is not specified or not supported, convert to latest version.

The default output will be printed to stdout in YAML format. One can use -o option to change to output destination.

Usage

$ convert -f FILENAME

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
filename f [] Filename, directory, or URL to files to need to get converted.
local true If true, convert will NOT try to contact api-server but run locally.
output o yaml Output format. One of: json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
output-version Output the formatted object with the given group version (for ex: 'extensions/v1beta1').)
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it

edit

Edit the service named 'docker-registry':

kubectl edit svc/docker-registry

Use an alternative editor

KUBE_EDITOR="nano" kubectl edit svc/docker-registry

Edit the job 'myjob' in JSON using the v1 API format:

kubectl edit job.v1.batch/myjob -o json

Edit the deployment 'mydeployment' in YAML and save the modified config in its annotation:

kubectl edit deployment/mydeployment -o yaml --save-config

Edit a resource from the default editor.

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 filenames 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 default format is YAML. To edit in JSON, specify "-o json".

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

$ edit (RESOURCE/NAME | -f FILENAME)

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
filename f [] Filename, directory, or URL to files to use to edit the resource
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath.
output-patch false Output the patch if the resource is edited.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
validate false If true, use a schema to validate the input before sending it
windows-line-endings false Defaults to the line ending native to your platform.

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 all pods in the namespace

kubectl label pods --all status=unhealthy

Update a pod identified by the type and name in "pod.json"

kubectl label -f pod.json status=unhealthy

Update pod 'foo' only if the resource is unchanged from version 1.

kubectl label pods foo status=unhealthy --resource-version=1

Update pod 'foo' by removing a label named 'bar' if it exists. # Does not require the --overwrite flag.

kubectl label pods foo bar-

Update the labels on a resource.

Usage

$ label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]

Flags

Name Shorthand Default Usage
all false Select all resources, including uninitialized ones, in the namespace of the specified resource types
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
field-selector Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.
filename f [] Filename, directory, or URL to files identifying the resource to update the labels
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
list false If true, display the labels for a given resource.
local false If true, label will NOT contact api-server but run locally.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
overwrite false If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
resource-version If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.
selector l Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

patch

Update a container's image; spec.containers[*].name is required because it's a merge key.

kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

Update a container's image using a json patch with positional arrays.

kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

Update field(s) of a resource using strategic merge patch, a JSON merge patch, or a JSON patch.

JSON and YAML formats are accepted.

Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.

Usage

$ patch (-f FILENAME | TYPE NAME) -p PATCH

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] Filename, directory, or URL to files identifying the resource to update
local false If true, patch will operate on the content of the file, not the server-side resource.
output o Output format. One of: json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath-file|jsonpath.
patch p The patch to be applied to the resource JSON file.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
type strategic The type of patch being provided; one of [json merge strategic]

replace

Replace a pod using the data in pod.json.

kubectl replace -f ./pod.json

Replace a pod based on the JSON passed into stdin.

cat pod.json | kubectl replace -f -

Update a single-container pod's image version (tag) to v4

kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

Force replace, delete and then re-create the resource

kubectl replace --force -f ./pod.json

Replace a resource by filename or stdin.

JSON and YAML formats are accepted. If replacing an existing resource, the complete resource spec must be provided. This can be obtained by

$ kubectl get TYPE NAME -o yaml

Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.

Usage

$ replace -f FILENAME

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
cascade true If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.
filename f [] to use to replace the resource.
force false Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
grace-period -1 Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
timeout 0s The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object
validate false If true, use a schema to validate the input before sending it

rollout

Rollback to the previous deployment

kubectl rollout undo deployment/abc

Manage the rollout of a resource.

Valid resource types include:

Usage

$ rollout SUBCOMMAND


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.

kubectl rollout pause deployment/nginx

Mark the provided resource as 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

$ pause RESOURCE

Flags

Name Shorthand Default Usage
filename f [] Filename, directory, or URL to files identifying the resource to get from a server.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.

resume

Resume an already paused deployment

kubectl rollout resume deployment/nginx

Resume a paused resource

Paused resources will not be reconciled by a controller. By resuming a resource, we allow it to be reconciled again. Currently only deployments support being resumed.

Usage

$ resume RESOURCE

Flags

Name Shorthand Default Usage
filename f [] Filename, directory, or URL to files identifying the resource to get from a server.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.

set

Configure application resources

These commands help you make changes to existing application resources.

Usage

$ set SUBCOMMAND


env

Update deployment 'registry' with a new environment variable

kubectl set env deployment/registry STORAGE_DIR=/local

List the environment variables defined on a deployments 'sample-build'

kubectl set env deployment/sample-build --list

List the environment variables defined on all pods

kubectl set env pods --all --list

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

Update all containers in all replication controllers in the project to have ENV=prod

kubectl set env rc --all ENV=prod

Import environment from a secret

kubectl set env --from=secret/mysecret deployment/myapp

Import environment from a config map with a prefix

kubectl set env --from=configmap/myconfigmap --prefix=MYSQL_ deployment/myapp

Import specific keys from a config map

kubectl set env --keys=my-example-key --from=configmap/myconfigmap deployment/myapp

Remove the environment variable ENV from container 'c1' in all deployment configs

kubectl set env deployments --all --containers="c1" ENV-

Remove the environment variable ENV from a deployment definition on disk and # update the deployment config on the server

kubectl set env -f deploy.json ENV-

Set some of the local shell environment into a deployment config on the server

env | grep RAILS_ | kubectl set env -e - deployment/registry

Update environment variables on a pod template.

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.

Possible resources include (case insensitive):

pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs)

Usage

$ env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N

Flags

Name Shorthand Default Usage
all false If true, select all resources in the namespace of the specified resource types
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
containers c * The names of containers in the selected pod templates to change - may use wildcards
dry-run false If true, only print the object that would be sent, without sending it.
env e [] Specify a key-value pair for an environment variable to set into each container.
filename f [] Filename, directory, or URL to files the resource to update the env
from The name of a resource from which to inject environment variables
keys [] Comma-separated list of keys to import from specified resource
list false If true, display the environment and any changes in the standard format. this flag will removed when we have kubectl view env.
local false If true, set env will NOT contact api-server but run locally.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
overwrite true If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment.
prefix Prefix to append to variable names
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
resolve false If true, show secret or configmap references when listing variables
selector l Selector (label query) to filter on
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

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

Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'

kubectl set image deployments nginx=nginx:1.9.1 --all

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

Update existing container image(s) of resources.

Possible resources include (case insensitive): pod (po), deployment (deploy)

Usage

$ image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N

Flags

Name Shorthand Default Usage
all false Select all resources, including uninitialized ones, in the namespace of the specified resource types
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] Filename, directory, or URL to files identifying the resource to get from a server.
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
local false If true, set image will NOT contact api-server but run locally.
output o Output format. One of: json|yaml|name|go-template|go-template-file|templatefile|template|jsonpath|jsonpath-file.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

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

Remove the resource requests for resources on containers in nginx

kubectl set resources deployment nginx --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 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

$ resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]

Flags

Name Shorthand Default Usage
all false Select all resources, including uninitialized ones, in the namespace of the specified resource types
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
containers c * The names of containers in the selected pod templates to change, all containers are selected by default - may use wildcards
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] Filename, directory, or URL to files identifying the resource to get from a server.
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
limits The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.
local false If true, set resources will NOT contact api-server but run locally.
output o Output format. One of: json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
requests The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.
selector l Selector (label query) to filter on, not including uninitialized ones,supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

selector

set the labels and selector before creating a deployment/service pair.

kubectl create service clusterip my-svc --clusterip="None" -o yaml --dry-run | kubectl set selector --local -f - 'environment=qa' -o yaml | kubectl create -f -
kubectl create deployment my-dep -o yaml --dry-run | 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

$ selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]

Flags

Name Shorthand Default Usage
all false Select all resources in the namespace of the specified resource types
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
dry-run false If true, only print the object that would be sent, without sending it.
filename f [] identifying the resource.
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
output o Output format. One of: json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath|jsonpath-file.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R true Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
resource-version If non-empty, the selectors update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

wait

Usage

$ wait resource.group/name [--for=delete|--for condition=available]

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
filename f [] identifying the resource.
for The condition to wait on: [delete|condition=condition-name].
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath.
recursive R true Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
timeout 30s The length of time to wait before giving up. Zero means check once and don't wait, negative means wait for a week.

WORKING WITH APPS

This section contains commands for inspecting and debugging your applications.


describe

Describe a pod

kubectl describe pods/nginx

Describe a pod identified by type and name in "pod.json"

kubectl describe -f pod.json

Describe all pods

kubectl describe pods

Describe pods by label name=myLabel

kubectl describe po -l name=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).

kubectl describe pods frontend

Show details of a specific resource or group of resources

Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:

$ kubectl describe TYPE NAME_PREFIX

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.

Use "kubectl api-resources" for a complete list of supported resources.

Usage

$ describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)

Flags

Name Shorthand Default Usage
filename f [] Filename, directory, or URL to files containing the resource to describe
include-uninitialized false If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
selector l Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
show-events true If true, display events related to the described object.

exec

Get output from running 'date' from pod 123456-7890, using the first container by default

kubectl exec 123456-7890 date

Get output from running 'date' in ruby-container from pod 123456-7890

kubectl exec 123456-7890 -c ruby-container date

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 client

kubectl exec 123456-7890 -c ruby-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").

kubectl exec 123456-7890 -i -t -- ls -t /usr

Execute a command in a container.

Usage

$ exec POD [-c CONTAINER] -- COMMAND [args...]

Flags

Name Shorthand Default Usage
container c Container name. If omitted, the first container in the pod will be chosen
pod p Pod name
stdin i false Pass stdin to the container
tty t false Stdin is a TTY

logs

Return snapshot logs from pod nginx with only one container

kubectl logs nginx

Return snapshot logs from pod nginx with multi containers

kubectl logs nginx --all-containers=true

Return snapshot logs from all containers in pods defined by label app=nginx

kubectl logs -lapp=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 of the ruby container in pod web-1

kubectl logs -f -c ruby web-1

Display only the most recent 20 lines of output in pod nginx

kubectl logs --tail=20 nginx

Show all logs from pod nginx written in the last hour

kubectl logs --since=1h nginx

Return snapshot logs from first container of a job named hello

kubectl logs job/hello

Return snapshot logs from container nginx-1 of a deployment named nginx

kubectl logs deployment/nginx -c nginx-1

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

$ logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]

Flags

Name Shorthand Default Usage
all-containers false Get all containers's logs in the pod(s).
container c Print the logs of this container
follow f false Specify if the logs should be streamed.
interactive false If true, prompt the user for input when required.
limit-bytes 0 Maximum bytes of logs to return. Defaults to no limit.
pod-running-timeout 20s The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running
previous p false If true, print the logs for the previous instance of the container in a pod if it exists.
selector l Selector (label query) to filter on.
since 0s Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used.
since-time Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used.
tail -1 Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise 10, if a selector is provided.
timestamps false Include timestamps on each line in the log output

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

$ api-versions

KUBECTL SETTINGS AND USAGE


alpha

These commands correspond to alpha features that are not enabled in Kubernetes clusters by default.

Usage

$ alpha


diff

Diff resources included in pod.json. By default, it will diff LOCAL and LIVE versions

kubectl alpha diff -f pod.json

When one version is specified, diff that version against LIVE

cat service.yaml | kubectl alpha diff -f - MERGED

Or specify both versions

kubectl alpha diff -f pod.json -f service.yaml LAST LOCAL

Diff configurations specified by filename or stdin between their local, last-applied, live and/or "merged" versions.

LOCAL and LIVE versions are diffed by default. Other available keywords are MERGED and LAST.

Output is always YAML.

KUBERNETES EXTERNAL DIFF environment variable can be used to select your own diff command. By default, the "diff" command available in your path will be run with "-u" (unicode) and "-N" (treat new files as empty) options.

Usage

$ diff -f FILENAME

Flags

Name Shorthand Default Usage
filename f [] Filename, directory, or URL to files contains the configuration to diff
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.

api-resources

Print the supported API Resources

kubectl api-resources

Print the supported API Resources with more information

kubectl api-resources -o wide

Print the supported namespaced resources

kubectl api-resources --namespaced=true

Print the supported non-namespaced resources

kubectl api-resources --namespaced=false

Print the supported API Resources with specific APIGroup

kubectl api-resources --api-group=extensions

Print the supported API resources on the server

Usage

$ api-resources

Flags

Name Shorthand Default Usage
api-group Limit to resources in the specified API group.
cached false Use the cached list of resources if available.
namespaced true If false, non-namespaced resources will be returned, otherwise returning namespaced resources by default.
no-headers false When using the default or custom-column output format, don't print headers (default print headers).
output o Output format. One of: wide|name.
verbs [] Limit to resources that support the specified verbs.

completion

Installing bash completion on macOS using homebrew ## If running Bash 3.2 included with macOS

brew install bash-completion

or, if running Bash 4.1+

brew install bash-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 directory

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

Installing bash completion on Linux ## Load the kubectl completion code for bash into the current shell

source <(kubectl completion bash)

Write bash completion code to a file and source if from .bash_profile

kubectl completion bash > ~/.kube/completion.bash.inc
printf "

Kubectl shell completion

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

source <(kubectl completion zsh)

Set the kubectl completion code for zsh[1] to autoload on startup

kubectl completion zsh > "${fpath[1]}/_kubectl"

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: https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion

Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2

Usage

$ 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 a list of paths (normal path delimitting 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

$ config SUBCOMMAND


current-context

Display the current-context

kubectl config current-context

Displays the current-context

Usage

$ current-context


delete-cluster

Delete the minikube cluster

kubectl config delete-cluster minikube

Delete the specified cluster from the kubeconfig

Usage

$ delete-cluster NAME


delete-context

Delete the context for the minikube cluster

kubectl config delete-context minikube

Delete the specified context from the kubeconfig

Usage

$ delete-context NAME


get-clusters

List the clusters kubectl knows about

kubectl config get-clusters

Display clusters defined in the kubeconfig.

Usage

$ get-clusters


get-contexts

List all the contexts in your kubeconfig file

kubectl config get-contexts

Describe one context in your kubeconfig file.

kubectl config get-contexts my-context

Displays one or many contexts from the kubeconfig file.

Usage

$ get-contexts [(-o|--output=)name)]

Flags

Name Shorthand Default Usage
no-headers false When using the default or custom-column output format, don't print headers (default print headers).
output o Output format. One of: name

rename-context

Rename the context 'old-name' to 'new-name' in your kubeconfig file

kubectl config rename-context old-name new-name

Renames a context from the kubeconfig file.

CONTEXT _NAME is the context name that you wish change.

NEW _NAME is the new name you wish to set.

Note: In case the context being renamed is the 'current-context', this field will also be updated.

Usage

$ rename-context CONTEXT_NAME NEW_NAME


set

Sets an individual value in a kubeconfig file

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 wish to set. Binary fields such as 'certificate-authority-data' expect a base64 encoded string unless the --set-raw-bytes flag is used.

Usage

$ set PROPERTY_NAME PROPERTY_VALUE

Flags

Name Shorthand Default Usage
set-raw-bytes false When writing a []byte PROPERTY_VALUE, write the given string directly without base64 decoding.

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 --certificate-authority=~/.kube/e2e/kubernetes.ca.crt

Disable cert checking for the dev cluster entry

kubectl config set-cluster e2e --insecure-skip-tls-verify=true

Sets a cluster entry in kubeconfig.

Specifying a name that already exists will merge new fields on top of existing values for those fields.

Usage

$ set-cluster NAME [--server=server] [--certificate-authority=path/to/certificate/authority] [--insecure-skip-tls-verify=true]

Flags

Name Shorthand Default Usage
embed-certs false embed-certs for the cluster entry in kubeconfig

set-context

Set the user field on the gce context entry without touching other values

kubectl config set-context gce --user=cluster-admin

Sets a context entry in kubeconfig

Specifying a name that already exists will merge new fields on top of existing values for those fields.

Usage

$ set-context NAME [--cluster=cluster_nickname] [--user=user_nickname] [--namespace=namespace]


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

Set basic auth for the "cluster-admin" entry

kubectl config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif

Embed client certificate data in the "cluster-admin" entry

kubectl config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true

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-

Sets a user entry in kubeconfig

Specifying a name that already exists will merge new fields on top of existing values.

Client-certificate flags: --client-certificate=certfile --client-key=keyfile

Bearer token flags: --token=bearer_token

Basic auth flags: --username=basic_user --password=basic_password

Bearer token and basic auth are mutually exclusive.

Usage

$ 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]

Flags

Name Shorthand Default Usage
auth-provider Auth provider for the user entry in kubeconfig
auth-provider-arg [] 'key=value' arguments for the auth provider
embed-certs false Embed client cert/key for the user entry in kubeconfig
password password for the user entry in kubeconfig
username username for the user entry in kubeconfig

unset

Unset the current-context.

kubectl config unset current-context

Unset namespace in foo context.

kubectl config unset contexts.foo.namespace

Unsets an individual value in a kubeconfig file

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

$ unset PROPERTY_NAME


use-context

Use the context for the minikube cluster

kubectl config use-context minikube

Sets the current-context in a kubeconfig file

Usage

$ use-context CONTEXT_NAME


view

Show merged kubeconfig settings.

kubectl config view

Show merged kubeconfig settings and raw certificate data.

kubectl config view --raw

Get the password for the e2e user

kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

Display merged kubeconfig settings or a specified kubeconfig file.

You can use --output jsonpath={...} to extract specific values using a jsonpath expression.

Usage

$ view

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
flatten false Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files)
merge true Merge the full hierarchy of kubeconfig files
minify false Remove all information not used by current-context from the output
output o yaml Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath.
raw false Display raw byte data
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

options

Print flags inherited by all commands

kubectl options

Print the list of flags inherited by all commands

Usage

$ options


plugin

Runs a command-line plugin.

Plugins are subcommands that are not part of the major command-line distribution and can even be provided by third-parties. Please refer to the documentation and examples for more information about how to install and write your own plugins.

Usage

$ plugin NAME


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

$ version

Flags

Name Shorthand Default Usage
client c false Client version only (no server required).
output o One of 'yaml' or 'json'.
short false Print just the version number.

DEPRECATED COMMANDS


run-container

Start a single instance of nginx.

kubectl run nginx --image=nginx

Start a single instance of hazelcast and let the container expose port 5701 .

kubectl run hazelcast --image=hazelcast --port=5701

Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the container.

kubectl run hazelcast --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.

kubectl run hazelcast --image=nginx --labels="app=hazelcast,env=prod"

Start a replicated instance of nginx.

kubectl run nginx --image=nginx --replicas=5

Dry run. Print the corresponding API objects without creating them.

kubectl run nginx --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.

kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'

Start a pod of busybox and keep it in the foreground, don't restart it if it exits.

kubectl run -i -t busybox --image=busybox --restart=Never

Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.

kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>

Start the nginx container using a different command and custom arguments.

kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>

Start the perl container to compute π to 2000 places and print it out.

kubectl run pi --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.

kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

Create and run a particular image, possibly replicated.

Creates a deployment or job to manage the created container(s).

Usage

$ run-container

Flags

Name Shorthand Default Usage
allow-missing-template-keys true If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.
cascade true If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.
command false If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default.
dry-run false If true, only print the object that would be sent, without sending it.
env [] Environment variables to set in the container
expose false If true, a public, external service is created for the container(s) which are run
filename f [] to use to replace the resource.
force false Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
generator The name of the API generator to use, see http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list.
grace-period -1 Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
image The image for the container to run.
image-pull-policy The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server
labels l Comma separated labels to apply to the pod(s). Will override previous values.
limits The resource requirement limits for this container. For example, 'cpu=200m,memory=512Mi'. Note that server side components may assign limits depending on the server configuration, such as limit ranges.
output o Output format. One of: json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
overrides An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.
pod-running-timeout 1m0s The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running
port The port that this container exposes. If --expose is true, this is also the port used by the service that is created.
quiet false If true, suppress prompt messages.
record false Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.
recursive R false Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
replicas r 1 Number of replicas to create for this container. Default is 1.
requests The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.
restart Always The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created, if set to 'OnFailure' a job is created, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always', for CronJobs Never.
save-config false If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
schedule A schedule in the Cron format the job should be run with.
service-generator service/v2 The name of the generator to use for creating a service. Only used if --expose is true
service-overrides An inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true.
stdin i false Keep stdin open on the container(s) in the pod, even if nothing is attached.
template Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
timeout 0s The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object
tty t false Allocated a TTY for each container in the pod.