Examples of kubectl commands to know as a system administrator by Marouane April 25, 2024 DevOps

 

Kubernetes, also known as K8S, is a popular container orchestration tool for managing and scaling containerized infrastructure.

kubectl is the common CLI tool we use to query and manage a Kubernetes cluster. kubectl uses the Kubernetes API to view, control, and manage the cluster. It is supported on different platforms and can be easily configured to manage a cluster.

In this article, we will cover some common kubectl commands that help with day-to-day administration of Kubernetes .

Get Kubectl

kubectl is already installed as part of the Kubernetes cluster configuration. If you are managing a cluster from a remote system, you can easily set it up to work with any cluster configuration.

On a Linux/Unix system, you can use the command below to get the latest version of kubectl:

$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

Make sure you place the downloaded binary in a fixed location, add the location to your PATHvariable and make it executable with chmod +xcommand.

On a Windows box, you can download the latest kubectl version available by first obtaining the latest stable version from https://dl.k8s.io/release/stable.txt

And then download it replacing {version}with the late first version using curl like:

$ curl -LO https://dl.k8s.io/release/{version}/bin/windows/amd64/kubectl.exe

For version 1.20.0, here is the curl command:

$ curl -LO https://dl.k8s.io/release/v1.20.0/bin/windows/amd64/kubectl.exe

If you don't have curl on your system, you can also download the kubectl executable using your browseuh like any other download.

For other supported and platform methods, you can find the official guide to getting kubectl here .

Check Kubectl configuration

To check your kubectl configuration, you can run the version command as:

$ kubectl version --client

The general syntax for using kubectl is:

$ kubectl [command] [TYPE] [NAME] [flags]

Set context and configuration

Before using kubectl commands on a Kubernetes cluster, we first need to set the configuration and context. This can be done with the kubectlself command.

To view the current kubectl configuration, use:

$ kubectl config view

To list all available contexts:

$ kubectl config get-contexts

To get the current kubectl context:

$ kubectl config current-context

We can change the context of use using:

$ kubectl config use-context [cluster-name]

To allow adding a new user in kubeconf:

$ kubectl config set-credentials NAME [--client-certificate=path/to/certfile] [--client-key=path/to/keyfile] [--token=bearer_token] [--username=basic_user] [--password=basic_password]

For example, to set only the "client-key" field to the "cluster-admin" without touching the other values, we can use:

$ kubectl config set-credentials cluster-admin --client-key=~/.kube/admin.key

Or, as another example, to set basic authentication for, say, the “cluster-admin” entry, you can specify the username and password as follows:

$ kubectl config set-credentials cluster-admin --username=[username] --password=[password]

If you want to embed the certificate clientate data in the "cluster-admin" entry, the syntax is changed to:

$ kubectl config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true

If you want kubectl to use a specific namespace and save it for all subsequent kubectl commands in this context:

$ kubectl config set-context --current --namespace=[NAMESPACE]

Create objects

kubectl is used to deploy different supported objects in a Kubernetes cluster. Its manifest can be defined in an YAMLor JSONfile with extension .yamlor .ymland .jsonrespectively.

Using the given manifest file, we can create defined resources using the following command:

$ kubectl apply -f [manifest.yaml]

Or to specify multiple YAML files, use:

$ kubectl apply -f [manifest1.yaml] [manifest2.yaml]

To create one or more resources in all manifest files present in a directory:

$ kubectl apply -f ./dir

Or to create resources from a URL:

$ kubectl apply -f [URL]

Or directly from the repository image name like:

$ kubectl create deployment [deployment-name] --image=[image-name]

For example, to deploy a single Nginx web server instance:

$ kubectl create deployment nginx --image=nginx

finally, to deploy resources directly by typing the YAML contained in the CLI without referencing a saved manifest file, try something like:

# Create multiple YAML objects from stdin
cat <<EOF | kubectl apply -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

View/Find Resources

kubectl provides getcommand to list deployed resources, get their details and learn more about them.

To list all services in the default namespace, use:

$ kubectl get services

Similarly, to list pods in all namespaces, the syntax will be:

$ kubectl get pods --all-namespaces

If we need to list more details about deployed pods, use -o widemark as:

$ kubectl get pods -o wide

The syntax for getting deployment details is:

$ kubectl get deployment [deployment-name]

To get the YAML content of a pod we can use -o yamlflag like:

$ kubectl get pod [pod-name] -o yaml

Often we need to get details about Kubernetes resources. The kubectl describe command helps get these details.

We can get more details about a node like:

$ kubectl describe nodes [node-name]

Or the same for pods like:

$ kubectl describe pods [pod-name]

kubectl allows you to sort the output based on a particular field. To list services sorted by service name, use:

$ kubectl get services --sort-by=.metadata.name

Or to get all running pods in the namespace we can try:

$ kubectl get pods --field-selector=status.phase=Running

To retrieve only the external IP addresses of all nodes, if assigned, we can use -o jsonpathflag with the syntax below:

$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

To retrieve the labels associated with a resource, for example pods, try:

$ kubectl get pods --show-labels

To get a list of events but that is sorted by timestamp, we can use -sort-bymark as:

$ kubectl get events --sort-by=.metadata.creationTimestamp

If we want to compare the current state of the cluster against the state the cluster would be in if the manifest was applied, we use diffcommand like:

