drx - Fotolia

Tip

Kubectl commands and best practices for new Kubernetes users

Kubectl is a simple and powerful means to control containers in Kubernetes. But as with any CLI, it demands familiarity with available operations, resource types and associated syntax.

The command line interface remains popular among systems administrators because it provides precise granular control and repeatability, which lends itself well to automation.

The rise of containers has been no different, and major container orchestration tools such as Kubernetes offer a command line interface (CLI). Kubectl is the command line tool that controls Kubernetes clusters. With kubectl, administrators can perform a wide array of container management and orchestration tasks such as: apply a configuration change to a resource; attach Kubernetes to a running container; access container logs; and run a specified image on the cluster.

Let's look closely at kubectl and its operations and consider some examples and best practices.

Kubectl syntax

Kubectl commands follow a common structure -- or syntax -- which enables administrators to read and validate each kubectl command entered into the terminal window. There are four major parameters to each kubectl call:

kubectl <command> <type> <name> <flags>

The <command> parameter is the operation that must be performed on a resource. Kubectl supports dozens of operations, including create, get, describe, execute and delete.

The <type> parameter stipulates the resource type, such as bindings, nodes and pods. Resource type designations usually use abbreviations to simplify the command line. For example, the "persistentvolumeclaims" type can be shortened to "pvc." The <type> parameter is powerful, as there are dozens of possible resource types, which also involve namespaces, replication controllers, resource quotas, services, jobs, leases and events. Developers and Kubernetes administrators should be familiar with a complete list of resource types.

The <name> parameter delineates the name of the resource within the environment. If the name parameter is omitted, the details for all resources are returned -- somewhat like a wildcard argument. In addition, administrators can specify multiple resource types and names within the same command line, as seen below.

kubectl <command> <type> <name1> <name2> … <nameX>

This is useful when the names are all the same resource type, for example:

kubectl get pod test-pod1 test-pod2

Kubectl syntax also supports the combination of different resource types and names on the same command line in two ways:

kubectl <command> <type1/name1> <type2/name2> … <typeX/nameX>

or:

kubectl get pod/test-pod1 replicationcontroller/xyzcorp-rc1

Finally, the <flags> parameter adds optional flags to the command line. Flags vary with the command, which means that not all flags are available for all commands. For example, the -s, (one dash shorthand notation) or --server (two dashes, longhand notation) flags specify the port and address of the Kubernetes API server.

The -o or --output <flag> sends responses to a terminal window in a specific format. For example, the -o yaml flag will output a YAML-formatted API object, while the -o json flag will output a JSON-formatted API object.

Kubectl operations

Kubectl commands support dozens of operations and management tasks. The following kubectl cheat sheet offers a quick overview of the available operations listed in alphabetical order. For more information, visit Kubernetes' documentation.

Kubectl command cheat sheet

Kubectl basic examples

While it is best to refer to the kubectl help function for complete syntax and options, the possible combination of operations, resource types and flags is vast. Below is a list of command lines that cover the most common tasks in kubectl.

List resources

The kubectl get operation lists one or more Kubernetes resources. The kubectl get pods command lists all pods under Kubernetes. When admins add a "wide" output flag such as kubectl get pods -o wide, it lists the pods with associated node names and other information. The get operation also lists resources like replication controllers and services. A command such as kubectl get rc,services lists all replication controllers and services. The get operation has many variations that enable users to stipulate specific nodes, shorten lengthy resource types with short aliases, and so on.

Describe resources

The get operation offers a compact list, but the kubectl describe operation reports the detailed state of one or more Kubernetes resources. The command kubectl describe pods describes all the pods under Kubernetes. When a replication controller manages pods, kubectl displays the details of pods under that replication controller with the kubectl describe pods rc-mycontrollername command -- where the name of the controller includes the "rc" prefix. In kubectl, the describe operation also focuses on specific nodes or pods. For example, the kubectl describe nodes nameofmynode command displays the named node's details, while the kubectl describe pods/nameofmypod command displays the named pod's details.

Create or change resources

