Kubernetes – Kubectl
Kubectl is a command-line software tool that is used to run commands in command-line mode against the Kubernetes Cluster. Kubectl runs the commands in the command line, Behind the scenes it authenticates with the master node of Kubernetes Cluster with API calls and performs the operations on Kubernetes Resources such as Creation, Deletion, Modification, and Viewing Operations. Here the Resources include such as Pod, Service, Deployment, Secrets, ReplicationController, ReplicationSet, Persistent Volumes, etc.
What is kubectl ?
Kubectl is command-line software that helps to run commands in the Kubernetes Cluster. It acts as a bridge between clients and the Kubernetes cluster providing communication through API requests using http or https protocols. It converts the commands entered the command line from a user into API requests and pass to the API server of the Kubernetes master Node with proper Authentication. It helps to manage the containers and deploy apps and other resources to run smoothly.
Kubernetes Internals
In Kubernetes the Orchestration of containerized applications are powered through operations of master and worker nodes. The Internal Resources of Kubernetes brings the robustness in Orchestrating the container applications. The Internals of Kubernetes includes k8s etcd resource for storing distributed key-value pair of configuration, K8s Controller Manager for maintaining desired state of container applications, K8s Scheduler resource for distributed of workloads, k8s API Server resources for acting at front of the control plane in transmission of API calls. These internals resources of the kubernetes provides the seamless features of ensuring scalability, resilience in container management.
Architecture of Kubectl in Kubernetes Cluster
The Kubectl is a client-side tool that acts as a bridge between the users and the K8s cluster. It provides an interactive command-line interface for the users to run the commands with kubectl against the Kubernetes cluster. The Architecture involves once the users/client executes a command through the command line it is authenticated with the master node of k8s Cluster through the Kubernetes API server. Based on the type of API request Kubernetes API server facilitates the orchestration and coordination of Kubernetes resources such as Control Manager, Kubernetes Scheduler, and Etcd resources. within the Kubernetes Cluster. The following Diagram illustrates the above-discussed architecture workflow of kubectl in Kubernetes.
Installation of Kubectl
You can set up the installation of Kubectl on any of the following sources of environment.
-
Linux
-
macOS
-
Windows
Once you install Kubectl on kuba respective environment you can cross-check by running the below command.
kubectl version
In the following screenshot you're versioning details of kubectl:
To know more about of kubectl, please read this cheatsheet: kubectl cheatsheet
Syntax
kubectl [command] [TYPE] [NAME] [flags]
-
Command: This will include the operation mentioned below you want to perform regarding the specific resource.
- Create
- get
- describe
- delete
-
Type: Here you have to mention the specific resource provided by Kubernetes that you want to create like kubernetes pods, Kubernetes namespaces, Kubernetes secrets, Kubernetes deployment, replica sets, and many more. This option is a case-sensitive.
-
NAME: Here we will provide the name which is case-sensitive.
-
flags: This will use to pass the flags like address or port number.
How to run the commands for resources that kubectl provides.
Create a Resource Using Kubectl
In Kubernetes, a resource gets created inside a namespace which resource using which we can create other resources in a separate environment.
First, we are creating a namespace inside which we will create our Pod.
kubectl create namespace geeksforgeeks
We can create a Pod using the below YAML file.
apiVersion: v1
kind: Pod
metadata:
name: geeksforgeeks
namespace: geeksforgeeks
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
The above file is a configuration file using which we are creating a pod of name geeksforgeeks in namespace geeksforgeeksnamespace which is an Nginx server. Similarly, we can create other resources like secrets, replica sets, etc by just changing the name in front of the kind and mentioning the key value in metadata and spec accordingly.
kubectl create -f geeksforgeekspod.yaml
The above discussed commands are implemented in the screenshot, try on implementing this
To Get the Resources
Command to see all the namespaces.
kubectl get namespaces
To see the namespace geeksforgeeksnamespace run the below command.
kubectl get namespaces
Command to see the list of all pods.
kubectl get pods
This will show the pods in the default namespace. To list all the pods in a particular namespace we can pass the flag -n and the name of the namespace with kubectl get pods
command.
kubectl get pods -n <namespace_name>
So if we have to list down the pod that we have created in namespace geeksforgeeksnamespace, run the below command.
kubectl get pod -n geeksforgeeks
Describe a Resource
To describe the resource we have to run kubectl describe command and then mention the resource and the namespace that resource is in.
kubectl describe resource_name -n namespace_name
So now we will describe our pod.
kubectl describe pod geeksforgeeks -n geeksforgeeks
Name: geeksforgeeks
Namespace: geeksforgeeksnamespace
Priority: 0
Node: cluc-control-plane/172.19.0.8
Start Time: Sun, 15 May 2022 11:17:36 +0000
Labels: <none>
Annotations: cni.projectcalico.org/containerID: ce6d80d1a912
a3edda623aeab52c2995aee87e7c225d6258f888d70a36c79b68
cni.projectcalico.org/podIP: 10.244.206.106/32
cni.projectcalico.org/podIPs: 10.244.206.106/32
Status: Running
IP: 10.244.206.106
IPs:
IP: 10.244.206.106
Containers:
nginx:
Container ID: containerd://b265bb64e9cea231b9e52a150f2
1399b4d051000c2c5dc9bc03cf1de42d060ae
Image: nginx:1.14.2
Image ID: docker.io/library/nginx@sha256:f7988fb6c02e0
ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Sun, 15 May 2022 11:19:20 +0000
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount
from kube-api-access-gz2zs (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-gz2zs:
Type: Projected (a volume that contains
injected data from multiple sources)
TokenExpirationSeconds: 3607
ConfigMapName: kube-root-ca.crt
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events: <none>
Creating namespace with name “geeksforgeeks” and creating pod with name “geeksforgeeks” inside this namespace is shown in this screenshot:
Delete the Resources
kubectl delete command is used to delete the resources by passing their name and namespace if we are deleting other resources other than a namespace.
kubectl delete resource resource_name -n namespace_name
Now we will delete the pod and namespace.
kubectl delete pod geeksforgeeks -n geeksforgeeks
You can verify whether the pod is deleted or not by running kubectl get pod -n geeksforgeeksnamespace.
Now we will delete the namespace instead of -n option as follows.
Note
If we delete the namespace before the pod then the pod will delete automatically with other resources in that namespace.
The following screenshot shows the practical deleting pods in namespaces and deleting namespaces:
Popular Commands Usage Of Kubectl
There are many commands in kubectl and their popularity depends on the requirements and its specific Use case. However, here some of the commands list that are some commonly used and popular kubectl commands:
The following command helps in listing all the pods in the specified namespace.
kubectl get pods -n namespace1
The following command is used to describe a Deployment resource in Kubernetes.
kubectl describe deployment <deployment-name>
The following command is used to scale/adjust the replicas for a deployment up or down.
kubectl scale deployment <deployment-name> --replicas=<number>
The following command is used to create a Kubernetes service and to expose the pods to the cluster through a YAML file.
kubectl apply -f <service-definition.yaml>
The following command is used for deleting a specific resource in a Kubernetes such as a pod, or deployment.
kubectl delete pod mypod
The above specific commands you can use depend on the tasks you are going to perform within your Kubernetes cluster. Additionally, it is always a recommended idea to refer the official documentation of Kubernetes for detailed information on kubectl commands and their usage.
How To Run Kubernetes Yaml Code Files With Kubectl ?
By defining the desired resources with Yaml syntax, you can create and run a Kubernetes YAML file using the ‘kubectl’ command for configuring those appliances to the Kubernetes cluster. Here is the step-by-step process of guidelines to create and run the k8s file with kubectl:
Create a Yaml File
On using a text editor create a YAML file describing the specification of resources that to create or modify. For Example a ‘Deployment.yaml’ file is created as a sample.
apiVersion: apps/v1
kind: Deployment
metadata:
name: mydeployment
spec:
replicas: 4
selector:
matchLabels:
app: myapp1
template:
metadata:
labels:
app: myapp1
spec:
containers:
- name: mycontainer1
image: nginx:latest
The following screenshot shows the creation of deployment practically with name “deployment” with replicas – 4
Applying The Configuration
Use the Deployment.yaml file with the ‘kubectl apply’ command to apply the configurations to the Kubernetes cluster. here I am using default namespace, to specify the use -n namespace_name at the end of the command.
kubectl create -f Deployment.yaml
When you are applying the configuration for the first time with the specified yaml file we use create option. i.e., kubectl create -f kubectl apply
can be used for the both creation and updating the configuration of the file ie., kubectl apply -f
The following screenshot shows the practical on updating the deployment configuration file with changing its replicas from 4 to 2.
To Check The Status Of The Resources in K8s
To verify whether the applied configurations of the resources from the file is created or updated successfully or not. Try on running the kubectl get command with the resource name i.e., kubectl get
kubectl get deployments
kubectl get pods
Describing the Resources ( Optional )
For knowing the detailed information about a specific resource, try on specifying resource type and resource type name with kubectl command.
kubectl describe deployment mydeployment
Updating The Resources ( Optional )
To make changes any changes to your resources, you can update the YAML file, and then reapply the configuration using kubectl apply command with
kubectl apply -f Deployment.yaml
Deleting The Resources (Optional)
To delete a specific resource that you created try on running the kubectl delete
command with resource type and resource type name.
kubectl delete -f Deployment.yaml
Features of Kubernetes Kubectl Tool
-
Management of Resources: Kubectl provides efficient management of Kubernetes resources such as pods, deployments, and Kubernetes services in the cluster with seamless interaction over performing operations such as creating, delete, modifying, and list of the resources.
-
Cluster Inspection and Debugging: It is helpful in offering effective commands to inspect and debug the cluster resources. Users can fetch detailed information regarding the resources such as pods, nodes, and configurations for troubleshooting and performance analysis.
-
Context Switching and Multi-Cluster Management: kubectl allows users to support context switching and seamless management of the Kubernetes cluster. It provides effective commands for both switching context and management of k8s cluster with namespaces.
-
Plugin Extensibility: kubectl allows the users the extend its functionality through Krew plugin manager for automation of tasks providing new effective commands to enhance overall user experience.
What are the popular plugins of Kubectl ?
Kubectl plugins help extend the capabilities of the ‘Kubectl’ command. It allows the automation of tasks and introduces specialized commands to increase productivity offering shortcuts and customized options. The following are a few widely used popular kubectl plugins:
-
Krew ( Plugin Manager ): Krew is helpful for users to easily install and update the plugins by simplified management of plugins. It provides a centralized repository by supporting a wide range of plugins to improve the overall experience.
-
kube-ps1 ( Shell Prompt Integration): It offers real-time visibility of current clusters and namespaces through integrating Kubernetes context into the shell prompt. It comes as a lightweight plugin that reduces manual context checks and improves the productivity of the command line.
-
kubectx and kubens (Context Switching ): These plugins are effective in management of k8s resources. ‘kubectx’ helps in effortless switch between the clusters whereas ‘kubens’ helps in simplify the namespace changes. It helps in efficient management of context, reducing the errors in multi-cluster and multi-namespaces.
What Are The Alternatives Tools To The Kubectl ?
For Interacting with Kubernetes clusters in command-line mode, kubectl is the primary and widely used command-line tool offering different features and user experience. Here are some other notable alternative command line tools for Kubectl:
-
OC ( Openshift Command-Line Tool ): The Openshift Command line tool is effective for managing the clusters extending beyond the
Kubectl
functionalities. It provides specific additional features for Openshift environments with commands such as projects, routes and build configurations. It helps in providing a seamless experience for the developers and administrators. -
K9s ( Kubernetes Terminal UI ): Kubernetes Terminal UI is a specific Kubernetes tool offering an interactive and visually-performing terminal UI. It provides a dynamic interface, real-time updates, and efficient navigation. It is a recommended tool for users who prefer the graphical representation of their clusters along with strong command line performance.
-
Helm ( Kubernetes Package Manager ): Helm comes up with a package manager approach for simplifying the application management of Kubernetes. It packages the k8s manifest files into the shareable charts for easy installations, upgrades, and uninstall of applications providing a high level of abstraction compared to Yaml files.
Conclusion
Kubectl stands as a powerfully effective tool for Kubernetes administrators and developers in management and operations over the clusters in multiple environments. It helps with the effortless management of resources, troubleshooting issues, and navigating in complex clusters. kubectl facilitates context-context switching capabilities and extends the functionality with plugins support providing a seamless interaction with containerized applications.