Mastering Kubernetes - structure, efficiency and control in the cluster

 

Kubernetes is the leading open source system for orchestrating containers - and for good reason. It offers tremendous flexibility and scalability, but also has a steep learning curve. For beginners, the sheer volume of concepts and commands can be overwhelming. But even experienced users sometimes lose track when it comes to finding the right command at the right time.

This is exactly where our Kubernetes 101 CheatSheet comes in: it is your practical companion that provides you with the most important basics, commands and tips in a compact format. Whether you are setting up your first cluster, preparing for an interview or simply want to work more efficiently - this overview will help you to better understand and use Kubernetes.

Let's unravel the complexity together and make Kubernetes manageable!

Within this blog post we will only look at the most important Kubernetes Commandline Interface commands. If you would like to learn more about Kubernetes or would like to take a look at what Kubernetes is and does in advance, please take a look at this blog post from us: https://www.mceikens.de/wir/blog/kubernetes.

 

The commands - your toolbox for Kubernetes

Kubernetes may seem complex at first glance, but with the right commands you can manage your clusters efficiently. In this section, we'll introduce you to the essential kubectl commands that every Kubernetes user should know. Whether you want to create resources, check the status of your applications or fix errors - these commands provide you with the basis for your daily work.

1. Explore cluster and resources

Before you can make changes to your Kubernetes cluster, you need to understand how your cluster is structured and what state the resources are in. The following commands will help you to get a comprehensive overview and dive deeper into the details.

kubectl cluster-info

Provides basic information about the cluster, including the URLs of the API server and other important services. Ideal for ensuring that your cluster is running correctly.

kubectl get nodes

Lists all nodes in the cluster and shows their status (e.g. Ready, NotReady). Useful for checking whether all nodes are active and ready for use.

kubectl get nodes
NAME             STATUS    ROLES    AGE    VERSION  
node-1           Ready     worker   10d    v1.27.0  
node-2           Ready     worker   10d    v1.27.0  
master-1         Ready     master   10d    v1.27.0  
kubectl top nodes

Shows the current resource utilization (CPU and memory) for all nodes. Practical for detecting overloads at an early stage.

1.2 Exploring resources at the top level

kubectl get pods

Lists all pods in the current namespace. You can optionally search specific areas with -A (all namespaces) or --namespace=<NAMESPACE>.

kubectl get pods -A  
NAMESPACE     NAME                      READY   STATUS    RESTARTS   AGE  
default       my-app-56f4d9c7f6-lz8km   1/1     Running   0          5h  
kube-system   coredns-5f5fd65b9b-7kfnl  1/1     Running   0          10d  
kubectl get deployments

Displays all active deployments, including their replicas and status.

kubectl get deployments
NAME           READY   UP-TO-DATE   AVAILABLE   AGE  
my-app         2/2     2            2           3d  
kubectl get services

Gives you an overview of all services running in the cluster, including their cluster IP and ports.

kubectl get services
NAME           TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE  
my-service     ClusterIP      10.96.0.1       <none>        80/TCP         3d  

1.3 Retrieving detailed information

kubectl describe node <NODE_NAME>

Shows detailed information about a specific node, including capacity, resources used, labels and taints.

kubectl describe pod <POD_NAME>

A detailed view of a pod, including events, specifications and logs. Ideal for troubleshooting when a pod is not working as expected.

kubectl get events

Lists the most recent events in the cluster, e.g. pod restarts, failed containers or network problems.

1.4 YAML output for deeper insights

If you need more technical details, you can output the resources in YAML or JSON formats.

kubectl get pod <POD_NAME> -o yaml

Displays the complete YAML definition of a pod, which you can also use for reproduction or debugging purposes.

1.5 Filtering and sorting cluster resources

Filter by labels:
Labels make it possible to find specific resources.

 

kubectl get pods -l app=my-app  

Sort by age:
With --sort-by you can sort the output based on attributes, e.g. by the age of the pods.

 

kubectl get pods --sort-by=.metadata.creationTimestamp

With these commands, you are well equipped to understand and effectively manage your cluster - from the surface to the depths of the configurations.

 

Full control over your containers!
Benefit from our comprehensive expertise in Kubernetes - the key technology for container orchestration. We support you in managing your applications efficiently, scaling them dynamically and keeping them highly available at all times. Whether consulting, development, maintenance or training - we offer you tailor-made solutions to optimally integrate Kubernetes into your infrastructure and automate your processes. Get started now and make your IT future-proof!

 

learn more   

2. Create and manage resources

