Getting started with Kubectl

Published on: July 12, 2024 by Jose Angel Morena


Introduction


This isn’t a comprehensive guide on Kubernetes. Assuming you’re already familiar with its complex features and components, we’ll focus on kubectl, including how to use it, some useful subcommands, and helpful tips.



  1. What is kubectl

  2. Installation

  3. How kubectl works

  4. Interesting commands


What is Kubectl?


Kubectl is the command-line tool at the heart of interacting with the Kubernetes API. This guide assumes you have a basic understanding of Kubernetes and its architecture. Here, we dive into the nuances of kubectl, exploring essential commands, tips for efficient usage, and some lesser-known features that can enhance your Kubernetes experience.


Installation


Installing kubectl is the first step to interacting with your Kubernetes cluster. Here’s how to get it up and running on various operating systems:


For Windows Users


Installing kubectl on Windows can be done in a few ways, depending on your preference for manual setup or using a package manager like Chocolatey. For detailed installation instructions, visit the official Kubernetes documentation.


For macOS Users


Installing kubectl on macOS can be done using the homebrew package manager. For detailed installation instructions, visit the official Kubernetes documentation.


For Linux Users


Installing kubectl on macOS can be done using the homebrew package manager. For detailed installation instructions, visit the official Kubernetes documentation.


Verify kubectl Installation


Once installed, you should verify that kubectl is working correctly. Open a new command prompt and type the following command:


kubectl version --client

This command will display the version of kubectl if it is properly installed, ensuring that your setup is ready for use.


Optional Setup: Autocompletion


Enable autocompletion for bash, zsh, or any other shell to speed up your workflow. For bash users, you can typically enable it via:


source <(kubectl completion bash)

Add this line to your .bashrc or .bash_profile to make the change permanent.


How kubectl works


Command Structure:
The basic syntax of a kubectl command is:


kubectl [verb] [object kind] [object name] [options]


  • Verb: Specifies the action to perform, such as get, create, delete, describe, etc.

  • Object Kind: Refers to the type of resource within Kubernetes. Common kinds include pod, service, deployment, and more.

  • Object Name: The name of the specific resource to manage.

  • Options: Additional flags or parameters to refine or modify the command.

Example Usage


Viewing Resources: To list all pods in the default namespace:


kubectl get pods

Creating Resources: To create a deployment using a configuration file:


kubectl create -f deployment.yaml

Modifying Resources: To update the image in a deployment:


kubectl set image deployment/myapp myapp=newimage:tag

Debugging: To inspect what’s happening in a running pod:


kubectl logs my-pod-name

By using different verbs and object kinds, kubectl allows users to manage nearly all aspects of their Kubernetes clusters and applications. Its versatility and robust feature set make it an essential tool for anyone working with Kubernetes.


Use the following command to see the available verbs:


kubectl help

Interesting commands


In this section you will find some interesting more spcific information about kubectl.



  1. Listing All Available Resources

  2. Getting Explanation for a Resource

  3. Using --dry-run=client for Creating Resource Templates

  4. Instant Deployment with Heredoc and kubectl apply

  5. The Beauty of kubectl apply: Declarative Management in Kubernetes

  6. Managing Kubernetes Contexts

  7. Using Plugins with kubectl


Listing all available resources


The kubectl api-resources command is essential for viewing all available resource types in a Kubernetes cluster. Below are some of the most useful options to tailor the output according to your needs:


Commonly Used Options


--namespaced


Shows either namespaced resources or cluster-wide resources.
Example:


kubectl api-resources --namespaced=true

This command will display those resources that belong into a namespace, if you would like to see


Getting Explanation for a Resource


The kubectl explain <resource> command is invaluable for understanding the fields and specifications of any Kubernetes resource type. It provides a detailed description of all the fields associated with a resource, which can be crucial for correctly configuring your YAML files for Kubernetes objects.


Usage


Basic Syntax:


kubectl explain <resource>

This will output a detailed description of the specified resource, including all its fields and their respective types and descriptions.


Example:
To get information about the pod resource:


kubectl explain pod

Extended Usage


You can also use kubectl explain to dive deeper into specific fields within a resource.


Syntax:


kubectl explain <resource>.<field>

Example:
To explore the spec field of a deployment:


kubectl explain deployment.spec

This will provide a breakdown of the spec field for deployments, detailing subfields and their purposes.


Getting Recursive Information


To get a recursive explanation that includes all subfields:


kubectl explain <resource> --recursive

Example:


kubectl explain pod --recursive

This will list all fields of the pod resource, including nested fields, providing a comprehensive overview of what configurations are possible.


These detailed explanations can greatly aid in understanding how to structure Kubernetes manifests and use different Kubernetes resources effectively.


Using --dry-run=client for Creating Resource Templates


When you want to quickly generate a Kubernetes resource template without applying it to the cluster, you can use the --dry-run=client option. This is particularly useful for setting up the skeleton of a resource, which you can then modify as needed before deployment.


