Convert site to Hugo (#8316)
This commit converts content and layout to use Hugo.
This commit is contained in:
committed by
k8s-ci-robot
parent
7745f0e0c5
commit
7f3b633aa0
Executable
+5
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: "kubectl CLI"
|
||||
weight: 60
|
||||
---
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
---
|
||||
approvers:
|
||||
- bgrant0607
|
||||
- erictune
|
||||
- krousey
|
||||
- clove
|
||||
title: kubectl Cheat Sheet
|
||||
---
|
||||
|
||||
See also: [Kubectl Overview](/docs/reference/kubectl/overview/) and [JsonPath Guide](/docs/reference/kubectl/jsonpath).
|
||||
|
||||
## Kubectl Autocomplete
|
||||
|
||||
```console
|
||||
$ source <(kubectl completion bash) # setup autocomplete in bash, bash-completion package should be installed first.
|
||||
$ source <(kubectl completion zsh) # setup autocomplete in zsh
|
||||
```
|
||||
|
||||
## Kubectl Context and Configuration
|
||||
|
||||
Set which Kubernetes cluster `kubectl` communicates with and modifies configuration
|
||||
information. See [Authenticating Across Clusters with kubeconfig](/docs/tasks/access-application-cluster/configure-access-multiple-clusters/) documentation for
|
||||
detailed config file information.
|
||||
|
||||
```console
|
||||
$ kubectl config view # Show Merged kubeconfig settings.
|
||||
|
||||
# use multiple kubeconfig files at the same time and view merged config
|
||||
$ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view
|
||||
|
||||
# Get the password for the e2e user
|
||||
$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
|
||||
|
||||
$ kubectl config current-context # Display the current-context
|
||||
$ kubectl config use-context my-cluster-name # set the default context to my-cluster-name
|
||||
|
||||
# add a new cluster to your kubeconf that supports basic auth
|
||||
$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
|
||||
|
||||
# set a context utilizing a specific username and namespace.
|
||||
$ kubectl config set-context gce --user=cluster-admin --namespace=foo \
|
||||
&& kubectl config use-context gce
|
||||
```
|
||||
|
||||
## Creating Objects
|
||||
|
||||
Kubernetes manifests can be defined in json or yaml. The file extension `.yaml`,
|
||||
`.yml`, and `.json` can be used.
|
||||
|
||||
```console
|
||||
$ kubectl create -f ./my-manifest.yaml # create resource(s)
|
||||
$ kubectl create -f ./my1.yaml -f ./my2.yaml # create from multiple files
|
||||
$ kubectl create -f ./dir # create resource(s) in all manifest files in dir
|
||||
$ kubectl create -f https://git.io/vPieo # create resource(s) from url
|
||||
$ kubectl run nginx --image=nginx # start a single instance of nginx
|
||||
$ kubectl explain pods,svc # get the documentation for pod and svc manifests
|
||||
|
||||
# Create multiple YAML objects from stdin
|
||||
$ cat <<EOF | kubectl create -f -
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: busybox-sleep
|
||||
spec:
|
||||
containers:
|
||||
- name: busybox
|
||||
image: busybox
|
||||
args:
|
||||
- sleep
|
||||
- "1000000"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: busybox-sleep-less
|
||||
spec:
|
||||
containers:
|
||||
- name: busybox
|
||||
image: busybox
|
||||
args:
|
||||
- sleep
|
||||
- "1000"
|
||||
EOF
|
||||
|
||||
# Create a secret with several keys
|
||||
$ cat <<EOF | kubectl create -f -
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: mysecret
|
||||
type: Opaque
|
||||
data:
|
||||
password: $(echo -n "s33msi4" | base64)
|
||||
username: $(echo -n "jane" | base64)
|
||||
EOF
|
||||
|
||||
```
|
||||
|
||||
## Viewing, Finding Resources
|
||||
|
||||
```console
|
||||
# Get commands with basic output
|
||||
$ kubectl get services # List all services in the namespace
|
||||
$ kubectl get pods --all-namespaces # List all pods in all namespaces
|
||||
$ kubectl get pods -o wide # List all pods in the namespace, with more details
|
||||
$ kubectl get deployment my-dep # List a particular deployment
|
||||
$ kubectl get pods --include-uninitialized # List all pods in the namespace, including uninitialized ones
|
||||
|
||||
# Describe commands with verbose output
|
||||
$ kubectl describe nodes my-node
|
||||
$ kubectl describe pods my-pod
|
||||
|
||||
$ kubectl get services --sort-by=.metadata.name # List Services Sorted by Name
|
||||
|
||||
# List pods Sorted by Restart Count
|
||||
$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
|
||||
|
||||
# Get the version label of all pods with label app=cassandra
|
||||
$ kubectl get pods --selector=app=cassandra rc -o \
|
||||
jsonpath='{.items[*].metadata.labels.version}'
|
||||
|
||||
# Get all running pods in the namespace
|
||||
$ kubectl get pods --field-selector=status.phase=Running
|
||||
|
||||
# Get ExternalIPs of all nodes
|
||||
$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
|
||||
|
||||
# List Names of Pods that belong to Particular RC
|
||||
# "jq" command useful for transformations that are too complex for jsonpath, it can be found at https://stedolan.github.io/jq/
|
||||
$ sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
|
||||
$ echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
|
||||
|
||||
# Check which nodes are ready
|
||||
$ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
|
||||
&& kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
|
||||
|
||||
# List all Secrets currently in use by a pod
|
||||
$ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
|
||||
|
||||
# List Events sorted by timestamp
|
||||
$ kubectl get events --sort-by=.metadata.creationTimestamp
|
||||
```
|
||||
|
||||
## Updating Resources
|
||||
|
||||
```console
|
||||
$ kubectl rolling-update frontend-v1 -f frontend-v2.json # Rolling update pods of frontend-v1
|
||||
$ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # Change the name of the resource and update the image
|
||||
$ kubectl rolling-update frontend --image=image:v2 # Update the pods image of frontend
|
||||
$ kubectl rolling-update frontend-v1 frontend-v2 --rollback # Abort existing rollout in progress
|
||||
$ cat pod.json | kubectl replace -f - # Replace a pod based on the JSON passed into stdin
|
||||
|
||||
# Force replace, delete and then re-create the resource. Will cause a service outage.
|
||||
$ kubectl replace --force -f ./pod.json
|
||||
|
||||
# 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
|
||||
|
||||
# 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 -
|
||||
|
||||
$ kubectl label pods my-pod new-label=awesome # Add a Label
|
||||
$ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # Add an annotation
|
||||
$ kubectl autoscale deployment foo --min=2 --max=10 # Auto scale a deployment "foo"
|
||||
```
|
||||
|
||||
## Patching Resources
|
||||
|
||||
```console
|
||||
$ kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # Partially update a node
|
||||
|
||||
# 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"}]'
|
||||
|
||||
# Disable a deployment livenessProbe using a json patch with positional arrays
|
||||
$ kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'
|
||||
|
||||
# Add a new element to a positional array
|
||||
$ kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'
|
||||
```
|
||||
|
||||
## Editing Resources
|
||||
The edit any API resource in an editor.
|
||||
|
||||
```console
|
||||
$ kubectl edit svc/docker-registry # Edit the service named docker-registry
|
||||
$ KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor
|
||||
```
|
||||
|
||||
## Scaling Resources
|
||||
|
||||
```console
|
||||
$ kubectl scale --replicas=3 rs/foo # Scale a replicaset named 'foo' to 3
|
||||
$ kubectl scale --replicas=3 -f foo.yaml # Scale a resource specified in "foo.yaml" to 3
|
||||
$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # If the deployment named mysql's current size is 2, scale mysql to 3
|
||||
$ kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Scale multiple replication controllers
|
||||
```
|
||||
|
||||
## Deleting Resources
|
||||
|
||||
```console
|
||||
$ kubectl delete -f ./pod.json # Delete a pod using the type and name specified in pod.json
|
||||
$ kubectl delete pod,service baz foo # Delete pods and services with same names "baz" and "foo"
|
||||
$ kubectl delete pods,services -l name=myLabel # Delete pods and services with label name=myLabel
|
||||
$ kubectl delete pods,services -l name=myLabel --include-uninitialized # Delete pods and services, including uninitialized ones, with label name=myLabel
|
||||
$ kubectl -n my-ns delete po,svc --all # Delete all pods and services, including uninitialized ones, in namespace my-ns,
|
||||
```
|
||||
|
||||
## Interacting with running Pods
|
||||
|
||||
```console
|
||||
$ kubectl logs my-pod # dump pod logs (stdout)
|
||||
$ kubectl logs my-pod -c my-container # dump pod container logs (stdout, multi-container case)
|
||||
$ kubectl logs -f my-pod # stream pod logs (stdout)
|
||||
$ kubectl logs -f my-pod -c my-container # stream pod container logs (stdout, multi-container case)
|
||||
$ kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell
|
||||
$ kubectl attach my-pod -i # Attach to Running Container
|
||||
$ kubectl port-forward my-pod 5000:6000 # Listen on port 5000 on the local machine and forward to port 6000 on my-pod
|
||||
$ kubectl exec my-pod -- ls / # Run command in existing pod (1 container case)
|
||||
$ kubectl exec my-pod -c my-container -- ls / # Run command in existing pod (multi-container case)
|
||||
$ kubectl top pod POD_NAME --containers # Show metrics for a given pod and its containers
|
||||
```
|
||||
|
||||
## Interacting with Nodes and Cluster
|
||||
|
||||
```console
|
||||
$ kubectl cordon my-node # Mark my-node as unschedulable
|
||||
$ kubectl drain my-node # Drain my-node in preparation for maintenance
|
||||
$ kubectl uncordon my-node # Mark my-node as schedulable
|
||||
$ kubectl top node my-node # Show metrics for a given node
|
||||
$ kubectl cluster-info # Display addresses of the master and services
|
||||
$ kubectl cluster-info dump # Dump current cluster state to stdout
|
||||
$ kubectl cluster-info dump --output-directory=/path/to/cluster-state # Dump current cluster state to /path/to/cluster-state
|
||||
|
||||
# If a taint with that key and effect already exists, its value is replaced as specified.
|
||||
$ kubectl taint nodes foo dedicated=special-user:NoSchedule
|
||||
```
|
||||
|
||||
## Resource types
|
||||
|
||||
The following table includes a list of all the supported resource types and their abbreviated aliases:
|
||||
|
||||
Resource type | Abbreviated alias
|
||||
-------------------- | --------------------
|
||||
`all` |
|
||||
`certificatesigningrequests` |`csr`
|
||||
`clusterrolebindings` |
|
||||
`clusterroles` |
|
||||
`componentstatuses` |`cs`
|
||||
`configmaps` |`cm`
|
||||
`controllerrevisions` |
|
||||
`cronjobs` |
|
||||
`customresourcedefinition` |`crd`, `crds`
|
||||
`daemonsets` |`ds`
|
||||
`deployments` |`deploy`
|
||||
`endpoints` |`ep`
|
||||
`events` |`ev`
|
||||
`horizontalpodautoscalers` |`hpa`
|
||||
`ingresses` |`ing`
|
||||
`jobs` |
|
||||
`limitranges` |`limits`
|
||||
`namespaces` |`ns`
|
||||
`networkpolicies` |`netpol`
|
||||
`nodes` |`no`
|
||||
`persistentvolumeclaims` |`pvc`
|
||||
`persistentvolumes` |`pv`
|
||||
`poddisruptionbudgets` |`pdb`
|
||||
`podpreset` |
|
||||
`pods` |`po`
|
||||
`podsecuritypolicies` |`psp`
|
||||
`podtemplates` |
|
||||
`replicasets` |`rs`
|
||||
`replicationcontrollers` |`rc`
|
||||
`resourcequotas` |`quota`
|
||||
`rolebindings` |
|
||||
`roles` |
|
||||
`secrets` |
|
||||
`serviceaccount` |`sa`
|
||||
`services` |`svc`
|
||||
`statefulsets` |`sts`
|
||||
`storageclasses` |`sc`
|
||||
|
||||
### Formatting output
|
||||
|
||||
To output details to your terminal window in a specific format, you can add either the `-o` or `-output` flags to a supported `kubectl` command.
|
||||
|
||||
Output format | Description
|
||||
--------------| -----------
|
||||
`-o=custom-columns=<spec>` | Print a table using a comma separated list of custom columns
|
||||
`-o=custom-columns-file=<filename>` | Print a table using the custom columns template in the `<filename>` file
|
||||
`-o=json` | Output a JSON formatted API object
|
||||
`-o=jsonpath=<template>` | Print the fields defined in a [jsonpath](/docs/reference/kubectl/jsonpath) expression
|
||||
`-o=jsonpath-file=<filename>` | Print the fields defined by the [jsonpath](/docs/reference/kubectl/jsonpath) expression in the `<filename>` file
|
||||
`-o=name` | Print only the resource name and nothing else
|
||||
`-o=wide` | Output in the plain-text format with any additional information, and for pods, the node name is included
|
||||
`-o=yaml` | Output a YAML formatted API object
|
||||
|
||||
### Kubectl output verbosity and debugging
|
||||
|
||||
Kubectl verbosity is controlled with the `-v` or `--v` flags followed by an integer representing the log level. General Kubernetes logging conventions and the associated log levels are described [here](https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md).
|
||||
|
||||
Verbosity | Description
|
||||
--------------| -----------
|
||||
`--v=0` | Generally useful for this to ALWAYS be visible to an operator.
|
||||
`--v=1` | A reasonable default log level if you don't want verbosity.
|
||||
`--v=2` | Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems.
|
||||
`--v=3` | Extended information about changes.
|
||||
`--v=4` | Debug level verbosity.
|
||||
`--v=6` | Display requested resources.
|
||||
`--v=7` | Display HTTP request headers.
|
||||
`--v=8` | Display HTTP request contents.
|
||||
`--v=9` | Display HTTP request contents without truncation of contents.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
approvers:
|
||||
- bgrant0607
|
||||
- janetkuo
|
||||
title: kubectl Usage Conventions
|
||||
---
|
||||
|
||||
{{< toc >}}
|
||||
|
||||
## Using `kubectl` in Reusable Scripts
|
||||
|
||||
For a stable output in a script:
|
||||
|
||||
* Request one of the machine-oriented output forms, such as `-o name`, `-o json`, `-o yaml`, `-o go-template`, or `-o jsonpath`
|
||||
* Specify `--output-version`, because the output forms use a particular API version to output the resource with the exception of `-o name` output form
|
||||
* Specify `--generator` to pin to a specific behavior forever when you use generator-based commands such as `kubectl run` or `kubectl expose`
|
||||
* Don't rely on context, preferences, or other implicit states.
|
||||
|
||||
## Best Practices
|
||||
|
||||
### `kubectl run`
|
||||
|
||||
For `kubectl run` to satisfy infrastructure as code:
|
||||
|
||||
* Tag the image with a version-specific tag and don't move that tag to a new version. For example, use `:v1234`, `v1.2.3`, `r03062016-1-4`, rather than `:latest` (For more information, see [Best Practices for Configuration](/docs/concepts/configuration/overview/#container-images)).
|
||||
* Capture the parameters in a checked-in script, or at least use `--record` to annotate the created objects with the command line for an image that is lightly parameterized.
|
||||
* Check in the script for an image that is heavily parameterized.
|
||||
* Switch to configuration files checked into source control for features that are needed, but not expressible via `kubectl run` flags.
|
||||
* Pin to a specific [generator](#generators) version, such as `kubectl run --generator=deployment/v1beta1`.
|
||||
|
||||
#### Generators
|
||||
|
||||
You can generate the following resources in `kubectl run`using `--generator` flag:
|
||||
|
||||
* Pod - use `run-pod/v1`.
|
||||
* Replication controller - use `run/v1`.
|
||||
* Deployment - use `extensions/v1beta1` and for an endpoint - use `deployment/v1beta1` (default).
|
||||
* Deployment - use `apps/v1beta1` and for an endpoint - use `deployment/apps.v1beta1` (recommended).
|
||||
* Job - use `job/v1`.
|
||||
* CronJob - use `batch/v1beta1`and for an endpoint - use `cronjob/v1beta1`(default).
|
||||
* CronJob - use`batch/v2alpha1` and for an endpoint - use `cronjob/v2alpha1` (deprecated).
|
||||
|
||||
If you do not specify a generator flag, other flags prompt you to use a specific generator. The following table lists the flags that force you to use specific generators, depending on the version of the cluster:
|
||||
|
||||
| Generated Resource | Cluster v1.4 and later | Cluster v1.3 | Cluster v1.2 | Cluster v1.1 and earlier |
|
||||
|:----------------------:|------------------------|-----------------------|--------------------------------------------|--------------------------------------------|
|
||||
| Pod | `--restart=Never` | `--restart=Never` | `--generator=run-pod/v1` | `--restart=OnFailure` OR `--restart=Never` |
|
||||
| Replication Controller | `--generator=run/v1` | `--generator=run/v1` | `--generator=run/v1` | `--restart=Always` |
|
||||
| Deployment | `--restart=Always` | `--restart=Always` | `--restart=Always` | N/A |
|
||||
| Job | `--restart=OnFailure` | `--restart=OnFailure` | `--restart=OnFailure` OR `--restart=Never` | N/A |
|
||||
| Cron Job | `--schedule=<cron>` | N/A | N/A | N/A |
|
||||
|
||||
**Note:** These flags use a default generator only when you have not specified
|
||||
any flag. This means that when you combine `--generator` with other flags the generator that you specified later does not change. For example, in a cluster v1.4, if you initially specify
|
||||
`--restart=Always`, a Deployment is created; if you later specify `--restart=Always`
|
||||
and `--generator=run/v1`, a Replication Controller is created.
|
||||
This enables you to pin to a specific behavior with the generator,
|
||||
even when the default generator is changed later.
|
||||
|
||||
The flags set the generator in the following order: first the schedule flag then restart policy and finally the generator.
|
||||
|
||||
To check the final resource that was created, use `--dry-run`
|
||||
flag, which provides the object to be submitted to the cluster.
|
||||
|
||||
|
||||
### `kubectl apply`
|
||||
|
||||
* When you use `kubectl apply` to update resources, always create resources initially using `kubectl apply` or using `--save-config`. See [managing resources with kubectl apply](/docs/concepts/cluster-administration/manage-deployment/#kubectl-apply) for more information.
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
approvers:
|
||||
- bgrant0607
|
||||
- brendandburns
|
||||
- thockin
|
||||
title: kubectl for Docker Users
|
||||
---
|
||||
|
||||
You can use the Kubernetes command line tool kubectl to interact with the api. You can use kubectl if you are familiar with docker-cli. However, there are a few differences in the docker-cli commands and the kubectl commands. Each of the following section details a docker subcommand and explains the kubectl equivalent.
|
||||
|
||||
{{< toc >}}
|
||||
|
||||
#### docker run
|
||||
|
||||
To run an nginx Deployment and expose the Deployment, see [kubectl run](/docs/reference/generated/kubectl/kubectl-commands/#run).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker run -d --restart=always -e DOMAIN=cluster --name nginx-app -p 80:80 nginx
|
||||
55c103fa129692154a7652490236fee9be47d70a8dd562281ae7d2f9a339a6db
|
||||
|
||||
$ docker ps
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
55c103fa1296 nginx "nginx -g 'daemon of…" 9 seconds ago Up 9 seconds 0.0.0.0:80->80/tcp nginx-app
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
# start the pod running nginx
|
||||
$ kubectl run --image=nginx nginx-app --port=80 --env="DOMAIN=cluster"
|
||||
deployment "nginx-app" created
|
||||
```
|
||||
|
||||
{{< note >}}
|
||||
**Note:** `kubectl` commands print the type and name of the resource created or mutated, which can then be used in subsequent commands. You can expose a new Service after a Deployment is created.
|
||||
{{< /note >}}
|
||||
|
||||
```shell
|
||||
# expose a port through with a service
|
||||
$ kubectl expose deployment nginx-app --port=80 --name=nginx-http
|
||||
service "nginx-http" exposed
|
||||
```
|
||||
|
||||
By using kubectl, you can create a [Deployment](/docs/concepts/workloads/controllers/deployment/) to ensure that N pods are running nginx, where N is the number of replicas stated in the spec and defaults to 1. You can also create a [service](/docs/concepts/services-networking/service/) with a selector that matches the pod labels. For more information, see [Use a Service to Access an Application in a Cluster](/docs/tasks/access-application-cluster/service-access-application-cluster).
|
||||
|
||||
By default images run in the background, similar to `docker run -d ...`. To run things in the foreground, use:
|
||||
|
||||
```shell
|
||||
kubectl run [-i] [--tty] --attach <name> --image=<image>
|
||||
```
|
||||
|
||||
Unlike `docker run ...`, if you specify `--attach`, then you attach `stdin`, `stdout` and `stderr`. You cannot control which streams are attached (`docker -a ...`).
|
||||
To detach from the container, you can type the escape sequence Ctrl+P followed by Ctrl+Q.
|
||||
|
||||
Because the kubectl run command starts a Deployment for the container, the Deployment restarts if you terminate the attached process by using Ctrl+C, unlike `docker run -it`.
|
||||
To destroy the Deployment and its pods you need to run `kubectl delete deployment <name>`.
|
||||
|
||||
#### docker ps
|
||||
|
||||
To list what is currently running, see [kubectl get](/docs/reference/generated/kubectl/kubectl-commands/#get).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker ps -a
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
14636241935f ubuntu:16.04 "echo test" 5 seconds ago Exited (0) 5 seconds ago cocky_fermi
|
||||
55c103fa1296 nginx "nginx -g 'daemon of…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp nginx-app
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl get po -a
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
nginx-app-8df569cb7-4gd89 1/1 Running 0 3m
|
||||
ubuntu 0/1 Completed 0 20s
|
||||
```
|
||||
|
||||
#### docker attach
|
||||
|
||||
To attach a process that is already running in a container, see [kubectl attach](/docs/reference/generated/kubectl/kubectl-commands/#attach).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker ps
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
55c103fa1296 nginx "nginx -g 'daemon of…" 5 minutes ago Up 5 minutes 0.0.0.0:80->80/tcp nginx-app
|
||||
|
||||
$ docker attach 55c103fa1296
|
||||
...
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl get pods
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
nginx-app-5jyvm 1/1 Running 0 10m
|
||||
|
||||
$ kubectl attach -it nginx-app-5jyvm
|
||||
...
|
||||
```
|
||||
|
||||
To detach from the container, you can type the escape sequence Ctrl+P followed by Ctrl+Q.
|
||||
|
||||
#### docker exec
|
||||
|
||||
To execute a command in a container, see [kubectl exec](/docs/reference/generated/kubectl/kubectl-commands/#exec).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker ps
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
55c103fa1296 nginx "nginx -g 'daemon of…" 6 minutes ago Up 6 minutes 0.0.0.0:80->80/tcp nginx-app
|
||||
|
||||
$ docker exec 55c103fa1296 cat /etc/hostname
|
||||
55c103fa1296
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl get po
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
nginx-app-5jyvm 1/1 Running 0 10m
|
||||
|
||||
$ kubectl exec nginx-app-5jyvm -- cat /etc/hostname
|
||||
nginx-app-5jyvm
|
||||
```
|
||||
|
||||
To use interactive commands.
|
||||
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker exec -ti 55c103fa1296 /bin/sh
|
||||
# exit
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl exec -ti nginx-app-5jyvm -- /bin/sh
|
||||
# exit
|
||||
```
|
||||
|
||||
For more information, see [Get a Shell to a Running Container](/docs/tasks/debug-application-cluster/get-shell-running-container/).
|
||||
|
||||
#### docker logs
|
||||
|
||||
To follow stdout/stderr of a process that is running, see [kubectl logs](/docs/reference/generated/kubectl/kubectl-commands/#logs).
|
||||
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker logs -f a9e
|
||||
192.168.9.1 - - [14/Jul/2015:01:04:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.35.0" "-"
|
||||
192.168.9.1 - - [14/Jul/2015:01:04:03 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.35.0" "-"
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl logs -f nginx-app-zibvs
|
||||
10.240.63.110 - - [14/Jul/2015:01:09:01 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
|
||||
10.240.63.110 - - [14/Jul/2015:01:09:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
|
||||
```
|
||||
|
||||
There is a slight difference between pods and containers; by default pods do not terminate if their processes exit. Instead the pods restart the process. This is similar to the docker run option `--restart=always` with one major difference. In docker, the output for each invocation of the process is concatenated, but for Kubernetes, each invocation is separate. To see the output from a previous run in Kubernetes, do this:
|
||||
|
||||
```shell
|
||||
$ kubectl logs --previous nginx-app-zibvs
|
||||
10.240.63.110 - - [14/Jul/2015:01:09:01 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
|
||||
10.240.63.110 - - [14/Jul/2015:01:09:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
|
||||
```
|
||||
|
||||
For more information, see [Logging Architecture](/docs/concepts/cluster-administration/logging/).
|
||||
|
||||
#### docker stop and docker rm
|
||||
|
||||
To stop and delete a running process, see [kubectl delete](/docs/reference/generated/kubectl/kubectl-commands/#delete).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker ps
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
a9ec34d98787 nginx "nginx -g 'daemon of" 22 hours ago Up 22 hours 0.0.0.0:80->80/tcp, 443/tcp nginx-app
|
||||
|
||||
$ docker stop a9ec34d98787
|
||||
a9ec34d98787
|
||||
|
||||
$ docker rm a9ec34d98787
|
||||
a9ec34d98787
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl get deployment nginx-app
|
||||
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
|
||||
nginx-app 1 1 1 1 2m
|
||||
|
||||
$ kubectl get po -l run=nginx-app
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
nginx-app-2883164633-aklf7 1/1 Running 0 2m
|
||||
|
||||
$ kubectl delete deployment nginx-app
|
||||
deployment "nginx-app" deleted
|
||||
|
||||
$ kubectl get po -l run=nginx-app
|
||||
# Return nothing
|
||||
```
|
||||
|
||||
{{< note >}}
|
||||
**Note:** When you use kubectl, you don't delete the pod directly.You have to fiirst delete the Deployment that owns the pod. If you delete the pod directly, the Deployment recreates the pod.
|
||||
{{< /note >}}
|
||||
|
||||
#### docker login
|
||||
|
||||
There is no direct analog of `docker login` in kubectl. If you are interested in using Kubernetes with a private registry, see [Using a Private Registry](/docs/concepts/containers/images/#using-a-private-registry).
|
||||
|
||||
#### docker version
|
||||
|
||||
To get the version of client and server, see [kubectl version](/docs/reference/generated/kubectl/kubectl-commands/#version).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker version
|
||||
Client version: 1.7.0
|
||||
Client API version: 1.19
|
||||
Go version (client): go1.4.2
|
||||
Git commit (client): 0baf609
|
||||
OS/Arch (client): linux/amd64
|
||||
Server version: 1.7.0
|
||||
Server API version: 1.19
|
||||
Go version (server): go1.4.2
|
||||
Git commit (server): 0baf609
|
||||
OS/Arch (server): linux/amd64
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl version
|
||||
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.9+a3d1dfa6f4335", GitCommit:"9b77fed11a9843ce3780f70dd251e92901c43072", GitTreeState:"dirty", BuildDate:"2017-08-29T20:32:58Z", OpenPaasKubernetesVersion:"v1.03.02", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
|
||||
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.9+a3d1dfa6f4335", GitCommit:"9b77fed11a9843ce3780f70dd251e92901c43072", GitTreeState:"dirty", BuildDate:"2017-08-29T20:32:58Z", OpenPaasKubernetesVersion:"v1.03.02", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
|
||||
```
|
||||
|
||||
#### docker info
|
||||
|
||||
To get miscellaneous information about the environment and configuration, see [kubectl cluster-info](/docs/reference/generated/kubectl/kubectl-commands/#cluster-info).
|
||||
|
||||
docker:
|
||||
|
||||
```shell
|
||||
$ docker info
|
||||
Containers: 40
|
||||
Images: 168
|
||||
Storage Driver: aufs
|
||||
Root Dir: /usr/local/google/docker/aufs
|
||||
Backing Filesystem: extfs
|
||||
Dirs: 248
|
||||
Dirperm1 Supported: false
|
||||
Execution Driver: native-0.2
|
||||
Logging Driver: json-file
|
||||
Kernel Version: 3.13.0-53-generic
|
||||
Operating System: Ubuntu 14.04.2 LTS
|
||||
CPUs: 12
|
||||
Total Memory: 31.32 GiB
|
||||
Name: k8s-is-fun.mtv.corp.google.com
|
||||
ID: ADUV:GCYR:B3VJ:HMPO:LNPQ:KD5S:YKFQ:76VN:IANZ:7TFV:ZBF4:BYJO
|
||||
WARNING: No swap limit support
|
||||
```
|
||||
|
||||
kubectl:
|
||||
|
||||
```shell
|
||||
$ kubectl cluster-info
|
||||
Kubernetes master is running at https://108.59.85.141
|
||||
KubeDNS is running at https://108.59.85.141/api/v1/namespaces/kube-system/services/kube-dns/proxy
|
||||
kubernetes-dashboard is running at https://108.59.85.141/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy
|
||||
Grafana is running at https://108.59.85.141/api/v1/namespaces/kube-system/services/monitoring-grafana/proxy
|
||||
Heapster is running at https://108.59.85.141/api/v1/namespaces/kube-system/services/monitoring-heapster/proxy
|
||||
InfluxDB is running at https://108.59.85.141/api/v1/namespaces/kube-system/services/monitoring-influxdb/proxy
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: JSONPath Support
|
||||
---
|
||||
|
||||
JSONPath template is composed of JSONPath expressions enclosed by {}.
|
||||
And we add three functions in addition to the original JSONPath syntax:
|
||||
|
||||
1. The `$` operator is optional since the expression always starts from the root object by default.
|
||||
2. We can use `""` to quote text inside JSONPath expressions.
|
||||
3. We can use `range` operator to iterate lists.
|
||||
4. We can use negative slice indices to step backwards through a list. Negative indices do not "wrap around" a list. They are valid as long as `-index + listLength >= 0`.
|
||||
|
||||
The result object is printed as its String() function.
|
||||
|
||||
Given the input:
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": "List",
|
||||
"items":[
|
||||
{
|
||||
"kind":"None",
|
||||
"metadata":{"name":"127.0.0.1"},
|
||||
"status":{
|
||||
"capacity":{"cpu":"4"},
|
||||
"addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}]
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind":"None",
|
||||
"metadata":{"name":"127.0.0.2"},
|
||||
"status":{
|
||||
"capacity":{"cpu":"8"},
|
||||
"addresses":[
|
||||
{"type": "LegacyHostIP", "address":"127.0.0.2"},
|
||||
{"type": "another", "address":"127.0.0.3"}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"users":[
|
||||
{
|
||||
"name": "myself",
|
||||
"user": {}
|
||||
},
|
||||
{
|
||||
"name": "e2e",
|
||||
"user": {"username": "admin", "password": "secret"}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Function | Description | Example | Result
|
||||
---------|--------------------|--------------------|------------------
|
||||
text | the plain text | kind is {.kind} | kind is List
|
||||
@ | the current object | {@} | the same as input
|
||||
. or [] | child operator | {.kind} or {['kind']}| List
|
||||
.. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e
|
||||
* | wildcard. Get all objects| {.items[*].metadata.name} | [127.0.0.1 127.0.0.2]
|
||||
[start:end :step] | subscript operator | {.users[0].name}| myself
|
||||
[,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
|
||||
?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
|
||||
range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
|
||||
'' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2
|
||||
|
||||
Below are some examples using jsonpath:
|
||||
|
||||
```shell
|
||||
$ kubectl get pods -o json
|
||||
$ kubectl get pods -o=jsonpath='{@}'
|
||||
$ kubectl get pods -o=jsonpath='{.items[0]}'
|
||||
$ kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
|
||||
$ kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
|
||||
```
|
||||
@@ -0,0 +1,344 @@
|
||||
---
|
||||
approvers:
|
||||
- bgrant0607
|
||||
- hw-qiaolei
|
||||
title: Overview of kubectl
|
||||
---
|
||||
|
||||
`kubectl` is a command line interface for running commands against Kubernetes clusters. This overview covers `kubectl` syntax, describes the command operations, and provides common examples. For details about each command, including all the supported flags and subcommands, see the [kubectl](/docs/user-guide/kubectl/) reference documentation. For installation instructions see [installing kubectl](/docs/tasks/kubectl/install/).
|
||||
|
||||
## Syntax
|
||||
|
||||
Use the following syntax to run `kubectl` commands from your terminal window:
|
||||
|
||||
```shell
|
||||
kubectl [command] [TYPE] [NAME] [flags]
|
||||
```
|
||||
|
||||
where `command`, `TYPE`, `NAME`, and `flags` are:
|
||||
|
||||
* `command`: Specifies the operation that you want to perform on one or more resources, for example `create`, `get`, `describe`, `delete`.
|
||||
|
||||
* `TYPE`: Specifies the [resource type](#resource-types). Resource types are case-insensitive and you can specify the singular, plural, or abbreviated forms. For example, the following commands produce the same output:
|
||||
|
||||
$ kubectl get pod pod1
|
||||
$ kubectl get pods pod1
|
||||
$ kubectl get po pod1
|
||||
|
||||
* `NAME`: Specifies the name of the resource. Names are case-sensitive. If the name is omitted, details for all resources are displayed, for example `$ kubectl get pods`.
|
||||
|
||||
When performing an operation on multiple resources, you can specify each resource by type and name or specify one or more files:
|
||||
|
||||
* To specify resources by type and name:
|
||||
|
||||
* To group resources if they are all the same type: `TYPE1 name1 name2 name<#>`.<br/>
|
||||
Example: `$ kubectl get pod example-pod1 example-pod2`
|
||||
|
||||
* To specify multiple resource types individually: `TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>`.<br/>
|
||||
Example: `$ kubectl get pod/example-pod1 replicationcontroller/example-rc1`
|
||||
|
||||
* To specify resources with one or more files: `-f file1 -f file2 -f file<#>`
|
||||
|
||||
* [Use YAML rather than JSON](/docs/concepts/configuration/overview/#general-config-tips) since YAML tends to be more user-friendly, especially for configuration files.<br/>
|
||||
Example: `$ kubectl get pod -f ./pod.yaml`
|
||||
* `flags`: Specifies optional flags. For example, you can use the `-s` or `--server` flags to specify the address and port of the Kubernetes API server.<br/>
|
||||
**Important**: Flags that you specify from the command line override default values and any corresponding environment variables.
|
||||
|
||||
If you need help, just run `kubectl help` from the terminal window.
|
||||
|
||||
## Operations
|
||||
|
||||
The following table includes short descriptions and the general syntax for all of the `kubectl` operations:
|
||||
|
||||
Operation | Syntax | Description
|
||||
-------------------- | -------------------- | --------------------
|
||||
`annotate` | `kubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | Add or update the annotations of one or more resources.
|
||||
`api-versions` | `kubectl api-versions [flags]` | List the API versions that are available.
|
||||
`apply` | `kubectl apply -f FILENAME [flags]`| Apply a configuration change to a resource from a file or stdin.
|
||||
`attach` | `kubectl attach POD -c CONTAINER [-i] [-t] [flags]` | Attach to a running container either to view the output stream or interact with the container (stdin).
|
||||
`autoscale` | `kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]` | Automatically scale the set of pods that are managed by a replication controller.
|
||||
`cluster-info` | `kubectl cluster-info [flags]` | Display endpoint information about the master and services in the cluster.
|
||||
`config` | `kubectl config SUBCOMMAND [flags]` | Modifies kubeconfig files. See the individual subcommands for details.
|
||||
`create` | `kubectl create -f FILENAME [flags]` | Create one or more resources from a file or stdin.
|
||||
`delete` | `kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags]` | Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.
|
||||
`describe` | `kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags]` | Display the detailed state of one or more resources.
|
||||
`edit` | `kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags]` | Edit and update the definition of one or more resources on the server by using the default editor.
|
||||
`exec` | `kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]` | Execute a command against a container in a pod,
|
||||
`explain` | `kubectl explain [--include-extended-apis=true] [--recursive=false] [flags]` | Get documentation of various resources. For instance pods, nodes, services, etc.
|
||||
`expose` | `kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [----external-ip=external-ip-of-service] [--type=type] [flags]` | Expose a replication controller, service, or pod as a new Kubernetes service.
|
||||
`get` | `kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags]` | List one or more resources.
|
||||
`label` | `kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | Add or update the labels of one or more resources.
|
||||
`logs` | `kubectl logs POD [-c CONTAINER] [--follow] [flags]` | Print the logs for a container in a pod.
|
||||
`patch` | `kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags]` | Update one or more fields of a resource by using the strategic merge patch process.
|
||||
`port-forward` | `kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]` | Forward one or more local ports to a pod.
|
||||
`proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | Run a proxy to the Kubernetes API server.
|
||||
`replace` | `kubectl replace -f FILENAME` | Replace a resource from a file or stdin.
|
||||
`rolling-update` | `kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC) [flags]` | Perform a rolling update by gradually replacing the specified replication controller and its pods.
|
||||
`run` | `kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]` | Run a specified image on the cluster.
|
||||
`scale` | `kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]` | Update the size of the specified replication controller.
|
||||
`stop` | `kubectl stop` | Deprecated: Instead, see `kubectl delete`.
|
||||
`version` | `kubectl version [--client] [flags]` | Display the Kubernetes version running on the client and server.
|
||||
|
||||
Remember: For more about command operations, see the [kubectl](/docs/user-guide/kubectl/) reference documentation.
|
||||
|
||||
## Resource types
|
||||
|
||||
The following table includes a list of all the supported resource types and their abbreviated aliases:
|
||||
|
||||
Resource type | Abbreviated alias
|
||||
-------------------- | --------------------
|
||||
`apiservices` |
|
||||
`certificatesigningrequests` |`csr`
|
||||
`clusters` |
|
||||
`clusterrolebindings` |
|
||||
`clusterroles` |
|
||||
`componentstatuses` |`cs`
|
||||
`configmaps` |`cm`
|
||||
`controllerrevisions` |
|
||||
`cronjobs` |
|
||||
`customresourcedefinition` |`crd`
|
||||
`daemonsets` |`ds`
|
||||
`deployments` |`deploy`
|
||||
`endpoints` |`ep`
|
||||
`events` |`ev`
|
||||
`horizontalpodautoscalers` |`hpa`
|
||||
`ingresses` |`ing`
|
||||
`jobs` |
|
||||
`limitranges` |`limits`
|
||||
`namespaces` |`ns`
|
||||
`networkpolicies` |`netpol`
|
||||
`nodes` |`no`
|
||||
`persistentvolumeclaims` |`pvc`
|
||||
`persistentvolumes` |`pv`
|
||||
`poddisruptionbudget` |`pdb`
|
||||
`podpreset` |
|
||||
`pods` |`po`
|
||||
`podsecuritypolicies` |`psp`
|
||||
`podtemplates` |
|
||||
`replicasets` |`rs`
|
||||
`replicationcontrollers` |`rc`
|
||||
`resourcequotas` |`quota`
|
||||
`rolebindings` |
|
||||
`roles` |
|
||||
`secrets` |
|
||||
`serviceaccounts` |`sa`
|
||||
`services` |`svc`
|
||||
`statefulsets` |
|
||||
`storageclasses` |
|
||||
|
||||
## Output options
|
||||
|
||||
Use the following sections for information about how you can format or sort the output of certain commands. For details about which commands support the various output options, see the [kubectl](/docs/user-guide/kubectl/) reference documentation.
|
||||
|
||||
### Formatting output
|
||||
|
||||
The default output format for all `kubectl` commands is the human readable plain-text format. To output details to your terminal window in a specific format, you can add either the `-o` or `-output` flags to a supported `kubectl` command.
|
||||
|
||||
#### Syntax
|
||||
|
||||
```shell
|
||||
kubectl [command] [TYPE] [NAME] -o=<output_format>
|
||||
```
|
||||
|
||||
Depending on the `kubectl` operation, the following output formats are supported:
|
||||
|
||||
Output format | Description
|
||||
--------------| -----------
|
||||
`-o=custom-columns=<spec>` | Print a table using a comma separated list of [custom columns](#custom-columns).
|
||||
`-o=custom-columns-file=<filename>` | Print a table using the [custom columns](#custom-columns) template in the `<filename>` file.
|
||||
`-o=json` | Output a JSON formatted API object.
|
||||
`-o=jsonpath=<template>` | Print the fields defined in a [jsonpath](/docs/user-guide/jsonpath) expression.
|
||||
`-o=jsonpath-file=<filename>` | Print the fields defined by the [jsonpath](/docs/user-guide/jsonpath) expression in the `<filename>` file.
|
||||
`-o=name` | Print only the resource name and nothing else.
|
||||
`-o=wide` | Output in the plain-text format with any additional information. For pods, the node name is included.
|
||||
`-o=yaml` | Output a YAML formatted API object.
|
||||
|
||||
##### Example
|
||||
|
||||
In this example, the following command outputs the details for a single pod as a YAML formatted object:
|
||||
|
||||
`$ kubectl get pod web-pod-13je7 -o=yaml`
|
||||
|
||||
Remember: See the [kubectl](/docs/user-guide/kubectl/) reference documentation for details about which output format is supported by each command.
|
||||
|
||||
#### Custom columns
|
||||
|
||||
To define custom columns and output only the details that you want into a table, you can use the `custom-columns` option. You can choose to define the custom columns inline or use a template file: `-o=custom-columns=<spec>` or `-o=custom-columns-file=<filename>`.
|
||||
|
||||
##### Examples
|
||||
|
||||
Inline:
|
||||
|
||||
```shell
|
||||
$ kubectl get pods <pod-name> -o=custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion
|
||||
```
|
||||
|
||||
Template file:
|
||||
|
||||
```shell
|
||||
$ kubectl get pods <pod-name> -o=custom-columns-file=template.txt
|
||||
```
|
||||
|
||||
where the `template.txt` file contains:
|
||||
|
||||
```
|
||||
NAME RSRC
|
||||
metadata.name metadata.resourceVersion
|
||||
```
|
||||
The result of running either command is:
|
||||
|
||||
```shell
|
||||
NAME RSRC
|
||||
submit-queue 610995
|
||||
```
|
||||
|
||||
#### Server-side columns
|
||||
|
||||
`kubectl` supports receiving specific column information from the server about objects.
|
||||
This means that for any given resource, the server will return columns and rows relevant to that resource, for the client to print.
|
||||
This allows for consistent human-readable output across clients used against the same cluster, by having the server encapsulate the details of printing.
|
||||
|
||||
To output object information using this feature, you can add the `--experimental-server-print` flag to a supported `kubectl` command.
|
||||
|
||||
##### Examples
|
||||
|
||||
```shell
|
||||
$ kubectl get pods <pod-name> --experimental-server-print
|
||||
```
|
||||
|
||||
The result of running this command is:
|
||||
|
||||
```shell
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
pod-name 1/1 Running 0 1m
|
||||
|
||||
### Sorting list objects
|
||||
|
||||
To output objects to a sorted list in your terminal window, you can add the `--sort-by` flag to a supported `kubectl` command. Sort your objects by specifying any numeric or string field with the `--sort-by` flag. To specify a field, use a [jsonpath](/docs/user-guide/jsonpath) expression.
|
||||
|
||||
#### Syntax
|
||||
|
||||
```shell
|
||||
kubectl [command] [TYPE] [NAME] --sort-by=<jsonpath_exp>
|
||||
```
|
||||
|
||||
##### Example
|
||||
|
||||
To print a list of pods sorted by name, you run:
|
||||
|
||||
`$ kubectl get pods --sort-by=.metadata.name`
|
||||
|
||||
## Examples: Common operations
|
||||
|
||||
Use the following set of examples to help you familiarize yourself with running the commonly used `kubectl` operations:
|
||||
|
||||
`kubectl create` - Create a resource from a file or stdin.
|
||||
|
||||
```shell
|
||||
// Create a service using the definition in example-service.yaml.
|
||||
$ kubectl create -f example-service.yaml
|
||||
|
||||
// Create a replication controller using the definition in example-controller.yaml.
|
||||
$ kubectl create -f example-controller.yaml
|
||||
|
||||
// Create the objects that are defined in any .yaml, .yml, or .json file within the <directory> directory.
|
||||
$ kubectl create -f <directory>
|
||||
```
|
||||
|
||||
`kubectl get` - List one or more resources.
|
||||
|
||||
```shell
|
||||
// List all pods in plain-text output format.
|
||||
$ kubectl get pods
|
||||
|
||||
// List all pods in plain-text output format and includes additional information (such as node name).
|
||||
$ kubectl get pods -o wide
|
||||
|
||||
// List the replication controller with the specified name in plain-text output format. Tip: You can shorten and replace the 'replicationcontroller' resource type with the alias 'rc'.
|
||||
$ kubectl get replicationcontroller <rc-name>
|
||||
|
||||
// List all replication controllers and services together in plain-text output format.
|
||||
$ kubectl get rc,services
|
||||
|
||||
// List all daemon sets, including uninitialized ones, in plain-text output format.
|
||||
$ kubectl get ds --include-uninitialized
|
||||
|
||||
// List all pods running on node server01
|
||||
$ kubectl get pods --field-selector=spec.nodeName=server01
|
||||
|
||||
// List all pods in plain-text output format, delegating the details of printing to the server
|
||||
$ kubectl get pods --experimental-server-print
|
||||
```
|
||||
|
||||
`kubectl describe` - Display detailed state of one or more resources, including the uninitialized ones by default.
|
||||
|
||||
```shell
|
||||
// Display the details of the node with name <node-name>.
|
||||
$ kubectl describe nodes <node-name>
|
||||
|
||||
// Display the details of the pod with name <pod-name>.
|
||||
$ kubectl describe pods/<pod-name>
|
||||
|
||||
// Display the details of all the pods that are managed by the replication controller named <rc-name>.
|
||||
// Remember: Any pods that are created by the replication controller get prefixed with the name of the replication controller.
|
||||
$ kubectl describe pods <rc-name>
|
||||
|
||||
// Describe all pods, not including uninitialized ones
|
||||
$ kubectl describe pods --include-uninitialized=false
|
||||
```
|
||||
|
||||
{{< note >}}
|
||||
**Note:** The `kubectl get` command is usually used for retrieving one or more
|
||||
resources of the same resource type. It features a rich set of flags that allows
|
||||
you to customize the output format using the `-o` or `--output` flag, for example.
|
||||
You can specify the `-w` or `--watch` flag to start watching updates to a particular
|
||||
object. The `kubectl describe` command is more focused on describing the many
|
||||
related aspects of a specified resource. It may invoke several API calls to the
|
||||
API server to build a view for the user. For example, the `kubectl describe node`
|
||||
command retrieves not only the information about the node, but also a summary of
|
||||
the pods running on it, the events generated for the node etc.
|
||||
{{< /note >}}
|
||||
|
||||
`kubectl delete` - Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.
|
||||
|
||||
```shell
|
||||
// Delete a pod using the type and name specified in the pod.yaml file.
|
||||
$ kubectl delete -f pod.yaml
|
||||
|
||||
// Delete all the pods and services that have the label name=<label-name>.
|
||||
$ kubectl delete pods,services -l name=<label-name>
|
||||
|
||||
// Delete all the pods and services that have the label name=<label-name>, including uninitialized ones.
|
||||
$ kubectl delete pods,services -l name=<label-name> --include-uninitialized
|
||||
|
||||
// Delete all pods, including uninitialized ones.
|
||||
$ kubectl delete pods --all
|
||||
```
|
||||
|
||||
`kubectl exec` - Execute a command against a container in a pod.
|
||||
|
||||
```shell
|
||||
// Get output from running 'date' from pod <pod-name>. By default, output is from the first container.
|
||||
$ kubectl exec <pod-name> date
|
||||
|
||||
// Get output from running 'date' in container <container-name> of pod <pod-name>.
|
||||
$ kubectl exec <pod-name> -c <container-name> date
|
||||
|
||||
// Get an interactive TTY and run /bin/bash from pod <pod-name>. By default, output is from the first container.
|
||||
$ kubectl exec -ti <pod-name> /bin/bash
|
||||
```
|
||||
|
||||
`kubectl logs` - Print the logs for a container in a pod.
|
||||
|
||||
```shell
|
||||
// Return a snapshot of the logs from pod <pod-name>.
|
||||
$ kubectl logs <pod-name>
|
||||
|
||||
// Start streaming the logs from pod <pod-name>. This is similar to the 'tail -f' Linux command.
|
||||
$ kubectl logs -f <pod-name>
|
||||
```
|
||||
|
||||
|
||||
## Next steps
|
||||
|
||||
Start using the [kubectl](/docs/user-guide/kubectl/) commands.
|
||||
Reference in New Issue
Block a user