Which of the following commands can be used to display containers that are no longer running
Kubernetes provides a command line tool for communicating with a Kubernetes cluster's control plane, using the Kubernetes API. Show
This tool is named kubectl. For configuration, kubectl looks for a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag. 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 reference documentation. For installation instructions, see Installing kubectl; for a quick guide, see the cheat sheet. If you're used to using the docker command-line tool, kubectl for Docker Users explains some equivalent commands for Kubernetes. SyntaxUse the following syntax to run kubectl commands from your terminal window: kubectl [command] [TYPE] [NAME] [flags] where command, TYPE, NAME, and flags are:
If you need help, run kubectl help from the terminal window. In-cluster authentication and namespace overridesBy default kubectl will first determine if it is running within a pod, and thus in a cluster. It starts by checking for the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT environment variables and the existence of a service account token file at /var/run/secrets/kubernetes.io/serviceaccount/token. If all three are found in-cluster authentication is assumed. To maintain backwards compatibility, if the POD_NAMESPACE environment variable is set during in-cluster authentication it will override the default namespace from the service account token. Any manifests or tools relying on namespace defaulting will be affected by this. POD_NAMESPACE environment variable If the POD_NAMESPACE environment variable is set, cli operations on namespaced resources will default to the variable value. For example, if the variable is set to seattle, kubectl get pods would return pods in the seattle namespace. This is because pods are a namespaced resource, and no namespace was provided in the command. Review the output of kubectl api-resources to determine if a resource is namespaced. Explicit use of --namespace How kubectl handles ServiceAccount tokens If:
then kubectl assumes it is running in your cluster. The kubectl tool looks up the namespace of that ServiceAccount (this is the same as the namespace of the Pod) and acts against that namespace. This is different from what happens outside of a cluster; when kubectl runs outside a cluster and you don't specify a namespace, the kubectl command acts against the default namespace. OperationsThe following table includes short descriptions and the general syntax for all of the kubectl operations:
To learn more about command operations, see the kubectl reference documentation. Resource typesThe following table includes a list of all the supported resource types and their abbreviated aliases. (This output can be retrieved from kubectl api-resources, and was accurate as of Kubernetes 1.19.1.)
Output optionsUse 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 reference documentation. Formatting outputThe 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. Syntaxkubectl [command] [TYPE] [NAME] -o Depending on the kubectl operation, the following output formats are supported:
ExampleIn 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 reference documentation for details about which output format is supported by each command. Custom columnsTo 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= ExamplesInline: kubectl get pods Template file: kubectl get pods where the template.txt file contains: NAME RSRC metadata.name metadata.resourceVersionThe result of running either command is similar to: NAME RSRC submit-queue 610995Server-side columnskubectl 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. This feature is enabled by default. To disable it, add the --server-print=false flag to the kubectl get command. ExamplesTo print information about the status of a pod, use a command like the following: kubectl get pods The output is similar to: NAME AGE pod-name 1mSorting list objectsTo 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 expression. Syntaxkubectl [command] [TYPE] [NAME] --sort-by= ExampleTo print a list of pods sorted by name, you run: kubectl get pods --sort-by=.metadata.name Examples: Common operationsUse the following set of examples to help you familiarize yourself with running the commonly used kubectl operations: kubectl apply - Apply or Update a resource from a file or stdin. # Create a service using the definition in example-service.yaml.
kubectl apply -f example-service.yaml
# Create a replication controller using the definition in example-controller.yaml.
kubectl apply -f example-controller.yaml
# Create the objects that are defined in any .yaml, .yml, or .json file within the kubectl get - List one or more resources. # List all pods in plain-text output format.
kubectl get pods
# List all pods in plain-text output format and include 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 kubectl describe - Display detailed state of one or more resources, including the uninitialized ones by default. # Display the details of the node with name kubectl delete - Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources. # 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 ' kubectl exec - Execute a command against a container in a pod. # Get output from running 'date' from pod kubectl logs - Print the logs for a container in a pod. # Return a snapshot of the logs from pod kubectl diff - View a diff of the proposed updates to a cluster. # Diff resources included in "pod.json". kubectl diff -f pod.json # Diff file read from stdin. cat service.yaml | kubectl diff -f - Examples: Creating and using pluginsUse the following set of examples to help you familiarize yourself with writing and using kubectl plugins: # create a simple plugin in any language and name the resulting executable file # so that it begins with the prefix "kubectl-" cat ./kubectl-hello #!/bin/sh # this plugin prints the words "hello world" echo "hello world" With a plugin written, let's make it executable: chmod a+x ./kubectl-hello # and move it to a location in our PATH sudo mv ./kubectl-hello /usr/local/bin sudo chown root:root /usr/local/bin # You have now created and "installed" a kubectl plugin. # You can begin using this plugin by invoking it from kubectl as if it were a regular command kubectl hello hello world# You can "uninstall" a plugin, by removing it from the folder in your # $PATH where you placed it sudo rm /usr/local/bin/kubectl-hello In order to view all of the plugins that are available to kubectl, use the kubectl plugin list subcommand: The output is similar to: The following kubectl-compatible plugins are available: /usr/local/bin/kubectl-hello /usr/local/bin/kubectl-foo /usr/local/bin/kubectl-barkubectl plugin list also warns you about plugins that are not executable, or that are shadowed by other plugins; for example: sudo chmod -x /usr/local/bin/kubectl-foo # remove execute permission kubectl plugin list The following kubectl-compatible plugins are available: /usr/local/bin/kubectl-hello /usr/local/bin/kubectl-foo - warning: /usr/local/bin/kubectl-foo identified as a plugin, but it is not executable /usr/local/bin/kubectl-bar error: one plugin warning was foundYou can think of plugins as a means to build more complex functionality on top of the existing kubectl commands: The next few examples assume that you already made kubectl-whoami have the following contents: #!/bin/bash # this plugin makes use of the `kubectl config` command in order to output # information about the current user, based on the currently selected context kubectl config view --template='{{ range .contexts }}{{ if eq .name "'$(kubectl config current-context)'" }}Current user: {{ printf "%s\n" .context.user }}{{ end }}{{ end }}' Running the above command gives you an output containing the user for the current context in your KUBECONFIG file: # make the file executable sudo chmod +x ./kubectl-whoami # and move it into your PATH sudo mv ./kubectl-whoami /usr/local/bin kubectl whoami Current user: plugins-user What's next
1 - kubectl Cheat SheetThis page contains a list of commonly used kubectl commands and flags. Kubectl autocompleteBASHsource <(kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion package should be installed first. echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell. You can also use a shorthand alias for kubectl that also works with completion: alias k=kubectl complete -o default -F __start_kubectl k ZSHsource <(kubectl completion zsh) # setup autocomplete in zsh into the current shell echo '[[ $commands[kubectl] ]] && source <(kubectl completion zsh)' >> ~/.zshrc # add autocomplete permanently to your zsh shell A Note on --all-namespacesAppending --all-namespaces happens frequently enough where you should be aware of the shorthand for --all-namespaces: kubectl -A Kubectl context and configurationSet which Kubernetes cluster kubectl communicates with and modifies configuration information. See Authenticating Across Clusters with kubeconfig documentation for detailed config file information. 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 view -o jsonpath='{.users[].name}' # display the first user kubectl config view -o jsonpath='{.users[*].name}' # get a list of users kubectl config get-contexts # display list of contexts kubectl config current-context # display the current-context kubectl config use-context my-cluster-name # set the default context to my-cluster-name kubectl config set-cluster my-cluster-name # set a cluster entry in the kubeconfig # configure the URL to a proxy server to use for requests made by this client in the kubeconfig kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url # add a new user to your kubeconf that supports basic auth kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword # permanently save the namespace for all subsequent kubectl commands in that context. kubectl config set-context --current --namespace=ggckad-s2 # set a context utilizing a specific username and namespace. kubectl config set-context gce --user=cluster-admin --namespace=foo \ && kubectl config use-context gce kubectl config unset users.foo # delete user foo # short alias to set/show context/namespace (only works for bash and bash-compatible shells, current context to be set before using kn to set namespace) alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f' alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f' Kubectl applyapply manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster through running kubectl apply. This is the recommended way of managing Kubernetes applications on production. See Kubectl Book. Creating objectsKubernetes manifests can be defined in YAML or JSON. The file extension .yaml, .yml, and .json can be used. kubectl apply -f ./my-manifest.yaml # create resource(s)
kubectl apply -f ./my1.yaml -f ./my2.yaml # create from multiple files
kubectl apply -f ./dir # create resource(s) in all manifest files in dir
kubectl apply -f https://git.io/vPieo # create resource(s) from url
kubectl create deployment nginx --image=nginx # start a single instance of nginx
# create a Job which prints "Hello World"
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"
# create a CronJob that prints "Hello World" every minute
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"
kubectl explain pods # get the documentation for pod manifests
# Create multiple YAML objects from stdin
cat < Viewing, finding resources# 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 current namespace, with more details kubectl get deployment my-dep # List a particular deployment kubectl get pods # List all pods in the namespace kubectl get pod my-pod -o yaml # Get a pod's YAML # Describe commands with verbose output kubectl describe nodes my-node kubectl describe pods my-pod # List Services Sorted by Name kubectl get services --sort-by=.metadata.name # List pods Sorted by Restart Count kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # List PersistentVolumes sorted by capacity kubectl get pv --sort-by=.spec.capacity.storage # Get the version label of all pods with label app=cassandra kubectl get pods --selector=app=cassandra -o \ jsonpath='{.items[*].metadata.labels.version}' # Retrieve the value of a key with dots, e.g. 'ca.crt' kubectl get configmap myconfig \ -o jsonpath='{.data.ca\.crt}' # Retrieve a base64 encoded value with dashes instead of underscores. kubectl get secret my-secret --template='{{index .data "key-name-with-dashes"}}' # Get all worker nodes (use a selector to exclude results that have a label # named 'node-role.kubernetes.io/control-plane') kubectl get node --selector='!node-role.kubernetes.io/control-plane' # 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}) # Show labels for all pods (or any other Kubernetes object that supports labelling) kubectl get pods --show-labels # 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" # Output decoded secrets without external tools kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}' # 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 all containerIDs of initContainer of all pods # Helpful when cleaning up stopped containers, while avoiding removal of initContainers. kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3 # List Events sorted by timestamp kubectl get events --sort-by=.metadata.creationTimestamp # Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied. kubectl diff -f ./my-manifest.yaml # Produce a period-delimited tree of all keys returned for nodes # Helpful when locating a key within a complex nested JSON structure kubectl get nodes -o json | jq -c 'paths|join(".")' # Produce a period-delimited tree of all keys returned for pods, etc kubectl get pods -o json | jq -c 'paths|join(".")' # Produce ENV for all pods, assuming you have a default container for the pods, default namespace and the `env` command is supported. # Helpful when running any supported command across all pods, not just `env` for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; done # Get a deployment's status subresource kubectl get deployment nginx-deployment --subresource=status Updating resourceskubectl set image deployment/frontend www=image:v2 # Rolling update "www" containers of "frontend" deployment, updating the image kubectl rollout history deployment/frontend # Check the history of deployments including the revision kubectl rollout undo deployment/frontend # Rollback to the previous deployment kubectl rollout undo deployment/frontend --to-revision=2 # Rollback to a specific revision kubectl rollout status -w deployment/frontend # Watch rolling update status of "frontend" deployment until completion kubectl rollout restart deployment/frontend # Rolling restart of the "frontend" deployment 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# Partially update a node kubectl patch node k8s-node-1 -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":"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" } }]' # Update a deployment's replica count by patching its scale subresource kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}' Editing resourcesEdit any API resource in your preferred editor. kubectl edit svc/docker-registry # Edit the service named docker-registry KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor Scaling resourceskubectl 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 resourceskubectl delete -f ./pod.json # Delete a pod using the type and name specified in pod.json kubectl delete pod unwanted --now # Delete a pod with no grace period 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 -n my-ns delete pod,svc --all # Delete all pods and services in namespace my-ns, # Delete all pods matching the awk pattern1 or pattern2 kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod Interacting with running Podskubectl logs my-pod # dump pod logs (stdout) kubectl logs -l name=myLabel # dump pod logs, with label name=myLabel (stdout) kubectl logs my-pod --previous # dump pod logs (stdout) for a previous instantiation of a container kubectl logs my-pod -c my-container # dump pod container logs (stdout, multi-container case) kubectl logs -l name=myLabel -c my-container # dump pod logs, with label name=myLabel (stdout) kubectl logs my-pod -c my-container --previous # dump pod container logs (stdout, multi-container case) for a previous instantiation of a container 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 logs -f -l name=myLabel --all-containers # stream all pods logs with label name=myLabel (stdout) kubectl run -i --tty busybox --image=busybox:1.28 -- sh # Run pod as interactive shell kubectl run nginx --image=nginx -n mynamespace # Start a single instance of nginx pod in the namespace of mynamespace kubectl run nginx --image=nginx # Run pod nginx and write its spec into a file called pod.yaml --dry-run=client -o yaml > pod.yaml 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 --stdin --tty my-pod -- /bin/sh # Interactive shell access to a running 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 kubectl top pod POD_NAME --sort-by=cpu # Show metrics for a given pod and sort it by 'cpu' or 'memory' Copy files and directories to and from containerskubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar # Copy /tmp/foo from a remote pod to /tmp/bar locally tar cf - /tmp/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C /tmp/bar # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace kubectl exec -n my-namespace my-pod -- tar cf - /tmp/foo | tar xf - -C /tmp/bar # Copy /tmp/foo from a remote pod to /tmp/bar locally Interacting with Deployments and Serviceskubectl logs deploy/my-deployment # dump Pod logs for a Deployment (single-container case)
kubectl logs deploy/my-deployment -c my-container # dump Pod logs for a Deployment (multi-container case)
kubectl port-forward svc/my-service 5000 # listen on local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000:my-service-port # listen on local port 5000 and forward to Service target port with name Interacting with Nodes and clusterkubectl 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 # View existing taints on which exist on current nodes. kubectl get nodes -o=custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect # 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 typesList all supported resource types along with their shortnames, API group, whether they are namespaced, and Kind: Other operations for exploring API resources: kubectl api-resources --namespaced=true # All namespaced resources kubectl api-resources --namespaced=false # All non-namespaced resources kubectl api-resources -o name # All resources with simple output (only the resource name) kubectl api-resources -o wide # All resources with expanded (aka "wide") output kubectl api-resources --verbs=list,get # All resources that support the "list" and "get" request verbs kubectl api-resources --api-group=extensions # All resources in the "extensions" API group Formatting outputTo output details to your terminal window in a specific format, add the -o (or --output) flag to a supported kubectl command.
Examples using -o=custom-columns: # All images running in a cluster kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image' # All images running in namespace: default, grouped by Pod kubectl get pods --namespace default --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.containers[*].image" # All images excluding "registry.k8s.io/coredns:1.6.2" kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry.k8s.io/coredns:1.6.2")].image' # All fields under metadata regardless of name kubectl get pods -A -o=custom-columns='DATA:metadata.*' More examples in the kubectl reference documentation. Kubectl output verbosity and debuggingKubectl 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.
What's next
3 - kubectlSynopsiskubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/ kubectl [flags]Options
Environment variables
See Also
4 - JSONPath SupportKubectl supports JSONPath template. JSONPath template is composed of JSONPath expressions enclosed by curly braces {}. Kubectl uses JSONPath expressions to filter on specific fields in the JSON object and format the output. In addition to the original JSONPath template syntax, the following functions and syntax are valid:
Given the JSON input: { "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"} } ] }
Examples using kubectl and JSONPath expressions: 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="{.items[*]['metadata.name', 'status.capacity']}" kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}' 5 - kubectl for Docker UsersYou can use the Kubernetes command line tool kubectl to interact with the API Server. Using kubectl is straightforward if you are familiar with the Docker command line tool. However, there are a few differences between the Docker commands and the kubectl commands. The following sections show a Docker sub-command and describe the equivalent kubectl command. docker runTo run an nginx Deployment and expose the Deployment, see kubectl create deployment. docker: docker run -d --restart=always -e DOMAIN=cluster --name nginx-app -p 80:80 nginx 55c103fa129692154a7652490236fee9be47d70a8dd562281ae7d2f9a339a6db 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-appkubectl: # start the pod running nginx kubectl create deployment --image=nginx nginx-app deployment.apps/nginx-app created# add env to nginx-app kubectl set env deployment/nginx-app DOMAIN=cluster deployment.apps/nginx-app env updated# expose a port through with a service kubectl expose deployment nginx-app --port=80 --name=nginx-http service "nginx-http" exposedBy using kubectl, you can create a 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 with a selector that matches the pod labels. For more information, see Use a Service to Access an Application in a Cluster. By default images run in the background, similar to docker run -d .... To run things in the foreground, use kubectl run to create pod: kubectl run [-i] [--tty] --attach 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. docker psTo list what is currently running, see kubectl get. docker: 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-appkubectl: NAME READY STATUS RESTARTS AGE nginx-app-8df569cb7-4gd89 1/1 Running 0 3m ubuntu 0/1 Completed 0 20sdocker attachTo attach a process that is already running in a container, see kubectl attach. docker: 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-appdocker attach 55c103fa1296 ... kubectl: NAME READY STATUS RESTARTS AGE nginx-app-5jyvm 1/1 Running 0 10mkubectl attach -it nginx-app-5jyvm ... To detach from the container, you can type the escape sequence Ctrl+P followed by Ctrl+Q. docker execTo execute a command in a container, see kubectl exec. docker: 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-appdocker exec 55c103fa1296 cat /etc/hostname 55c103fa1296kubectl: NAME READY STATUS RESTARTS AGE nginx-app-5jyvm 1/1 Running 0 10mkubectl exec nginx-app-5jyvm -- cat /etc/hostname nginx-app-5jyvmTo use interactive commands. docker: docker exec -ti 55c103fa1296 /bin/sh # exit kubectl: kubectl exec -ti nginx-app-5jyvm -- /bin/sh # exit For more information, see Get a Shell to a Running Container. docker logsTo follow stdout/stderr of a process that is running, see kubectl logs. docker: 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: 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: 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. docker stop and docker rmTo stop and delete a running process, see kubectl delete. docker: 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 a9ec34d98787 a9ec34d98787kubectl: kubectl get deployment nginx-app NAME READY UP-TO-DATE AVAILABLE AGE nginx-app 1/1 1 1 2mkubectl get po -l app=nginx-app NAME READY STATUS RESTARTS AGE nginx-app-2883164633-aklf7 1/1 Running 0 2mkubectl delete deployment nginx-app deployment "nginx-app" deletedkubectl get po -l app=nginx-app # Return nothing docker loginThere 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. docker versionTo get the version of client and server, see kubectl version. docker: 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/amd64kubectl: 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 infoTo get miscellaneous information about the environment and configuration, see kubectl cluster-info. docker: 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 supportkubectl: Kubernetes master is running at https://203.0.113.141 KubeDNS is running at https://203.0.113.141/api/v1/namespaces/kube-system/services/kube-dns/proxy kubernetes-dashboard is running at https://203.0.113.141/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy Grafana is running at https://203.0.113.141/api/v1/namespaces/kube-system/services/monitoring-grafana/proxy Heapster is running at https://203.0.113.141/api/v1/namespaces/kube-system/services/monitoring-heapster/proxy InfluxDB is running at https://203.0.113.141/api/v1/namespaces/kube-system/services/monitoring-influxdb/proxy6 - kubectl Usage ConventionsRecommended usage conventions for kubectl. Using kubectl in Reusable ScriptsFor a stable output in a script:
Subresources
Best Practiceskubectl runFor kubectl run to satisfy infrastructure as code:
You can use the --dry-run=client flag to preview the object that would be sent to your cluster, without really submitting it. kubectl apply
|