The heart of working with Kubernetes is creating, updating and managing resources. This is all about YAML files and the powerful flexibility that kubectl offers you. Below you will learn how to create and manage various resources efficiently.

2.1 Creating resources

Resources are usually created in Kubernetes by applying YAML or JSON manifests.

kubectl apply -f <DATEI>

Applies a manifest and creates the resources defined in it.

# Beispiel: Deployment-Manifest (my-deployment.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: nginx
        image: nginx:latest

With the command:

kubectl apply -f my-deployment.yaml

the NGINX Deployment Manifest can be created.

kubectl create <RESSOURCENART>

Creates a resource directly from the command line. This is useful for simple resources such as ConfigMaps or namespaces.

kubectl create namespace my-namespace
kubectl create configmap my-config --from-literal=key=value
kubectl run

Quick commands to start pods directly. Useful for development purposes, but not recommended for production environments.

kubectl run nginx --image=nginx:latest --port=80

2.2 Updating resources

Change management is a core component of Kubernetes work.

kubectl apply -f <DATEI>

Updates a resource if it already exists.
Example: You change the number of replicas in your deployment manifest from 3 to 5 and reapply the manifest:

kubectl apply -f my-deployment.yaml
kubectl edit <RESSOURCENART> <NAME>

Opens the resource in a text editor (by default vi or another configured editor). After saving, the resource is automatically updated.

kubectl edit deployment my-app
kubectl set image

Updates the image of a deployment or pod directly.

kubectl set image deployment/my-app nginx=nginx:1.21.0

2.3 Scaling resources

Scaling is one of the strengths of Kubernetes - whether manual or automatic.

Manual scaling:

 

You can use the following command to change the number of replicas for a deployment:

kubectl scale deployment my-app --replicas=5

Check the status after scaling:

kubectl get pods

Horizontal autoscaling:
Kubernetes also enables automatic scaling based on CPU utilization:

kubectl autoscale deployment my-app --cpu-percent=80 --min=2 --max=10

2.4 Deleting resources

Resources that are no longer required should be removed to free up resources in the cluster

kubectl delete <RESSOURCENART> <NAME>

Removes a specific resource.

kubectl delete pod nginx kubectl delete deployment my-app

Delete with a manifest:

 

If you no longer need the manifest for a resource, you can also use it to remove the resource:

kubectl delete -f my-deployment.yaml

Delete all resources of a type:

 

For example, if you want to delete all pods in a namespace:

kubectl delete pods --all

2.5 Exporting and backing up resources

To ensure that you can reproduce the configuration of resources, you can export them:

kubectl get <RESSOURCENART> <NAME> -o yaml

Exports the current definition of a resource in YAML format.

kubectl get deployment my-app -o yaml > my-app-backup.yaml
kubectl get all -o yaml

Exports all resources in a namespace.

With these commands and techniques, you are well equipped to deploy new applications and services in Kubernetes, adapt existing resources and manage your clusters efficiently.

 

3. Error diagnosis and debugging

Errors and unexpected behavior are inevitable when working with Kubernetes - especially in complex clusters. Fortunately, Kubernetes provides powerful tools and commands to quickly identify and fix the cause of problems. Here you can find out how to efficiently overcome typical challenges.

3.1 Analyze logs

Logs are one of the first places to start when troubleshooting.

Display a pod's logs:

 

kubectl logs <POD_NAME>

Here you get the standard output of the container in the specified pod.

 

Logs of a specific container in a multi-container pod:

kubectl logs <POD_NAME> -c <CONTAINER_NAME>

 

Show continuous logs:

With the -f option, you can track the logs in real time:

kubectl logs <POD_NAME> -f

3.2 Accessing the shell of a container

Sometimes it is necessary to go directly into a container in order to use debugging tools there manually.

Open interactive shell:

 

kubectl exec -it <POD_NAME> -- /bin/bash

For alpine-based containers that do not have a bash shell, you can use sh instead:

kubectl exec -it <POD_NAME> -- /bin/sh

 

Execute a command directly in the container:

kubectl exec <POD_NAME> -- ls /app

3.3 Checking the condition of resources

Inspecting resources is critical to identifying problems.

View details about a pod:

 

kubectl describe pod <POD_NAME>

This command shows events, status details and the pod's container specifications. Search for error messages or unusual events such as CrashLoopBackOff.

 

Check the resource status in the cluster:

kubectl get pods kubectl get deployments kubectl get services

With -o wide you get additional details such as IP addresses and assigned nodes:

kubectl get pods -o wide

3.4 Examining events and system status

Events are a great source of information for understanding what is happening in the cluster.