$ kubectl diff -f ./manifest-file.yaml

Editing resources

Deployed resources were often modified for any configuration changes.

To do a rolling update of, say, "www" containers or, say, a "frontend" deployment by updating their image, we can use:

$ kubectl set image deployment/frontend www=image:v2

We can check deployment history including revision like:

$ kubectl rollout history deployment/frontend

Or to return to aprevjudicious deployment, use:

$ kubectl rollout undo deployment/frontend

We can also return to a revision by specifying --to-revisionmark as:

$ kubectl rollout undo deployment/frontend --to-revision=2

And to check the progress of the status update, we use:

$ kubectl rollout status -w deployment/frontend

For soft restart of deployment, let's say "front-end", use:

$ kubectl rollout restart deployment/frontend

We can specify a JSON manifest to override a pod by passing it to standard input as shown below:

$ cat pod.json | kubectl replace -f -

There may be times when you need to force replace, delete, and then recreate a resource (NOTE: this will also cause a service outage) which can be done like:

$ kubectl replace --force -f [manifest-file]

Tagging a resource (which supports tags) is easy and can be done using:

$ kubectl label pods [pod-name] new-label=[label]

Similarly, an annotation can be added to a resource using:

$ kubectl annotate pods [pod-name] icon-url=[url]

Autoscaling a deployment is possible with:

$ kubectl autoscale deployment [dep-name] --min=[min-val] --max=[max-val]

Here dep-nameis the name of the deployment to autoscale and min-valindicates max-valthe minimum and maximum value to use for autoscaling.

Editing resources

It is possible to edit an API resource in your favorite editor with editcommand.

$ kubectl edit [api-resource-name]

Or to use your own alternative editor, specify KUBE_EDITORas:

KUBE_EDITOR="nano" kubectl edit [api-resource-name]

Resource Scaling

Resource scaling is one of the features supported by Kubernetes and kubectl makes this easy.

To scale a named replica set, say foo to 3, we use:

$ kubectl scale --replicas=3 rs/foo

Or instead we can reference a manifest YAML file to specify the resource to scale like:

$ kubectl scale --replicas=3 -f foo.yaml

We can also scale based on the current deployment st as:

$ kubectl scale --current-replicas=2 --replicas=3 deployment/nginx

Deleting resources

Created resources will be available only requires some modification or deletion. With kubectl we can delete existing resources in several ways.

To delete a pod using the JSON file specification, we use:

$ kubectl delete -f ./pod.json

We can remove pods and services with the same names pod-nameand service-namelike:

$ kubectl delete pod,service [pod-name] [service-name]

If resources are tagged and we need to remove resources with a specific tag, say label-name, we can use:

$ kubectl delete pods,services -l name=[label-name]

To delete all pods and services contained in a namespace, use:

$ kubectl -n [namespace] delete pod,svc --all

Interact with running pods

We can use kubectl to get details about running pods that help administer a Kubernetes cluster .

One of the common commands is to get logs from a pod, which can be done as follows:

$ kubectl logs [pod-name]

Or to dump pod logs with a specific label:

$ kubectl logs -l name=[label-name]

Or to get logs for a specific container like:

$ kubectl logs -l name=[label-name] -c [container-name]

We can also stream logs like we do with Linux tail -fcommand with kubectl -fflag too:

$ kubectl logs -f [pod-name]

Running a pod interactively can be done with kubectl like:

$ kubectl run -i --tty busybox --image=busybox -- sh

Or to run a pod in a specific namespace, use:

$ kubectl run nginx --image=nginx -n [namespace]

You can attach it to a running container with attachcommand:

$ kubectl attach [pod-name] -i

Port forwarding can be done for a pod at runtime with the command below:

$ kubectl port-forward [pod-name] [local-machine-port]:[pod-port]

To run something directly in a pod connection and get the output, use:

$ kubectl exec [pod-name] -- [command]

The above command works if the pod contains a single container. For multi-container pods, use:

$ kubectl exec [pod-name] -c [container-name] -- [command]

To view performance metrics for a given pod and its containers, we can use:

$ kubectl top pod [pod-name] --containers

Or to sort it by a metric, for example CPU or memory, we can achieve this using:

$ kubectl top pod [pod-name] --sort-by=cpu

Interact with nodes and cluster

kubectl can interact with nodes and the cluster. Here are some of the commands that kubectl uses for the same.

To mark a node as unschedulable, use:

$ kubectl cordon [node-name]

To drain a node as part of preparing for maintenance:

$ kubectl drain [node-name]

To mark the node as schedulable again, use:

$ kubectl uncordon [node-name]

To obtain performance measurements related to a node, we can use:

$ kubectl top node [node-name]

To get details about the current cluster:

$ kubectl cluster-info

We can add ally dump cluster state to standard output using:

$ kubectl cluster-info dump

Or to dump to a file, use:

$ kubectl cluster-info dump --output-directory=/path/to/cluster-state

Conclusion

Kubernetes is the buzzword in the industry and knowing how to manage it effectively will always boost your career. kubectl is the main interface for interacting with a Kubernetes cluster and this article demonstrates how powerful this tool is in the hands of an experienced user.

Still, we can only cover a brief overview of what more Kubectl can do. To explore it in more detail and check everything it supports, refer to its official documentation here .

Copyright © Marouane All Rights Reserved

Buy Me a Coffee