How To Use Kubectl To Manage Your Kubernetes Clusters

kubectl kubernetes kubernetes certification Sep 14, 2020
How To Use Kubectl To Manage Your Kubernetes Clusters

If you are reading about Kubernetes or learning about it you should already be familiar with the Kubectl command. If not completely but somewhere at basic level maybe. Kubernetes is an open-sourced tool which is originally developed by Google and used for automatic deployment and auto-scaling the containerized applications. In this post we will read about kubectl and how it is use to manage Kubernetes cluster.

 

What is kubectl?

Kubectl is a powerful command line tool that is used for running commands against Kubernetes clusters. It interacts with the Kubernetes API and its shared state to deploy and manage applications on the Kubernetes cluster.

How to install and setup kubectl?

There are various ways to install kubectl to your system. One by downloading binary to your OS and make it executable and install it(specifially for windows). The other way is to clone the source code from Github and build the tool using source for reference you can check Readme file. The most preferred and easy way to do this is to download a ready binary file and execute it to install it into your system.

Let’s see how to install kubectl from binary on different OS

  • Firstly, we need to set up Kubernetes cluster that can be easily done using http://stakater.com
  • If you are on Mac or Linux you need to install tools like wget and curl.
  • It would be great if you have a basic knowledge about commands like mv, chmod, curl, export.

Become a Certified Kubernetes Administrator (CKA)!

 

Following are the steps to install the latest release of kubectl, this covers installation for Linux, MacOs and windows.

Linux and MacOS:

Download kubectl binary

curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/darwin/amd64/kubectl

Move the binary to /usr/local/bin/ directory and make it executable.

 

mv ./kubectl /usr/local/bin/chmod +x /usr/local/bin/kubectl

Make sure /usr/local/bin/ is in your $PATH.

Windows:

For Windows, download the binary from this link and install it like any other normal Windows application.

Become a Certified Kubernetes Administrator (CKA)!

Verify the Kubectl Configuration

After successful installation run the following command to confirm that Kubectl has been configured properly and check the cluster state.

$ kubectl cluster-infoKubernetes master is running at https://192.168.99.100:8443
To further debug and diagnose cluster problems, use ‘kubectl cluster-info dump’.

 

If you get a URL response as an output, then congratulations kubectl is configured correctly and ready to use with your cluster. If you get an error from above command you can dump your cluster configuration for further troubleshooting using the following command:

$ kubectl cluster-info dump

To get less content, pipe to head to filter:

