• Kloudnative
  • Posts
  • Why Most DevOps Struggle With Kubernetes Commands

Why Most DevOps Struggle With Kubernetes Commands

Discover Smarter Solutions to Streamline Your Operations

In partnership with

Kubernetes ability to manage, scale, and deploy containerized applications seamlessly across clusters has cemented its place in software development and operations. At the heart of Kubernetes lies kubectl, the command-line interface that empowers engineers to interact directly with Kubernetes clusters.

Mastering kubectl commands isn't just a skill; it’s a gateway to unlocking Kubernetes’ full potential. From managing deployments to scaling replicas, troubleshooting pods, and configuring namespaces, these commands provide granular control over resources. For DevOps engineers, knowing these commands means enhanced efficiency in managing workflows, diagnosing issues, and automating routine tasks.

With Kubernetes becoming the backbone of cloud-native environments, a solid understanding of its command-line capabilities ensures engineers can navigate complex systems with confidence and precision, fostering faster deployments and robust system performance.

Getting Started with Kubernetes Commands

Setup Prerequisites

Before diving into Kubernetes commands, setting up a functional environment is critical. Here’s what you need:

1. Kubernetes Cluster (Local or Online):
You can set up a local cluster using tools like Minikube, kind, or access a managed Kubernetes service such as AWS EKS, GCP GKE, or Azure AKS.

Example using Minikube:

# Install Minikube (Linux)
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube

# Start a Kubernetes cluster
minikube start --cpus=2 --memory=2048 --driver=virtualbox

2. Installing and Configuring kubectl:
kubectl is the command-line tool for Kubernetes management.

Installation Example:

# Install kubectl (Linux)
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
sudo mv kubectl /usr/local/bin/

Verify installation:

kubectl version --client

3. Configuring kubectl for Cluster Access:
Ensure kubectl is connected to your Kubernetes cluster by setting up the kubeconfig file. This file stores cluster connection information, including contexts, users, and namespaces.

Example of checking available contexts:

kubectl config get-contexts
kubectl config use-context <context_name>

4. Use a Non-Production Environment:
Always test Kubernetes commands in a safe, non-production cluster. This minimizes the risk of unintended disruptions.

Switching to a test namespace:

kubectl create namespace test-env
kubectl config set-context --current --namespace=test-env

By ensuring these prerequisites, you set up a stable foundation for mastering Kubernetes commands while minimizing risks.

Core Kubernetes Commands

Version and Cluster Details

Understanding the Kubernetes environment starts with basic commands to check the cluster's state and configuration.

1. Fetching kubectl Version:
The kubectl version command retrieves the client and server versions, helping you verify compatibility between your local tool and the cluster.

Example Command:

kubectl version --client --output=yaml

Output Sample:

clientVersion:
  major: "1"
  minor: "27"
  gitVersion: v1.27.3
  platform: linux/amd64

If the server version is missing in the output, this could indicate a connection issue with the cluster.

2. Gathering Cluster Information:
The kubectl cluster-info command provides key details about the control plane services running on the cluster.

Example Command:

kubectl cluster-info

Output Sample:

Kubernetes control plane is running at https://127.0.0.1:6443
CoreDNS is running at https://127.0.0.1:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

If you see an error such as "The connection to the server was refused", check that your kubeconfig file is correctly configured and that the Kubernetes API server is running.

Listing API Resources

Kubernetes provides a variety of API resources (e.g., pods, services, deployments) to manage the cluster. The kubectl api-resources command lists all available resources, their API groups, and the supported verbs (e.g., get, create, delete).

Example Command:

kubectl api-resources

Output Sample:

NAME                     SHORTNAMES   APIGROUP        NAMESPACED   KIND
pods                     po                          true          Pod
services                 svc                         true          Service
deployments              deploy       apps           true          Deployment
nodes                    no                          false         Node

Key Insights:

  • Namespaced vs Non-Namespaced: Resources like Pods and Deployments are namespaced, meaning they exist within a specific namespace, while Nodes are cluster-wide.

  • Shortnames: Short aliases (e.g., po for Pods, svc for Services) make commands more concise.

Practical Tips for Beginners:

Verify Namespace: Always ensure you’re working in the correct namespace. Use:

kubectl config set-context --current --namespace=<namespace_name>

Explore Resource Verbs:
Use kubectl explain <resource> to understand what actions (verbs) can be performed on a resource. For example:

kubectl explain pods

These foundational commands ensure you understand and navigate the Kubernetes environment effectively.

Managing Kubernetes Contexts

Kubernetes contexts allow you to manage multiple clusters seamlessly. A context is a configuration that ties together a cluster, a user, and a namespace. Mastering context commands helps streamline workflows across different environments.

1. Retrieving Kubernetes Contexts:
The command kubectl config get-contexts lists all available contexts from your kubeconfig file, showing details about associated clusters, users, and namespaces.

