Lesson 1.5: Anatomy of kubectl commands
Flow Diagram
+-------------------+ +-------------------+ +-------------------+ | kubectl | ----> | API Server | ----> | etcd | | (Client) | <---- | (Server) | <---- | (Database) | +-------------------+ +-------------------+ +-------------------+ ^ ^ | | | | | | | | +-------------------+ +-------------------+ | kubelet | | Node Controller | | (Node Agent) | | (Controller Mgr) | +-------------------+ +-------------------+
Why is kubectl
Required?
kubectl
(pronounced "kube-control" or "kube-cuttle") is the command-line tool for interacting with Kubernetes clusters. It allows you to deploy, inspect, manage, and troubleshoot applications and resources in a Kubernetes cluster.
How kubectl
Commands Work Internally
When you run a kubectl
command (e.g., kubectl get nodes
), it interacts with the Kubernetes API server to retrieve or modify cluster state. Here’s how it works internally:
Step 1: kubectl
Sends a Request to the API Server
kubectl
reads the kubeconfig file (usually located at~/.kube/config
) to determine:- The API server’s address.
- Authentication credentials (e.g., certificates, tokens).
- It sends an HTTP request (e.g., GET, POST, DELETE) to the appropriate API endpoint.
Step 2: API Server Authenticates and Authorizes the Request
- The API server:
- Authenticates the request using the credentials provided by
kubectl
. - Authorizes the request to ensure the user has permission to perform the action (using RBAC or other authorization mechanisms).
- Authenticates the request using the credentials provided by
Step 3: API Server Interacts with etcd
- For commands that read or modify cluster state (e.g.,
kubectl get
,kubectl apply
), the API server queries or updates theetcd
database. etcd
stores the entire state of the Kubernetes cluster, including node information, pod details, and configurations.
Step 4: API Server Processes and Returns the Data
- The API server processes the data from
etcd
and formats it into a response. - The response is sent back to
kubectl
in JSON format.
Step 5: kubectl
Formats and Displays the Output
kubectl
receives the JSON response from the API server.- It formats the data into a human-readable table (or other formats like JSON or YAML, depending on the
-o
flag). - The output is displayed in your terminal.
Example: How kubectl get nodes
Works
When you run kubectl get nodes
, the following steps occur:
kubectl
sends a GET request to the/api/v1/nodes
endpoint.- The API server retrieves node information from
etcd
. - The API server returns the node data to
kubectl
. kubectl
formats the data into a table and displays it in your terminal.
Example output:
NAME STATUS ROLES AGE VERSION node-1 Ready control-plane 10m v1.27.3 node-2 Ready worker 10m v1.27.3 node-3 Ready worker 10m v1.27.3