Show all events:

 

kubectl get events

The output can be filtered by age or type (e.g. warnings).

 

Search for error messages in events:

If a pod does not start, you can check specific events for this pod:

kubectl describe pod <POD_NAME>

3.5 Finding resources in a faulty state

You can use filters and labels to search specifically for problematic resources.

Pods with the status Error or CrashLoopBackOff:

 

kubectl get pods --field-selector=status.phase!=Running

 

Filter by labels:

If you know which labels could cause a problem:

kubectl get pods -l app=my-app

3.6 Investigating network problems

Network problems are one of the most common causes of application errors in Kubernetes.

Test service accessibility:

 

Use curl or wget within a pod to check the accessibility of a service:

kubectl exec -it <POD_NAME> -- curl my-service

 

Test DNS resolution:

kubectl exec -it <POD_NAME> -- nslookup my-service

Provide network diagnostic tools:

If deeper analysis is needed, you can start a temporary debugging pod with tools like curl, ping and traceroute:

kubectl run debug-pod --image=alpine:latest --restart=Never -- sleep 10000 kubectl exec -it debug-pod -- sh

3.7 Fixing CrashLoopBackOff errors

A common problem is that a container constantly restarts.

Check the logs:

 

kubectl logs <POD_NAME>

 

Check startup commands and environment variables:

Look at the definition of the pod:

kubectl describe pod <POD_NAME> kubectl get pod <POD_NAME> -o yaml

 

Reset backoff timer:

Delete the pod so that it restarts with fresh resources:

kubectl delete pod <POD_NAME>

3.8 Monitoring and external debugging tools

In addition to the native Kubernetes tools, there are a variety of observability tools that help you diagnose problems faster and monitor your cluster better. These tools provide deeper insights into metrics, logs and events that go beyond the Kubernetes command line.

Log analysis with the Elastic Stack

The Elastic Stack (formerly ELK: Elasticsearch, Logstash, Kibana) is a powerful toolset for collecting, processing and analyzing logs.

  • Example: Integrating logs from Kubernetes into Elastic Stack
    • Use Filebeat or Fluentd to collect container logs and export them to Elasticsearch.
    • Analyze and visualize the logs in Kibana to detect patterns or anomalies.
  • Advantages:
    • Centralized collection of all logs.
    • Powerful search and filter options.
    • Visual dashboards for in-depth analysis.

 

Metrics monitoring with Prometheus and Grafana

Prometheus is a widely used tool for collecting time series metrics, and Grafana enables the creation of appealing dashboards to visualize this data.

  • Setup:
    • Use Prometheus Operator to install Prometheus in Kubernetes.
    • Use Node Exporter, Kube State Metrics and other exporters to collect metrics from nodes, pods and deployments.
    • Grafana dashboards can be easily imported via the community dashboard library.
  • Use cases:
    • Monitor resources such as CPU, memory, network and pod availability.
    • Create alerts for specific thresholds, e.g. high CPU utilization.
    • Track anomalies such as sudden load spikes.

 

Holistic observability with Datadog or Splunk

Providers such as Datadog or Splunk offer comprehensive observability tools that can combine logs, metrics, traces and infrastructure monitoring.

  • Advantages:
    • Simplified integration in Kubernetes clusters
    • Support for distributed tracing to analyze the performance of applications
    • Dashboards for a complete overview of your cluster and application metrics.
  • Special features:
    • Visualization of Kubernetes workloads in a central view.
    • Advanced features such as APM (Application Performance Monitoring) and security monitoring.

 

Additional tools and strategies

  • Fluentd:
    A flexible log aggregation tool that integrates with many backends such as Elasticsearch, Splunk and Cloud Logging.
  • Jaeger or Zipkin:
    These tools support you with distributed tracing and help you track requests across different services - ideal for microservices architectures.

 

Summary
The combination of these observability tools enables you to comprehensively analyze logs, metrics and traces. This allows you to identify problems more quickly, optimize cluster performance and react proactively to potential bottlenecks. Choose the tools that best suit your requirements and integrate them seamlessly into your Kubernetes environment.

With these techniques and commands, you can effectively diagnose and fix problems in your Kubernetes cluster. A systematic approach is crucial: collect information, analyze the logs and check events and configurations. This will help you get to grips with even the trickiest errors!

Full control over your containers!
Benefit from our comprehensive expertise in Kubernetes - the key technology for container orchestration. We support you in managing your applications efficiently, scaling them dynamically and keeping them highly available at all times. Whether consulting, development, maintenance or training - we offer you tailor-made solutions to optimally integrate Kubernetes into your infrastructure and automate your processes. Get started now and make your IT future-proof!

 

