Handy kubectl commands to know¶
kubectl controls the Kubernetes cluster manager.
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
Basic Commands (Beginner):¶
create¶
Create a resource from a file or from stdin.
Examples:¶
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 using the v1 API format then create the resource using the edited data.
kubectl create -f docker-registry.yaml --edit --output-version=v1 -o json
Create a clusterrolebinding to make a service account a cluster-admin.
kubectl create clusterrolebinding monitoring-default-role --clusterrole=cluster-admin --serviceaccount=monitoring:default
Available Commands:¶
| clusterrole | Create a ClusterRole. |
| clusterrolebinding | Create a ClusterRoleBinding for a particular ClusterRole |
| configmap | Create a configmap from a local file, directory or literal value |
| deployment | Create a deployment with the specified name. |
| job | Create a job with the specified name. |
| namespace | Create a namespace with the specified name |
| poddisruptionbudget | Create a pod disruption budget with the specified name. |
| priorityclass | Create a priorityclass with the specified name. |
| quota | Create a quota with the specified name. |
| role | Create a role with single rule. |
| rolebinding | Create a RoleBinding for a particular Role or ClusterRole |
| secret | Create a secret using specified subcommand |
| service | Create a service using specified subcommand. |
| serviceaccount | Create a service account with the specified name |
expose¶
Expose a resource as a new Kubernetes service.
Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only the matchLabels component. Note that if no port is specified via –port and the exposed resource has multiple ports, all will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the resource it exposes.
Possible resources:¶
pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)
Examples:¶
Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
kubectl expose rc nginx --port=80 --target-port=8000
Create a service for a replication controller identified by type and name specified in “nginx-controller.yaml”, which serves on port 80 and connects to the containers on port 8000.
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000
Create a service for a pod valid-pod, which serves on port 444 with the name “frontend”
kubectl expose pod valid-pod --port=444 --name=frontend
Create a second service based on the above service, exposing the container port 8443 as port 443 with the name “nginx-https”
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https
Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named ‘video-stream’.
kubectl expose rc streamer --port=4100 --protocol=udp --name=video-stream
Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on port 8000.
kubectl expose rs nginx --port=80 --target-port=8000
Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.
kubectl expose deployment nginx --port=80 --target-port=8000
run¶
Create and run a particular image, possibly replicated.
Creates a deployment or job to manage the created container(s).
Examples:¶
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)'
set¶
Configure application resources
These commands help you make changes to existing application resources.
Available Commands:¶
| env | Update environment variables on a pod template |
| image | Update image of a pod template |
| resources | Update resource requests/limits on objects with pod templates |
| selector | Set the selector on a resource |
| serviceaccount | Update ServiceAccount of a resource |
| subject | Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding |
Usage:¶
kubectl set SUBCOMMAND [options]
run-container¶
See ‘run’.
Basic Commands (Intermediate):¶
get¶
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.
Valid resource types include:¶
- all
- certificatesigningrequests (aka ‘csr’)
- clusterrolebindings
- clusterroles
- componentstatuses (aka ‘cs’)
- configmaps (aka ‘cm’)
- controllerrevisions
- cronjobs
- customresourcedefinition (aka ‘crd’)
- daemonsets (aka ‘ds’)
- deployments (aka ‘deploy’)
- endpoints (aka ‘ep’)
- events (aka ‘ev’)
- horizontalpodautoscalers (aka ‘hpa’)
- ingresses (aka ‘ing’)
- jobs
- limitranges (aka ‘limits’)
- namespaces (aka ‘ns’)
- networkpolicies (aka ‘netpol’)
- nodes (aka ‘no’)
- persistentvolumeclaims (aka ‘pvc’)
- persistentvolumes (aka ‘pv’)
- poddisruptionbudgets (aka ‘pdb’)
- podpreset
- pods (aka ‘po’)
- podsecuritypolicies (aka ‘psp’)
- podtemplates
- replicasets (aka ‘rs’)
- replicationcontrollers (aka ‘rc’)
- resourcequotas (aka ‘quota’)
- rolebindings
- roles
- secrets
- serviceaccounts (aka ‘sa’)
- services (aka ‘svc’)
- statefulsets (aka ‘sts’)
- storageclasses (aka ‘sc’)
Examples:¶
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
kubectl get cs
List a single replication controller with specified NAME in ps output format.
kubectl get replicationcontroller web
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
List all resources with different types.
kubectl get all
explain¶
List the fields for supported resources
This command describes the fields associated with each supported API resource. Fields are identified via a simple JSONPath identifier:
<type>.<fieldName>[.<fieldName>]
Add the –recursive flag to display all of the fields at once without descriptions. Information about each field is retrieved from the server in OpenAPI format.
Valid resource types include:¶
- all
- certificatesigningrequests (aka ‘csr’)
- clusterrolebindings
- clusterroles
- componentstatuses (aka ‘cs’)
- configmaps (aka ‘cm’)
- controllerrevisions
- cronjobs
- customresourcedefinition (aka ‘crd’)
- daemonsets (aka ‘ds’)
- deployments (aka ‘deploy’)
- endpoints (aka ‘ep’)
- events (aka ‘ev’)
- horizontalpodautoscalers (aka ‘hpa’)
- ingresses (aka ‘ing’)
- jobs
- limitranges (aka ‘limits’)
- namespaces (aka ‘ns’)
- networkpolicies (aka ‘netpol’)
- nodes (aka ‘no’)
- persistentvolumeclaims (aka ‘pvc’)
- persistentvolumes (aka ‘pv’)
- poddisruptionbudgets (aka ‘pdb’)
- podpreset
- pods (aka ‘po’)
- podsecuritypolicies (aka ‘psp’)
- podtemplates
- replicasets (aka ‘rs’)
- replicationcontrollers (aka ‘rc’)
- resourcequotas (aka ‘quota’)
- rolebindings
- roles
- secrets
- serviceaccounts (aka ‘sa’)
- services (aka ‘svc’)
- statefulsets (aka ‘sts’)
- storageclasses (aka ‘sc’)
Examples:¶
Get the documentation of the resource and its fields
kubectl explain pods
Get the documentation of a specific field of a resource
kubectl explain pods.spec.containers
edit¶
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.
Examples:¶
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
delete¶
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.
Examples:¶
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
Deploy Commands:¶
rollout¶
Manage the rollout of a resource.
Valid resource types include:
- deployments
- daemonsets
- statefulsets
Examples:¶
Rollback to the previous deployment
kubectl rollout undo deployment/abc
Check the rollout status of a daemonset
kubectl rollout status daemonset/foo
Available Commands:¶
| history | View rollout history |
| pause | Mark the provided resource as paused |
| resume | Resume a paused resource |
| status | Show the status of the rollout |
| undo | Undo a previous rollout |
rolling-update¶
Perform a rolling update of the given ReplicationController.
Replaces the specified replication controller with a new replication controller by updating one pod at a time to use the new PodTemplate. The new-controller.json must specify the same namespace as the existing replication controller and overwrite at least one (common) label in its replicaSelector.
! http://kubernetes.io/images/docs/kubectl_rollingupdate.svg
Examples:¶
Update pods of frontend-v1 using new replication controller data in frontend-v2.json.
kubectl rolling-update frontend-v1 -f frontend-v2.json
Update pods of frontend-v1 using JSON data passed into stdin.
cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -
Update the pods of frontend-v1 to frontend-v2 by just changing the image, and switching the
# name of the replication controller.
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
Update the pods of frontend by just changing the image, and keeping the old name.
kubectl rolling-update frontend --image=image:v2
Abort and reverse an existing rollout in progress (from frontend-v1 to frontend-v2).
kubectl rolling-update frontend-v1 frontend-v2 --rollback
scale¶
Set a new size for a Deployment, ReplicaSet, Replication Controller, or StatefulSet.
Scale also allows users to specify one or more preconditions for the scale action.
If –current-replicas or –resource-version is specified, it is validated before the scale is attempted, and it is guaranteed that the precondition holds true when the scale is sent to the server.
Examples:¶
Scale a replicaset named ‘foo’ to 3.
kubectl scale --replicas=3 rs/foo
Scale a resource identified by type and name specified in “foo.yaml” to 3.
kubectl scale --replicas=3 -f foo.yaml
If the deployment named mysql’s current size is 2, scale mysql to 3.
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
Scale multiple replication controllers.
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
Scale statefulset named ‘web’ to 3.
kubectl scale --replicas=3 statefulset/web
autoscale¶
Creates an autoscaler that automatically chooses and sets the number of pods that run in a kubernetes cluster.
Looks up a Deployment, ReplicaSet, or ReplicationController by name and creates an autoscaler that uses the given resource as a reference. An autoscaler can automatically increase or decrease number of pods deployed within the system as needed.
Examples:¶
Auto scale a deployment “foo”, with the number of pods between 2 and 10, no target CPU utilization specified so a default autoscaling policy will be used:
kubectl autoscale deployment foo --min=2 --max=10
Auto scale a replication controller “foo”, with the number of pods between 1 and 5, target CPU utilization at 80%:
kubectl autoscale rc foo --max=5 --cpu-percent=80
Cluster Management Commands:¶
certificate¶
Modify certificate resources.
Available Commands:¶
| approve | Approve a certificate signing request |
| deny | Deny a certificate signing request |
Usage:¶
kubectl certificate SUBCOMMAND [options]
cluster-info¶
Display addresses of the master and services with label kubernetes.io/cluster-service=true To further debug and diagnose cluster problems, use ‘kubectl cluster-info dump’.
Available Commands:¶
| dump | Dump lots of relevant info for debugging and diagnosis |
top¶
Display Resource (CPU/Memory/Storage) usage.
The top command allows you to see the resource consumption for nodes or pods.
This command requires Heapster to be correctly configured and working on the server.
Available Commands:¶
| node | Display Resource (CPU/Memory/Storage) usage of nodes |
| pod | Display Resource (CPU/Memory/Storage) usage of pods |
Usage:¶
kubectl top [flags] [options]
drain¶
Drain node in preparation for maintenance.
The given node will be marked unschedulable to prevent new pods from arriving. ‘drain’ evicts the pods if the APIServer supports eviction (http://kubernetes.io/docs/admin/disruptions/). Otherwise, it will use normal DELETE to delete the pods. The ‘drain’ evicts or deletes all pods except mirror pods (which cannot be deleted through the API server). If there are DaemonSet-managed pods, drain will not proceed without –ignore-daemonsets, and regardless it will not delete any DaemonSet-managed pods, because those pods would be immediately replaced by the DaemonSet controller, which ignores unschedulable markings. If there are any pods that are neither mirror pods nor managed by ReplicationController, ReplicaSet, DaemonSet, StatefulSet or Job, then drain will not delete any pods unless you use –force. –force will also allow deletion to proceed if the managing resource of one or more pods is missing.
‘drain’ waits for graceful termination. You should not operate on the machine until the command completes.
When you are ready to put the node back into service, use kubectl uncordon, which will make the node schedulable again.
! http://kubernetes.io/images/docs/kubectl_drain.svg
Examples:¶
Drain node “foo”, even if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet on it.
kubectl drain foo --force
As above, but abort if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet, and use a grace period of 15 minutes.
kubectl drain foo --grace-period=900
taint¶
Update the taints on one or more nodes.
- A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect.
- The key must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 253 characters.
- Optionally, the key can begin with a DNS subdomain prefix and a single ‘/’, like example.com/my-app
- The value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 63 characters.
- The effect must be NoSchedule, PreferNoSchedule or NoExecute.
- Currently taint can only apply to node.
Examples:¶
Update node ‘foo’ with a taint with key ‘dedicated’ and value ‘special-user’ and effect ‘NoSchedule’. If a taint with that key and effect already exists, its value is replaced as specified.
kubectl taint nodes foo dedicated=special-user:NoSchedule
Remove from node ‘foo’ the taint with key ‘dedicated’ and effect ‘NoSchedule’ if one exists.
kubectl taint nodes foo dedicated:NoSchedule-
Remove from node ‘foo’ all the taints with key ‘dedicated’
kubectl taint nodes foo dedicated-
Add a taint with key ‘dedicated’ on nodes having label mylabel=X
kubectl taint node -l myLabel=X dedicated=foo:PreferNoSchedule
Troubleshooting and Debugging Commands:¶
describe¶
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.
Examples:¶
Describe a node
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
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
logs¶
Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.
Aliases:¶
logs, log
Examples:¶
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
attach¶
Attach to a process that is already running inside an existing container.
Examples:¶
Get output from running pod 123456-7890, using the first container by default
kubectl attach 123456-7890
Get output from ruby-container from pod 123456-7890
kubectl attach 123456-7890 -c ruby-container
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 attach 123456-7890 -c ruby-container -i -t
Get output from the first pod of a ReplicaSet named nginx
kubectl attach rs/nginx
exec¶
Execute a command in a container.
Examples:¶
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
port-forward¶
Forward one or more local ports to a pod.
Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to ‘pod’ if omitted.
If there are multiple pods matching the criteria, a pod will be selected automatically. The forwarding session ends when the selected pod terminates, and rerun of the command is needed to resume forwarding.
Examples:¶
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
kubectl port-forward pod/mypod 5000 6000
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the deployment
kubectl port-forward deployment/mydeployment 5000 6000
Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the service
kubectl port-forward service/myservice 5000 6000
Listen on port 8888 locally, forwarding to 5000 in the pod
kubectl port-forward pod/mypod 8888:5000
Listen on a random port locally, forwarding to 5000 in the pod
kubectl port-forward pod/mypod :5000
proxy¶
Creates a proxy server or application-level gateway between localhost and the Kubernetes API Server. It also allows serving static content over specified HTTP path. All incoming data enters through one port and gets forwarded to the remote kubernetes API Server port, except for the path matching the static content path.
Examples:¶
To proxy all of the kubernetes api and nothing else, use:
kubectl proxy --api-prefix=/
To proxy only part of the kubernetes api and also some static files:
kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
The above lets you ‘curl localhost:8001/api/v1/pods’.
To proxy the entire kubernetes api at a different root, use:
kubectl proxy --api-prefix=/custom/
The above lets you ‘curl localhost:8001/custom/api/v1/pods’
Run a proxy to kubernetes apiserver on port 8011, serving static content from ./local/www/
kubectl proxy --port=8011 --www=./local/www/
Run a proxy to kubernetes apiserver on an arbitrary local port. The chosen port for the server will be output to stdout.
kubectl proxy --port=0
Run a proxy to kubernetes apiserver, changing the api prefix to k8s-api This makes e.g. the pods api available at localhost:8001/k8s-api/v1/pods/
kubectl proxy --api-prefix=/k8s-api
cp¶
Copy files and directories to and from containers.
Examples:¶
!!!Important Note!!! Requires that the ‘tar’ binary is present in your container image. If ‘tar’ is not present, ‘kubectl cp’ will fail.
Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
auth¶
Inspect authorization
Available Commands:¶
| can-i | Check whether an action is allowed |
| reconcile | Reconciles rules for RBAC Role, RoleBinding, ClusterRole, and ClusterRole binding objects |
Usage:¶
kubectl auth [flags] [options]
Example:¶
Can I ‘get pods’ on namespace as a particular user
kubectl auth can-i get pods -n default --as plenderyou
Can I create a deployment on the default namespace as a particular user
kubectl auth can-i create deployment --namespace default --as plenderyou
Can I do anything on all namespaces, i.e. am I a cluster admin
kubectl auth can-i '*' '*' --all-namespaces
Advanced Commands:¶
apply¶
Apply a configuration to a resource by filename or stdin. The resource name must be specified. This resource will be created if it doesn’t exist yet. To use ‘apply’, always create the resource initially with either ‘apply’ or ‘create –save-config’.
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.
Examples:¶
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
Available Commands:¶
| edit-last-applied | Edit latest last-applied-configuration annotations of a resource/object |
| set-last-applied | Set the last-applied-configuration annotation on a live object to match the contents of a file. |
| view-last-applied | View latest last-applied-configuration annotations of a resource/object |
patch¶
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.
Examples:¶
Partially update a node using a strategic merge patch. Specify the patch as JSON.
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
Partially update a node using a strategic merge patch. Specify the patch as YAML.
kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'
Partially update a node identified by the type and name specified in “node.json” using strategic merge patch.
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
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":"newimage"}]'
replace¶
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.
Examples:¶
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
convert¶
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.
Examples:¶
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 -
Settings Commands:¶
label¶
Update the labels on a resource.
- A label key and value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to 63 characters each.
- Optionally, the key can begin with a DNS subdomain prefix and a single ‘/’, like example.com/my-app
- If –overwrite is true, then existing labels can be overwritten, otherwise attempting to overwrite a label will result in an error.
- If –resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
Examples:¶
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-
annotate¶
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.
Examples:¶
Update pod ‘foo’ with the annotation ‘description’ and the value ‘my frontend’. 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-
Other Commands:¶
api-versions¶
Print the supported API versions on the server, in the form of “group/version”
config¶
Modify kubeconfig files using subcommands like “kubectl config set current-context my-context”
The loading order follows these rules:
- If the –kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.
- If $KUBECONFIG environment variable is set, then it is used as 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.
- Otherwise, ${HOME}/.kube/config is used and no merging takes place.
Available Commands:¶
| current-context | Displays the current-context |
| delete-cluster | Delete the specified cluster from the kubeconfig |
| delete-context | Delete the specified context from the kubeconfig |
| get-clusters | Display clusters defined in the kubeconfig |
| get-contexts | Describe one or many contexts |
| rename-context | Renames a context from the kubeconfig file. |
| set | Sets an individual value in a kubeconfig file |
| set-cluster | Sets a cluster entry in kubeconfig |
| set-context | Sets a context entry in kubeconfig |
| set-credentials | Sets a user entry in kubeconfig |
| unset | Unsets an individual value in a kubeconfig file |
| use-context | Sets the current-context in a kubeconfig file |
| view | Display merged kubeconfig settings or a specified kubeconfig file |
plugin¶
Provides utilities for interacting with plugins.
Plugins provide extended functionality that is not part of the major command-line distribution. Please refer to the documentation and examples for more information about how write your own plugins.
Available Commands:¶
| list | list all visible plugin executables on a user’s PATH |
version¶
Print the client and server version information
kubectl version
Output
Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.3", GitCommit:"435f92c719f279a3a67808c80521ea17d5715c66", GitTreeState:"clean", BuildDate:"2018-11-27T01:14:37Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.0", GitCommit:"0ed33881dc4355495f623c6f22e7dd0b7632b7c0", GitTreeState:"clean", BuildDate:"2018-09-27T16:55:41Z", GoVersion:"go1.10.4", Compiler:"gc", Platform:"linux/amd64"}
Handy one-liners¶
Remove all pods that have been ‘Evicted’:
kubectl get po -a --all-namespaces -o json | \
jq '.items[] | select(.status.reason!=null) | select(.status.reason | contains("Evicted")) | \
"kubectl delete po \(.metadata.name) -n \(.metadata.namespace)"' | xargs -n 1 bash -c