Kubectl enables users to create a resource from a specific file or stdin, or standard input, such as a keyboard, with the apply operation. The kubectl apply -f mynewservice.yaml command uses a YAML file -- the -f flag -- named mynewservice.yaml to create a service. As an example, if the goal is to use the contents of a mynewcontroller.yaml file to create a replication controller, use the kubectl apply -f mynewcontroller.yaml command. Users can opt for a broader command, such as kubectl apply -f nameofdirectory, which creates services or resources defined in any YAML or JSON file in the specified directory.

Delete resources

Kubectl can also destroy resources and services that are no longer necessary. This is a crucial management task and frees computing capacity for other container tasks under Kubernetes. For example, the kubectl delete pods --all command will delete all pods. It is usually more desirable -- and safer -- to use types and names specified in a separate YAML file to delete a pod. For example, if an admin creates a pod with the testpod1.yaml file, then the admin can delete the same pod with a kubectl delete -f testpod1.yaml command. Kubectl can also delete pods and services that share a specific label -- previously assigned with the kubectl label operation. For example, the kubectl delete pods,services -l name=testbed1 command deletes any pods and services with the "testbed1" label.

Execute a command

Finally, with kubectl, use the exec operation to run a command against a container or a pod. For example, the kubectl exec mypod date command will run the date command on the pod called "mypod" and then display its output. The command executes on the pod's first container by default. As another example, the kubectl exec mypod -c contaner1 date command runs the date command in the container named "container1" within the pod named "mypod" and then displays the output.

Display pod logs

Kubectl can use the logs operation to display logs for selected pods. For example, the kubectl logs pod1 command shows the logs from the first container in the pod named "pod1." If the pod runs multiple containers, the kubectl logs pod1 --all-containers=true command generates logs for all containers within the pod. The logs operation also enables users to get logs from containers that bear specific labels. For example, the kubectl logs -lapp=tests --all-containers=true command returns logs for all containers with the "tests" label, previously applied with the label operation.

Kubectl best practices

As with any CLI, the kubectl command line tool demands a level of expertise in available operations, resource types and associated syntax. Here are five considerations that reduce the chances of errors when working with kubectl.

1. Know the defaults

A well-designed CLI will implement the most commonly used option or path for most operations. Rely on the default -- when appropriate -- to save time and reduce spelling and syntax errors in long and complex commands. In kubectl, for example, the get operation provides an "all-namespaces" flag, which is set to false by default -- but can be either true or false -- so when admins use a get operation, it will only list the requested object in the current namespace by default, rather than all namespaces. If this is the intended behavior, there is no need to include the flag and option explicitly, which potentially reduces errors and oversights.

2. Use simple aliases

CLIs often use readable terms and phrases for complex resources. Although the goal is to make command line operations, resources and flags more human-readable, it also introduces tremendous opportunities for spelling errors -- especially where admins repeatedly use the long names. The use of short and efficient aliases enables admins to use the same items with far shorter designations, which are less readable but also less prone to mistakes. In kubectl, for example, it is much faster and easier to replace the "replicationcontrollers" resource type with the "rc" alias, or the "horizontalpodautoscalers" resource type with the "hpa" alias. Be consistent with the use of aliases -- especially when multiple aliases are available -- to keep the script more readable to others.

3. Know how to use help

Command lines can be difficult to remember with complex syntax and granular options. Developers and administrators can easily feel overwhelmed when they create or review scripts with commands that demand arcane details or are rarely used. Well-designed CLIs provide a comprehensive help system. To access kubectl's help system, use kubectl help at the kubectl command line; help reveals the proper syntax and flag options for desired operations. In addition, the current version reference is readily available with the --version operation. Know how to access logs for operational and debugging details. For kubectl, the logs operation reads and displays logs for a container in a pod.

4. Provide output at regular intervals

Kubectl provides a means to output text to a stdout -- standard output -- device, such as a terminal window. Include output messages to mark important waypoints in the script in case a script takes longer to run than a user expects. This can prevent users from exiting a script improperly because they think the script was hung.

5. Use the dry run for testing

With kubectl's dry run option, the CLI can step through a script without executing any of the operations. The dry run option benefits script testing and debugging. In kubectl, the run operation has a "dry-run=true/false" flag that aids testing and helps avoids unintended consequences on production systems.

Next Steps

Manage Kubernetes clusters with PowerShell and kubectl

An IT ops guide to Kubernetes Job vs. CronJob

Dig Deeper on Containers and virtualization