$ kubectl cluster-info dump |head
{
 “selfLink”: “/api/v1/nodes”,
 “resourceVersion”: “29495”,
 “Items”: [
 {
 “name”: “minikube”,
 “selfLink”: “/api/v1/nodes/minikube”,
 “uid”: “86b7bd31-e550–11e7–8389–080027320547”,
 “resourceVersion”: “29493”,
 “creationTimestamp”: “2017–12–20T06:39:27Z”,

Now, as we have installed Kubectl, configured it properly now it’s time to enable shell autocompletion for Kubectl commands.

Kubectl comes with built in bash and zsh completion. The autocomplete feature of Kubectl can save you a lot of time as it improves the productivity by autocompleting flags and objects, e.g. pod names and namespaces. To enable this feature run the following command:

echo “source <(kubectl completion bash)” >> ~/.bashrc

This will add kubectl to your profile so kubectl will be automatically loaded on any new shell invocation and if you are using zsh add these lines to your ~zshrc file.

# kubectl bash completion
if [ $commands[kubectl] ]; then
 source <(kubectl completion zsh)
fi

To update your changes and make them permanent you need to run the following command:

source ~/.zshrc

And to confirm your changes you can run the following command to verify:

$ tail -n 5 ~/.zshrc
# kubectl bash completionif [ $commands[kubectl] ]; then
 source <(kubectl completion zsh)
fi

Now if you type kubectl and press enter, it should list all available options:

$ kubectl <TAB TWICE>
alpha           cluster-info    describe        logs            rolloutannotate        completion      drain           options         runapi-versions    config          edit            patch           scaleapply           convert         exec            plugin          setattach          cordon          explain         port-forward    taintauth            cp              expose          proxy           topautoscale       create          get             replace         uncordoncertificate     delete          label           rolling-update  version

The syntax of Kubectl command is as following:

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

This is a standard syntax and is applicable for all the commands that you run on your terminal. Where CommandTYPENAME, and flags are:

  • Command: This specifies the operation to be performed on a resource, like describe, get, delete, create, run, edit, set, convert, label, scale etc.
  • TYPE: This specifies a resource type. Note that resource types are case sensitive, and can be singular, plural, or abbreviated forms. For example commands pod, pods, po will return same output.
  • NAME: This specifies a resource name, names are case sensitive. If no name is given, details for all resources will be displayed. A resource can be specified by type and name.
  • Flags: Used to specify optional flags which override default values. For example: -s or — server flag is used to specify the address of Kubernetes API Server.

Now we are well aware about the basics of kubectl and now we will see some common kubectl operations that we can perform on Kubernetes cluster.

Become a Certified Kubernetes Administrator (CKA)!

Creating a resource from a file: For creating a resource on Kubernetes with kubectl we can use the following command syntax

$ kubectl create -f FILENAME

Supported file formats are JSON and YAML. So to create a pod from yaml file named pod.yml, you’ll run

$ kubectl create -f ./pod.ymlpod “mytestserver” created

The same pod.yml contents can be passed as stdin to kubectl command as below.

$ cat pod1.yml | kubectl create -f -pod “mytestserver1” created

Listing all the resources: To list one or more resources, kubectl get command is used for this, it supports plain-text output format. A number of resource types are supported. To get all pods in human readable format, use

$ kubectl get pods
NAME            READY     STATUS    RESTARTS   AGEmytestserver    1/1       Running   0          59smytestserver1   1/1       Running   0          32s

If you want to get the output in json format, use json flag:

$ kubectl get pods -o json | head
{
“apiVersion”: “v1”,
“items”: [
{
“apiVersion”: “v1”,
“kind”: “Pod”,
“metadata”: {
“creationTimestamp”: “2018-01-06T07:00:42Z”,
“name”: “mytestserver”,
“namespace”: “default”,

To list all pods with more information, you can use the wide flag as follwing:

$ kubectl get pods -o wideNAME            READY     STATUS    RESTARTS   AGE       IP           NODE
mytestserver    1/1       Running   0          5m        172.17.0.4   minikube
mytestserver1   1/1       Running   0          5m        172.17.0.5   minikube

You can also list more than two resources together by separating them with a comma.

$ kubectl get nodes,jobs,events,pods

Where pods,jobs,events and nodes are resource types. You can also check Kubernetes documentation for all the available resource types.

For displaying detailed state of resources: To display detailed state of a resource with kubectl, the follwing command can be used.

$ kubectl describe pods/<pod-name>

For deleting a resource: You can use the follwing command to delete a resources from either a file or stdin. To delete service defined in a file, you’ll use -f flag followed by the name of the file:

$ kubectl delete -f pod1.yamlpod “mytestserver1” deleted

If you want to exceute a specific command against a kubernetes container in pod the following commands comes handy.

$ kubectl exec web -c <container-name> date

You can replace <container-name> with the name of your container and date with the command to be executed on the container.

$ kubectl exec mytestserver dateSat Jan 6 07:18:22 UTC 2018

Printing the container logs on Prod: Sometimes, we need to check logs to troubleshoot the issues on production environment and that can be achieved using following command:

$ kubectl logs mytestserver
2018/01/06 07:17:43 Starting webserver and listen on :8082

Next command below will return snapshot of previous terminated nginx container logs from pod prod-web

$ kubectl logs -p -c hello-world mytestserver1

You can also stream real time logs using -f flag:

$ kubectl logs -f -c hello-world mytestserver12018/01/06 07:17:43 Starting webserver and listen on :8082

Other options available are — tail and — since

$ kubectl logs –tail=50 mytestserver # Print most recent 50 lines
$ kubectl logs –since=3h mytestserver # Print last 3 hours logs

Forwarding one or more local ports to pod
If your node has a public IP address and you would like to access service port on a container through host system port, you’ll need to forward ports using kubectl port-forward command. The syntax is:

$ kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT

Below command will forward port 80 on the host to port 80 on the on the pod.

$ kubectl port-forward prod-web 80:80

Edit a resource: If we want to edit a resource using kubectl command line tool, the following command can help. It will open the editor defined by your KUBE_EDITOR, or EDITOR environment variables and the fallback is set for vi editor in Linux and notepad in Windows. The default format is YAML. The syntax of command is

$ kubectl edit (RESOURCE/NAME | -f FILENAME)

The follwing command shows how we can edit mytestserver1 using vim editor.

$ KUBE_EDITOR=”vim” kubectl edit pod mytestserver1

Become a Certified Kubernetes Administrator (CKA)!

Apply a configuration to a resource

You can apply a configuration to a resource by filename or stdin. If the resource doesn’t exist yet, it will be created. The formats accepted are JSON and YAML. Consider these examples

# Apply configuration in mypod.yml to a pod
$ kubectl apply -f ./pod.yml
pod “mytestserver” created# Apply the JSON passed into stdin to a pod
$ cat mypod.json | kubectl apply -f –

Convert config files between different API versions

If we want to convert our config files between different API versions we can use kubectl convert command. This support both YAML and JSON formats. An input passed to the command can be a filename, directory, or URL. We can specify the output format using — output-version tag, if no version is specified, latest will be used. We also need to specify the destination using -o flag and the output will be printed to stdout in YAML

Examples:

kubectl convert -f tests/pod.yml # convert to latest version and print on stdout$ kubectl convert -f tests/pod.yml –local -o json # convert and print to stdout in json format$ kubectl convert -f . | kubectl create -f –   # Convert all files in current directory and create them all

Conclusion

So, in this post we have learned about installation and configuration of kubectl and how we can manage Kubernetes cluster using Kubectl command.

Become a Certified Kubernetes Administrator (CKA)!

Join TechCommanders Today. 

Over 60 Courses and Practice Questions! 

Coaching and CloudINterviewACE

Join TechCommanders

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

We hate SPAM. We will never sell your information, for any reason.