The kubectl command is how administrators interact with and manage a Kubernetes cluster on a Linux system. It is an essential command line tool that works with all Kubernetes cluster envrionments like Amazon Web Services, Google Cloud Platform, or a cluster on your own hardware (e.g., kubeadm). Managing Kubernetes clusters at scale can be a challenge at first, but mastering the kubectl command will make it much easier.
In this tutorial, we will learn how to manage Kubernetes clusters with the kubectl command. We will explore various command options and see how to effectively use kubectl, as well as some tips and tricks to make using kubectl easier.
In this tutorial you will learn:
How to use kubectl commands against a Kubernetes cluster
Privileged access to your Linux system as root or via the sudo command.
Conventions
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command $ – requires given linux commands to be executed as a regular non-privileged user
Manage Kubernetes Clusters With kubectl
The examples below show some of the most common and essential kubectl commands to use against a Kubernetes cluster in Linux.
To apply a manifest file, which can also deploy an application in Kubernetes, we can use the following syntax:
$ kubectl apply -f ./application.yaml
This can deploy our custom Docker containerized application or one that we retrieve from a central repository, such as Docker Hub.
We can also delete a deployment with the delete parameter. Here are some examples:
$ kubectl delete deployment my-application
Or specify the file:
$ kubectl delete -f application.yaml
Retrieve information about all of the Kubernetes pods in your network with:
$ kubectl get pods
Or the more verbose version, which will show pods in all name spaces:
The kubectl command is also essential when scaling resources. To scale deployment ‘mysql’ to 5 replicas:
$ kubectl scale --replicas=5 deployment/mysql
Or to scale resources as specified in a YAML file:
$ kubectl scale --replicas=5 -f mysql.yaml
To drain all pods from a node (e.g., to perform maintenance on the node without it causing interruptions to the Kubernetes cluster):
$ kubectl drain worker-node
To see all information about your Kubernetes cluster:
$ kubectl cluster-info
Closing Thoughts
In this tutorial, we saw how to use the kubectl command to manage a Kubernetes cluster on a Linux system. Learning how to use kubectl is essential for administrators to create new deployments, pods, and manage nodes from the command line. It also allows us to inspect logs and see a current status of how the cluster and its individual components are operating at any given time.