Usage


The --dry-run=client option simulates a command without making any changes to the cluster. It allows you to verify the command syntax and output the resulting resource definition to a file, which serves as a customizable template.


Example: Creating a Deployment Template


To create a deployment resource template for an nginx server, you can use the following command:


kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > my_fancy_deployment.yml

This command performs a dry run to generate a deployment YAML for an nginx server and redirects the output to my_fancy_deployment.yml. The file will contain a basic deployment configuration, including the nginx image specification.


Explanation



  • --dry-run=client: Ensures that the command is only simulated on the client side, without contacting the server.

  • -o yaml: Specifies the output format as YAML, which is suitable for configuration files.

  • >: Redirects the output to a file instead of displaying it on the console.

Modifying the Template


Once the YAML file is generated, you can open my_fancy_deployment.yml and edit it to add configurations such as environment variables, volume mounts, or any other specific settings required for your deployment.


Instant Deployment with cat EOF and kubectl apply


Deploying Kubernetes resources directly from the command line can be streamlined using the cat command with a here-document (EOF) and kubectl apply. This method enables the creation and application of resource configurations in a single step, which is particularly useful for quick tests or automation scripts.


How It Works


The cat command can be used to create a here-document (EOF) that contains the YAML configuration of the Kubernetes resource. Piping this directly into kubectl apply applies the configuration to your cluster immediately.


Example Usage


Here is how you can use this technique to create and apply a Kubernetes Deployment for an nginx server:


cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
EOF

Why This Is a Cool Trick



  • Efficiency: This method eliminates the need for creating and managing separate YAML files, making it extremely efficient for quick deployments.

  • Immediate Feedback: You get instant feedback from kubectl, as it applies the configuration right away, which is excellent for debugging and development.

  • Versatility: It's easy to integrate into scripts or automation tools, enhancing the automation capabilities for managing Kubernetes resources.

  • Simplicity: Reduces the complexity in managing multiple files and keeps everything within the command line, simplifying the deployment process.

Using cat EOF and kubectl apply together combines the simplicity of command line management with the power of Kubernetes, making it an effective tool for developers and system administrators alike.


The Beauty of kubectl apply: Declarative Management in Kubernetes


Kubernetes supports both imperative commands (like kubectl set or kubectl rollout) and declarative management. While imperative commands tell Kubernetes how to make a change, declarative commands like kubectl apply focus on what the final state should be. This distinction highlights the true power and elegance of Kubernetes.


Declarative Management with kubectl apply


kubectl apply is used to apply a configuration to a resource by file or stdin. It creates or updates resources in a cluster to match the desired state defined in your files.


Example Usage


You can maintain your Kubernetes manifest files (YAML files) in a version-controlled repository. Whenever you need to update your application or its configuration in the cluster, you can simply update these files and use kubectl apply to synchronize the state:


kubectl apply -f my-kubernetes-deployment.yaml

Advantages of Declarative Management



  • Version Control: You can keep all your configurations in a source control system, allowing for version tracking, rollbacks, and collaboration.

  • Consistency: Applying configurations declaratively ensures that the cluster's state matches exactly what's defined in your files, reducing inconsistencies and surprises in your deployments.

  • Audit Trail: Since all changes are committed in the version control system, it provides a clear audit trail of who changed what and when.

  • Automation Friendly: kubectl apply can be easily integrated into CI/CD pipelines, enabling automated deployments and scaling. This is particularly useful for maintaining consistent environments across development, staging, and production setups.

Integrating into CI/CD Pipelines


A common setup is to have a CI/CD pipeline that automatically runs kubectl apply when changes are pushed to a Kubernetes configuration repository. This ensures that your cluster is always in sync with the repository:



  1. Push Changes: Developers push updates to the YAML files in the repository.

  2. CI/CD Pipeline Triggers: The pipeline detects changes and runs kubectl apply to update the cluster.

  3. Cluster Updates: Kubernetes updates the resources to match the desired state defined in the YAML files.


Conclusion


Using kubectl apply for declarative resource management allows Kubernetes to shine by continuously aligning the live state with the desired state declared in your configurations. It embodies the principle of infrastructure as code and harnesses the full power of Kubernetes' self-healing and management capabilities.


Managing Kubernetes Contexts


Kubernetes contexts are a fundamental component of kubectl configuration, which allow users to manage and switch between multiple clusters easily. A context in Kubernetes essentially encapsulates the settings for a cluster, including the cluster name, user credentials, and namespace.


What is a Context?


A Kubernetes context is a set of access parameters for a specific Kubernetes cluster. Each context contains:
- Cluster: The name of the cluster as defined in the kubeconfig.
- User: The user credentials used to access the cluster.
- Namespace (optional): The default namespace to use with commands applied to this context.


Contexts are extremely useful in scenarios where you need to interact with multiple clusters, such as different environments (development, staging, production) or separate Kubernetes installations.


How to Manage Contexts


