Command line tool (kubectl)

    This tool is named .

    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 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 ; for a quick guide, see the cheat sheet. If you’re used to using the docker command-line tool, explains some equivalent commands for Kubernetes.

    Use the following syntax to run kubectl commands from your terminal window:

    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 types are case-insensitive and you can specify the singular, plural, or abbreviated forms. For example, the following commands produce the same output:

      1. kubectl get pod pod1
      2. kubectl get pods pod1
      3. 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<#>.
          Example: kubectl get pod example-pod1 example-pod2

        • To specify multiple resource types individually: TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>.
          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 since YAML tends to be more user-friendly, especially for configuration files.
          Example: kubectl get -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.

    Caution: Flags that you specify from the command line override default values and any corresponding environment variables.

    If you need help, run kubectl help from the terminal window.

    In-cluster authentication and namespace overrides

    By 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

    Explicit use of --namespace <value> overrides this behavior.

    How kubectl handles ServiceAccount tokens

    If:

    • there is Kubernetes service account token file mounted at /var/run/secrets/kubernetes.io/serviceaccount/token, and
    • the KUBERNETES_SERVICE_HOST environment variable is set, and
    • the KUBERNETES_SERVICE_PORT environment variable is set, and
    • you don’t explicitly specify a namespace on the kubectl command line

    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 namespace set for the current context in your client configuration. To change the default namespace for your kubectl you can use the following command:

    1. kubectl config set-context --current --namespace=<namespace-name>

    The following table includes short descriptions and the general syntax for all of the kubectl operations:

    To learn more about command operations, see the reference documentation.

    Resource types

    The 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.25.0)

    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 reference documentation.

    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

    1. kubectl [command] [TYPE] [NAME] -o <output_format>

    Depending on the kubectl operation, the following output formats are supported:

    Example

    In this example, the following command outputs the details for a single pod as a YAML formatted object:

    1. 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 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:

    1. kubectl get pods <pod-name> -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion

    Template file:

    1. kubectl get pods <pod-name> -o custom-columns-file=template.txt

    where the template.txt file contains:

    1. NAME RSRC
    2. metadata.name metadata.resourceVersion

    The result of running either command is similar to:

    1. NAME RSRC
    2. 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.

    Examples

    To print information about the status of a pod, use a command like the following:

    1. kubectl get pods <pod-name> --server-print=false

    The output is similar to:

    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 flag. To specify a field, use a jsonpath expression.

    Syntax

    1. kubectl [command] [TYPE] [NAME] --sort-by=<jsonpath_exp>
    Example

    To print a list of pods sorted by name, you run:

    1. 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 apply - Apply or Update a resource from a file or stdin.

    1. # Create a service using the definition in example-service.yaml.
    2. kubectl apply -f example-service.yaml
    3. # Create a replication controller using the definition in example-controller.yaml.
    4. kubectl apply -f example-controller.yaml
    5. kubectl apply -f <directory>

    kubectl get - List one or more resources.

    1. # List all pods in plain-text output format.
    2. kubectl get pods
    3. # List all pods in plain-text output format and include additional information (such as node name).
    4. kubectl get pods -o wide
    5. # 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'.
    6. kubectl get replicationcontroller <rc-name>
    7. # List all replication controllers and services together in plain-text output format.
    8. kubectl get rc,services
    9. # List all daemon sets in plain-text output format.
    10. kubectl get ds
    11. # List all pods running on node server01
    12. kubectl get pods --field-selector=spec.nodeName=server01

    kubectl describe - Display detailed state of one or more resources, including the uninitialized ones by default.

    1. # Display the details of the node with name <node-name>.
    2. kubectl describe nodes <node-name>
    3. # Display the details of the pod with name <pod-name>.
    4. kubectl describe pods/<pod-name>
    5. # Display the details of all the pods that are managed by the replication controller named <rc-name>.
    6. # Remember: Any pods that are created by the replication controller get prefixed with the name of the replication controller.
    7. kubectl describe pods <rc-name>
    8. # Describe all pods
    9. kubectl describe pods

    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.

    kubectl delete - Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.

    1. # Delete a pod using the type and name specified in the pod.yaml file.
    2. kubectl delete -f pod.yaml
    3. # Delete all the pods and services that have the label '<label-key>=<label-value>'.
    4. kubectl delete pods,services -l <label-key>=<label-value>
    5. # Delete all pods, including uninitialized ones.
    6. kubectl delete pods --all

    kubectl exec - Execute a command against a container in a pod.

    1. # Get output from running 'date' from pod <pod-name>. By default, output is from the first container.
    2. kubectl exec <pod-name> -- date
    3. # Get output from running 'date' in container <container-name> of pod <pod-name>.
    4. kubectl exec <pod-name> -c <container-name> -- date
    5. # Get an interactive TTY and run /bin/bash from pod <pod-name>. By default, output is from the first container.
    6. kubectl exec -ti <pod-name> -- /bin/bash

    kubectl logs - Print the logs for a container in a pod.

    1. # Return a snapshot of the logs from pod <pod-name>.
    2. kubectl logs <pod-name>
    3. # Start streaming the logs from pod <pod-name>. This is similar to the 'tail -f' Linux command.
    4. kubectl logs -f <pod-name>

    kubectl diff - View a diff of the proposed updates to a cluster.

    1. # Diff resources included in "pod.json".
    2. # Diff file read from stdin.
    3. cat service.yaml | kubectl diff -f -

    Use the following set of examples to help you familiarize yourself with writing and using kubectl plugins:

    1. #!/bin/sh
    2. # this plugin prints the words "hello world"
    3. echo "hello world"

    With a plugin written, let’s make it executable:

    1. chmod a+x ./kubectl-hello
    2. # and move it to a location in our PATH
    3. sudo mv ./kubectl-hello /usr/local/bin
    4. sudo chown root:root /usr/local/bin
    5. # You have now created and "installed" a kubectl plugin.
    6. # You can begin using this plugin by invoking it from kubectl as if it were a regular command
    7. kubectl hello
    1. hello world
    1. # You can "uninstall" a plugin, by removing it from the folder in your
    2. # $PATH where you placed it
    3. 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:

    1. kubectl plugin list

    The output is similar to:

    1. The following kubectl-compatible plugins are available:
    2. /usr/local/bin/kubectl-hello
    3. /usr/local/bin/kubectl-foo
    4. /usr/local/bin/kubectl-bar

    kubectl plugin list also warns you about plugins that are not executable, or that are shadowed by other plugins; for example:

    1. sudo chmod -x /usr/local/bin/kubectl-foo # remove execute permission
    2. kubectl plugin list
    1. The following kubectl-compatible plugins are available:
    2. /usr/local/bin/kubectl-hello
    3. /usr/local/bin/kubectl-foo
    4. - warning: /usr/local/bin/kubectl-foo identified as a plugin, but it is not executable
    5. /usr/local/bin/kubectl-bar
    6. error: one plugin warning was found

    You can think of plugins as a means to build more complex functionality on top of the existing kubectl commands:

    1. cat ./kubectl-whoami

    Running the above command gives you an output containing the user for the current context in your KUBECONFIG file:

    1. # make the file executable
    2. sudo chmod +x ./kubectl-whoami
    3. # and move it into your PATH
    4. sudo mv ./kubectl-whoami /usr/local/bin
    5. kubectl whoami
    6. Current user: plugins-user

    What’s next