• Overview of kubectl
    • Syntax
    • Operations
    • Resource types
    • Output options
      • Formatting output
        • Syntax
          • Example
        • Custom columns
          • Examples
        • Server-side columns
          • Examples
      • Sorting list objects
        • Syntax
          • Example
    • Examples: Common operations
    • Examples: Creating and using plugins
    • What's next
    • Feedback

    Overview of kubectl

    Kubectl is a command line interface for running commands against Kubernetes clusters. 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.

    Syntax

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

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

    OperationSyntaxDescription
    annotatekubectl 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-versionskubectl api-versions [flags]List the API versions that are available.
    applykubectl apply -f FILENAME [flags]Apply a configuration change to a resource from a file or stdin.
    attachkubectl attach POD -c CONTAINER [-i] [-t] [flags]Attach to a running container either to view the output stream or interact with the container (stdin).
    autoscalekubectl 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-infokubectl cluster-info [flags]Display endpoint information about the master and services in the cluster.
    configkubectl config SUBCOMMAND [flags]Modifies kubeconfig files. See the individual subcommands for details.
    createkubectl create -f FILENAME [flags]Create one or more resources from a file or stdin.
    deletekubectl 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.
    describekubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags]Display the detailed state of one or more resources.
    diffkubectl diff -f FILENAME [flags]Diff file or stdin against live configuration (BETA)
    editkubectl 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.
    execkubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [— COMMAND [args…]]Execute a command against a container in a pod.
    explainkubectl explain [—recursive=false] [flags]Get documentation of various resources. For instance pods, nodes, services, etc.
    exposekubectl 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.
    getkubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [—watch] [—sort-by=FIELD] [[-o | —output]=OUTPUT_FORMAT] [flags]List one or more resources.
    labelkubectl 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.
    logskubectl logs POD [-c CONTAINER] [—follow] [flags]Print the logs for a container in a pod.
    patchkubectl 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-forwardkubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT […[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]Forward one or more local ports to a pod.
    proxykubectl proxy [—port=PORT] [—www=static-dir] [—www-prefix=prefix] [—api-prefix=prefix] [flags]Run a proxy to the Kubernetes API server.
    replacekubectl replace -f FILENAMEReplace a resource from a file or stdin.
    rolling-updatekubectl 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.
    runkubectl 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.
    scalekubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) —replicas=COUNT [—resource-version=version] [—current-replicas=count] [flags]Update the size of the specified replication controller.
    versionkubectl version [—client] [flags]Display the Kubernetes version running on the client and server.

    Remember: For more about command operations, see the kubectl 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 is accurate as of Kubernetes 1.13.3.)

    Resource NameShort NamesAPI GroupNamespacedResource Kind
    bindingstrueBinding
    componentstatusescsfalseComponentStatus
    configmapscmtrueConfigMap
    endpointseptrueEndpoints
    limitrangeslimitstrueLimitRange
    namespacesnsfalseNamespace
    nodesnofalseNode
    persistentvolumeclaimspvctruePersistentVolumeClaim
    persistentvolumespvfalsePersistentVolume
    podspotruePod
    podtemplatestruePodTemplate
    replicationcontrollersrctrueReplicationController
    resourcequotasquotatrueResourceQuota
    secretstrueSecret
    serviceaccountssatrueServiceAccount
    servicessvctrueService
    mutatingwebhookconfigurationsadmissionregistration.k8s.iofalseMutatingWebhookConfiguration
    validatingwebhookconfigurationsadmissionregistration.k8s.iofalseValidatingWebhookConfiguration
    customresourcedefinitionscrd, crdsapiextensions.k8s.iofalseCustomResourceDefinition
    apiservicesapiregistration.k8s.iofalseAPIService
    controllerrevisionsappstrueControllerRevision
    daemonsetsdsappstrueDaemonSet
    deploymentsdeployappstrueDeployment
    replicasetsrsappstrueReplicaSet
    statefulsetsstsappstrueStatefulSet
    tokenreviewsauthentication.k8s.iofalseTokenReview
    localsubjectaccessreviewsauthorization.k8s.iotrueLocalSubjectAccessReview
    selfsubjectaccessreviewsauthorization.k8s.iofalseSelfSubjectAccessReview
    selfsubjectrulesreviewsauthorization.k8s.iofalseSelfSubjectRulesReview
    subjectaccessreviewsauthorization.k8s.iofalseSubjectAccessReview
    horizontalpodautoscalershpaautoscalingtrueHorizontalPodAutoscaler
    cronjobscjbatchtrueCronJob
    jobsbatchtrueJob
    certificatesigningrequestscsrcertificates.k8s.iofalseCertificateSigningRequest
    leasescoordination.k8s.iotrueLease
    eventsevevents.k8s.iotrueEvent
    ingressesingextensionstrueIngress
    networkpoliciesnetpolnetworking.k8s.iotrueNetworkPolicy
    poddisruptionbudgetspdbpolicytruePodDisruptionBudget
    podsecuritypoliciespsppolicyfalsePodSecurityPolicy
    clusterrolebindingsrbac.authorization.k8s.iofalseClusterRoleBinding
    clusterrolesrbac.authorization.k8s.iofalseClusterRole
    rolebindingsrbac.authorization.k8s.iotrueRoleBinding
    rolesrbac.authorization.k8s.iotrueRole
    priorityclassespcscheduling.k8s.iofalsePriorityClass
    csidriversstorage.k8s.iofalseCSIDriver
    csinodesstorage.k8s.iofalseCSINode
    storageclassesscstorage.k8s.iofalseStorageClass
    volumeattachmentsstorage.k8s.iofalseVolumeAttachment

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

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

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

    Output formatDescription
    -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 jsonOutput a JSON formatted API object.
    -o jsonpath=<template>Print the fields defined in a jsonpath expression.
    -o jsonpath-file=<filename>Print the fields defined by the jsonpath expression in the <filename> file.
    -o namePrint only the resource name and nothing else.
    -o wideOutput in the plain-text format with any additional information. For pods, the node name is included.
    -o yamlOutput a YAML formatted API object.
    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:

    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.

    This feature is enabled by default in kubectl 1.11 and higher. To disable it, add the—server-print=false flag to the kubectl get command.

    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

    Output looks like this:

    1. NAME READY STATUS RESTARTS AGE
    2. 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 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. # Create the objects that are defined in any .yaml, .yml, or .json file within the <directory> directory.
    6. 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 moreresources of the same resource type. It features a rich set of flags that allowsyou 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 particularobject. The kubectl describe command is more focused on describing the manyrelated aspects of a specified resource. It may invoke several API calls to theAPI server to build a view for the user. For example, the kubectl describe nodecommand retrieves not only the information about the node, but also a summary ofthe 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 name=<label-name>.
    4. kubectl delete pods,services -l name=<label-name>
    5. # Delete all the pods and services that have the label name=<label-name>.
    6. kubectl delete pods,services -l name=<label-name>
    7. # Delete all pods, including uninitialized ones.
    8. 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>

    Examples: Creating and using plugins

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

    1. # create a simple plugin in any language and name the resulting executable file
    2. # so that it begins with the prefix "kubectl-"
    3. cat ./kubectl-hello
    4. #!/bin/bash
    5. # this plugin prints the words "hello world"
    6. echo "hello world"
    7. # with our plugin written, let's make it executable
    8. sudo chmod +x ./kubectl-hello
    9. # and move it to a location in our PATH
    10. sudo mv ./kubectl-hello /usr/local/bin
    11. # we have now created and "installed" a kubectl plugin.
    12. # we can begin using our plugin by invoking it from kubectl as if it were a regular command
    13. kubectl hello
    1. hello world
    1. # we can "uninstall" a plugin, by simply removing it from our PATH
    2. sudo rm /usr/local/bin/kubectl-hello

    In order to view all of the plugins that are available to kubectl, we can usethe kubectl plugin list subcommand:

    1. kubectl plugin list
    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
    1. # this command can also warn us about plugins that are
    2. # not executable, or that are overshadowed by other
    3. # plugins, for example
    4. sudo chmod -x /usr/local/bin/kubectl-foo
    5. 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

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

    1. cat ./kubectl-whoami
    2. #!/bin/bash
    3. # this plugin makes use of the `kubectl config` command in order to output
    4. # information about the current user, based on the currently selected context
    5. kubectl config view --template='{{ range .contexts }}{{ if eq .name "'$(kubectl config current-context)'" }}Current user: {{ .context.user }}{{ end }}{{ end }}'

    Running the above plugin gives us an output containing the user for the currently selectedcontext in our KUBECONFIG file:

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

    To find out more about plugins, take a look at the example cli plugin.

    What's next

    Start using the kubectl commands.

    Feedback

    Was this page helpful?

    Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it onStack Overflow.Open an issue in the GitHub repo if you want toreport a problemorsuggest an improvement.