Managing Kubernetes contexts involves creating, modifying, and switching between different contexts. This is all managed through the kubeconfig file, which stores your cluster, user, and context information.


Viewing Current Context and All Contexts


To see your current context along with a list of all configured contexts:


kubectl config get-contexts

Creating a New Context


To create a new context, you can define it manually in your kubeconfig file or use the following command:


kubectl config set-context my-new-context --cluster=my-cluster --user=my-user --namespace=my-namespace

Changing the Namespace in the Current Context


kubectl config set-context --current namespace=my-namespace

In order to verify the namespace in the current context, run the following command:


kubectl config view --minify --output 'jsonpath={..namespace}'

Switching Contexts


To switch between contexts:


kubectl config use-context my-new-context

This command sets the current context to my-new-context. All subsequent kubectl commands will use the settings from this context until it's changed again.


Deleting a Context


If you need to remove a context from your kubeconfig:


kubectl config delete-context my-old-context

Using Kubernetes contexts effectively can streamline the process of managing multiple clusters and simplify command execution across varied environments.


Where to Find the kubeconfig File


The kubeconfig file is the file that kubectl uses to configure access to Kubernetes clusters. It contains information about clusters, users, namespaces, and contexts.


Default Location:
- On Linux and macOS, the default location for the kubeconfig file is ~/.kube/config.
- On Windows, the default location is %USERPROFILE%\.kube\config.


If you have not specifically configured kubectl or set up any clusters, this file may not exist. Additionally, you can specify a different kubeconfig file by setting the KUBECONFIG environment variable or by using the --kubeconfig flag with kubectl commands.


How kubeconfig Works


The kubeconfig file can include information for multiple clusters, users, and contexts. Here’s a brief overview of its structure:



  • Clusters: Defines the connection parameters for the Kubernetes clusters.

  • Users: Contains user authentication information.

  • Contexts: Associates a cluster (from the clusters section) and a user (from the users section) and optionally specifies a default namespace.

When you switch contexts using kubectl config use-context, kubectl updates the current-context field in the kubeconfig file.


Using plugins with kubectl


Using plugins with kubectl enhances the functionality of Kubernetes' command-line interface, enabling more efficient management, troubleshooting, and interaction with your Kubernetes clusters. Here’s how plugins can benefit your Kubernetes operations and some notable plugins to consider:


Benefits of Using kubectl Plugins



  1. Extended Functionality: Plugins can extend the capabilities of kubectl beyond what is included out-of-the-box, allowing for custom commands and utilities tailored to specific needs.

  2. Efficiency and Productivity: With plugins, routine tasks can be automated and complex operations can be simplified, which boosts productivity and reduces the scope for errors.

  3. Community-Driven Solutions: Many plugins are developed by the Kubernetes community, so they are often designed to solve common problems faced by a wide range of users.


Popular kubectl Plugins



  1. Krew: Krew is a plugin manager for kubectl that makes it easy to find and install other kubectl plugins. It provides a plugin index and handles the installation, upgrading, and removal of plugins.
    - Installation: Typically, you start by installing Krew itself, and then use Krew to install other plugins.
    - Example command: kubectl krew search to find plugins, and kubectl krew install <plugin-name> to install a plugin.

  2. Kube-ps1: This plugin adds the current Kubernetes context and namespace to your shell prompt, making it clear at a glance which cluster and namespace you’re interacting with.
    - Benefit: Reduces the risk of running commands against the wrong cluster or namespace.

  3. Kubectx and Kubens: These are two simple scripts that allow you to switch between clusters (kubectx) and namespaces (kubens) more easily than with regular kubectl commands.
    - Benefit: Speeds up workflow by simplifying context and namespace switching.

  4. Kube-shell: An integrated shell for Kubernetes that provides features like auto-completion, history, and inline documentation.
    - Benefit: Enhances user interaction with Kubernetes by providing a more interactive and informative command-line experience.

  5. Stern: Stern allows you to tail multiple pods on Kubernetes and multiple containers within the pod. It’s extremely useful for debugging purposes.
    - Example command: stern <pod-name> to follow output from all containers in these pods.

  6. Ksniff: This plugin provides a method for sniffing traffic from a pod. It’s very useful for network debugging and monitoring.
    - Benefit: Allows for real-time network monitoring at the pod level, which is great for troubleshooting network issues.

  7. Kubectl-neat: This plugin cleans up Kubernetes manifests to make them more readable by removing unnecessary or auto-generated fields.
    - Example command: kubectl get pod <pod-name> -o yaml | kubectl-neat


Installing and Managing Plugins


To start using plugins, you should first install a plugin manager like Krew. Once Krew is installed, you can explore the available plugins and install them according to your needs. Each plugin typically comes with its own set of installation instructions and usage guidelines. For more information check out this official Kubernetes documentation.


The End


This is the end of the article, I do hope it provided a nice introduction to kubectl as well as some useful tricks that may help have a better experience. We will keep expanding and possibly simplifying this guide as time goes by.