Example Command:

kubectl config get-contexts

Sample Output:

CURRENT   NAME             CLUSTER          AUTHINFO         NAMESPACE
*         dev-cluster      dev-cluster      dev-user         dev
          prod-cluster     prod-cluster     prod-user        prod

Kloudnative is committed to staying free for all our users. We kindly encourage you to explore our sponsors to help support us.

Streamline your development process with Pinata’s easy File API

  • Easy file uploads and retrieval in minutes

  • No complex setup or infrastructure needed

  • Focus on building, not configurations

☝️ Support Kloudnative by clicking the link above to explore our sponsors!

2. Switching Clusters:
To switch to a specific cluster or environment, use the kubectl config use-context command. This is especially useful when working with staging and production environments.

Example Command:

kubectl config use-context prod-cluster

Confirmation Output:

Switched to context "prod-cluster".

3. Setting Default Namespaces:
Reduce verbosity by setting a default namespace for a context. This prevents the need to specify --namespace in every command.

Example Command:

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

Verification Command:

kubectl config view --minify | grep namespace

Resource Creation and Updates

Creating Resources:

  • kubectl create: Creates resources imperatively.

  • kubectl apply: Reconciles resources declaratively using YAML files, making it ideal for GitOps workflows.

Example Command (Apply):

kubectl apply -f deployment.yaml

Updating Resources:

For incremental changes, use kubectl patch to avoid modifying complete manifests.

Example Command (Patch):

kubectl patch deployment my-deployment -p '{"spec": {"replicas": 5}}'

Managing Deployments and Pods

Listing Resources:

kubectl get pods --namespace=prod
kubectl describe deployment my-deployment

Rolling Out Updates:

kubectl rollout restart deployment/my-deployment
kubectl rollout status deployment/my-deployment

Scaling Pods:

kubectl scale deployment my-deployment --replicas=10

Debugging and Troubleshooting

  • View Logs:

kubectl logs <pod_name>
  • Debug Pods:

kubectl debug pod/my-pod --image=busybox --target=my-container
  • Execute Inside Pods:

kubectl exec -it my-pod -- /bin/sh

Advanced Resource Management

  • Expose Resources as Services:

kubectl expose deployment my-deployment --type=NodePort --port=8080
  • Add/Modify Labels:

kubectl label pod my-pod env=production --overwrite
  • Node Maintenance:

kubectl cordon <node_name>
kubectl drain <node_name> --ignore-daemonsets
kubectl uncordon <node_name>

Monitoring and Output Formatting

  • View Metrics:

kubectl top nodes
kubectl top pods
  • Customize Output:

kubectl get pods -o wide
kubectl get pods -o json

Handy Tricks for Kubernetes Operations

  • Copy Files to/from Containers:

kubectl cp local-file.txt my-pod:/path/inside-container
  • Port Forward for Local Access:

kubectl port-forward pod/my-pod 8080:80
  • Compare Configurations:

kubectl diff -f updated-config.yaml

Best Practices for Kubernetes Commands

  1. Test in a Non-Production Environment:
    Avoid running commands directly on production clusters without prior testing.

  2. Use YAML Configurations:
    Declarative YAML ensures consistency and scalability across environments.

  3. Stay Updated:
    Regularly refer to Kubernetes documentation for new features and commands.

Conclusion

Mastering Kubernetes commands, particularly with kubectl, is not just a technical skill but a core competency for DevOps engineers striving to manage modern, containerized applications effectively. Kubernetes simplifies the deployment, scaling, and management of applications, but its true power lies in how well you can utilize its tools to automate and optimize workflows.

Commands like kubectl get, apply, and rollout provide insights and control, enabling you to manage complex clusters effortlessly. Advanced commands for debugging, patching, and resource management empower you to troubleshoot issues, roll out updates without downtime, and maintain high availability for your applications. By learning to navigate multiple contexts and customize namespaces, you can seamlessly switch between development, staging, and production environments with minimal errors and maximum efficiency.

Ultimately, a deep understanding of kubectl commands translates to confidence in handling live systems, reducing deployment risks, and improving overall system reliability. Regular practice, coupled with exploring YAML configurations and leveraging automation scripts, ensures consistency and repeatability in your workflows.

Stay curious and proactive: explore new Kubernetes features, participate in community discussions, and experiment in sandbox environments. With a disciplined approach to learning and practicing, Kubernetes can become not just a tool but an ally in delivering scalable, resilient, and efficient infrastructure.

Remember, Kubernetes mastery is a journey, not a destination. Embrace the challenges, learn from real-world scenarios, and aim to make cluster management second nature. Whether you're scaling applications or troubleshooting issues, the command line will always be your most powerful ally.

Happy Kubernetting! 🌟

Call to Action