learn more   

4. Context and namespaces

Kubernetes clusters can quickly become complex, especially when multiple teams, environments or projects are working in a single cluster. Contexts and namespaces play a central role in maintaining an overview and making administration efficient.

4.1 Context: Managing connections to clusters and users

A context in Kubernetes defines which cluster, which namespace and which user is used for a specific session. Contexts allow you to switch seamlessly between different clusters or configurations without having to constantly specify all parameters.

 

Show current context:

kubectl config current-context

 

List all available contexts:

kubectl config get-contexts

 

Switch between contexts:

If you are working with several clusters, you can change the context with a simple command:

kubectl config use-context <KONTEXT_NAME>

 

Define a new context:
If a new cluster or user is added, you can add a context:

kubectl config set-context <KONTEXT_NAME> \ --cluster=<CLUSTER_NAME> \ --namespace=<NAMESPACE_NAME> \ --user=<USER_NAME>

 

Remove contexts:

To clean up outdated contexts:

kubectl config delete-context <KONTEXT_NAME>

 

Best practices for contexts:

Give contexts descriptive names, e.g. prod-cluster, staging-cluster, or dev-cluster-user1. Use scripts or tools such as kubectx to make switching between contexts even faster.

4.2 Namespaces: Organizing and isolating resources

Namespaces are the logical unit within a cluster for grouping and isolating resources such as pods, services and ConfigMaps. This is particularly useful when several teams or projects share the same cluster.

  • Standard namespaces:
    Kubernetes includes some predefined namespaces out of the box:
    • default: The namespace for all resources that do not have a specific namespace.
    • kube-system: For Kubernetes system components (e.g. controller, scheduler).
    • kube-public: Publicly accessible resources, especially for cluster documentation.
    • kube-node-lease: For node heartbeat data.

4.3 Creating and managing namespaces

Create a new namespace:

kubectl create namespace <NAMESPACE_NAME>

 

Show all namespaces in the cluster:

kubectl get namespaces

 

Specify namespace for a command:

If you want to work with resources in a specific namespace, you can specify the namespace directly:

kubectl get pods -n <NAMESPACE_NAME>

 

Delete namespace:

Attention: Deleting a namespace removes all the resources it contains!

kubectl delete namespace <NAMESPACE_NAME>

4.5 Best practices for namespaces

  • One namespace per project or team:
    Separate resources by project or team to ensure clear accountability and easier management.
  • Separation of environments:
    Create separate namespaces for development, test and production environments (e.g. dev, staging, prod).
  • Set resource limits:
    With ResourceQuotas and LimitRanges you can ensure that a namespace is only allowed to use a limited amount of resources such as CPU and memory.
apiVersion: v1
kind: ResourceQuota
metadata:
 name: quota
 namespace: dev
spec:
 hard:
   cpu: "10"
   memory: 20Gi
  • Use RBAC (Role-Based Access Control):
    Combine namespaces with RBAC to granularly control access to resources.
    Example: A user may only manage deployments in a specific namespace.

4.6 Tools for namespace management

With the right use of contexts and namespaces, you can make your Kubernetes environment much more structured and secure. They are essential for organizing, isolating and managing resources, especially in clusters with multiple users or projects.

 

Conclusion

Kubernetes is a powerful tool that offers both flexibility and scalability for modern applications. However, its complexity can seem overwhelming at first. With a well-organized approach, clear best practices and a solid knowledge of the most important commands and tools, you can master this complexity.

In this CheatSheet, we've covered basic and advanced topics, from exploring clusters and resources to creating, managing and troubleshooting them. We put special focus on:

  • Cluster exploration: The ability to check the health of your cluster is crucial to prevent problems before they occur.
  • Resource management: Through automation and declarative configuration, you can ensure that your cluster operates efficiently and consistently.
  • Troubleshooting: With logs, debugging commands and modern observability tools such as Prometheus, Grafana or Elastic Stack, you are well equipped to fix problems quickly.
  • Organization with contexts and namespaces: These tools are crucial for creating order in complex clusters and simplifying collaboration between teams.

Whether you're just getting started with Kubernetes or want to deepen your skills, this CheatSheet gives you a practical foundation to build on. Work systematically, use the commands and tools presented, and don't be afraid to consult the extensive Kubernetes documentation or community resources.

Over time, you'll find that Kubernetes is not just a technical tool, but a mindset for running modern, containerized applications. Use it to make your infrastructure more efficient and resilient - and always stay in control of your cluster.