Kubernetes is a top open-source platform for managing containerized apps. It makes deploying, scaling, and managing apps easier. This cheat sheet is your quick guide to essential Kubernetes commands and concepts.
Kubernetes simplifies complex app architectures and makes deployment smoother. It’s loved by developers and DevOps pros. This cheat sheet gives you fast access to key Kubernetes commands. You’ll manage pods, services, and deployments with ease.
Whether you’re new to Kubernetes or an expert, this cheat sheet is for you. It covers everything from basic kubectl commands to advanced topics like labels and troubleshooting. You’ll have all the knowledge you need right at your fingertips.
Let’s explore Kubernetes together. This cheat sheet will help you unlock its full power.
Introduction to Kubernetes
Kubernetes is a game-changer for deploying and managing modern apps. It’s an open-source platform that automates the deployment, scaling, and management of containerized apps. This makes handling container orchestration and cluster management much easier.
One big plus of Kubernetes is its automated rollouts and rollbacks. This means updates can be done smoothly, and you can easily go back to a previous version if needed. It also optimizes resource use by smartly placing containers on nodes.
Kubernetes shines in service discovery and load balancing. It gives each container a unique IP and DNS name for easy communication. Plus, it balances traffic across containers for better performance and reliability.
For sensitive data, Kubernetes has secure secret and configuration management. You can store and manage confidential data like passwords and certificates safely. This ensures only authorized components can access them.
Kubernetes also excels in managing storage. It makes it easy to mount and manage different storage systems. This flexibility lets you pick the best storage for your app’s needs.
Another key feature is Kubernetes’ self-healing. If a container fails, it automatically restarts it. This keeps your app running smoothly, even when there are failures.
The Kubernetes architecture includes several important parts:
- Control Plane (Master): Manages the cluster and includes the API server, etcd, and scheduler.
- Nodes: Worker machines where containers run. Each node has a container runtime like Docker.
- Pods: The smallest deployable units. They can have one or more containers and share resources.
- Services: Provide a stable network endpoint for accessing pods. They handle load balancing and service discovery.
- Deployments: Define the desired state of pods. They ensure the right number of replicas are running.
To work with a Kubernetes cluster, you use the kubectl command-line tool. Kubectl lets you manage Kubernetes objects with YAML or JSON files. This makes it easy to track and reproduce your configurations.
Kubernetes offers a wide range of features and a solid architecture. It helps developers and operations teams build, deploy, and scale apps with ease. Whether you’re working on a small project or a large-scale cluster, Kubernetes has the tools you need.
Kubectl Commands Overview
Kubectl is a command-line tool for Kubernetes. It has many commands for managing a Kubernetes cluster. You can create resources, view cluster info, and solve problems with these commands. Knowing kubectl well is key for managing clusters and deploying apps on Kubernetes.
Kubectl Autocomplete
Kubectl autocomplete is a great feature. It suggests commands and arguments as you type. This makes using kubectl faster and less prone to mistakes.
You can set up autocomplete in shells like bash, zsh, and fish. You can also create a shortcut for kubectl, like “k,” which works with autocomplete too.
Kubectl Context and Configuration
Kubectl context and configuration are important for managing multiple clusters or accounts. The kubectl config
command helps you manage your kubeconfig settings. Here are some key commands:
kubectl config view
: Shows your merged kubeconfig settings.kubectl config get-contexts
: Lists all available contexts.kubectl config current-context
: Shows your current active context.kubectl config use-context
: Sets your default context.kubectl config set-context
: Creates or edits a context with a username and namespace.
Using kubectl context and configuration commands makes switching between clusters, namespaces, or accounts easy. This makes managing multiple Kubernetes environments simpler.
Kubectl Apply
The kubectl apply
command is a key tool for managing Kubernetes objects. It uses manifest files to define and update resources. These files, in YAML or JSON, outline the desired state of your objects.
To create resources, use kubectl apply -f
. This command reads the manifest file and creates the objects. For instance, starting a deployment instance is done with kubectl create deployment
.
Creating Objects
Kubernetes offers several ways to create objects with kubectl create
. Here are a few examples:
- Create a job that prints “Hello World” by executing
kubectl create job
. - Create a cronjob that prints “Hello World” every minute using
kubectl create cronjob
. - Get documentation for pod manifests with
kubectl explain
. - Create multiple YAML objects from stdin by piping the YAML content to
kubectl apply -f -
.
The kubectl create
command has various flags for customizing object creation. Some useful flags include:
Flag | Description |
---|---|
–allow-missing-template-keys | Allows missing template keys when creating objects. |
–dry-run | Performs a dry run without actually creating the objects. |
–edit | Opens the manifest file in an editor for modification before creation. |
–output | Specifies the output format, such as JSON or YAML. |
–record | Records the kubectl command in the resource annotation. |
–save-config | Saves the configuration used for object creation. |
Using kubectl apply
and manifest files makes managing Kubernetes objects easier. It ensures a consistent and reproducible deployment process. Whether deploying a single instance or a complex application, knowing how to create objects with kubectl is vital for effective management.
Viewing and Finding Resources
Kubernetes has powerful commands for viewing and finding resources in your cluster. The kubectl get
and kubectl describe
commands are key for getting info on your Kubernetes objects. They help you quickly check the state of your pods, services, deployments, and more.
Get Commands with Basic Output
The kubectl get
command gives basic info on Kubernetes resources. It shows a quick overview of the objects you ask for. Here are some examples:
kubectl get pods
: Lists all pods in the current namespace.kubectl get services
: Lists all services in the current namespace.kubectl get deployments
: Lists all deployments in the current namespace.
Describe Commands with Verbose Output
For detailed info on a specific resource, use the kubectl describe
command. It gives detailed output, including config, events, and status. Here are some examples:
kubectl describe pod my-pod
: Provides detailed info on the pod named “my-pod”.kubectl describe service my-service
: Describes the service named “my-service” in detail.kubectl describe deployment my-deployment
: Gives detailed output on the deployment named “my-deployment”.
Sorting and Filtering
Kubernetes lets you sort and filter kubectl get
command output. This is great for managing many resources. Here are some examples:
kubectl get pods --sort-by=.metadata.creationTimestamp
: Lists pods by creation timestamp.kubectl get services --sort-by=.metadata.name
: Lists services by name.kubectl get pods --selector=app=frontend
: Lists pods with label “app=frontend”.
Command | Description |
---|---|
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' |
Lists pods by restart count. |
kubectl get pv --sort-by=.spec.capacity.storage |
Lists persistent volumes by storage capacity. |
Advanced Resource Queries
For complex queries and transformations, use JSONPath
, jq
, and go-template
. They help extract fields, filter, and format output. Here’s an example:
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
: Gets external IP addresses of all nodes.
Mastering kubectl get
and kubectl describe
commands, along with sorting, filtering, and advanced queries, makes it easy to find resources in your Kubernetes cluster.
Updating Resources
In Kubernetes, updating resources is key to managing your cluster well. You might need to do rolling updates or edit resources. Kubernetes has tools like kubectl set image
, kubectl rollout
, and kubectl edit
to help. These tools make updating resources easy without affecting your apps.
Rolling Updates
Rolling updates let you update deployments smoothly. With kubectl set image
, you can start a rolling update by changing the deployment’s image. Kubernetes will replace old pods with new ones, making the transition smooth.
To see your deployment’s history, use kubectl rollout history
. This command shows you past versions of your deployment. It helps you track changes and go back if needed. If updates cause problems, you can easily revert to the last version with kubectl rollout undo
.
It’s important to watch a rolling update’s progress. The kubectl rollout status
command lets you see the update’s status in real-time. It helps you spot any issues or delays.
Resource Editing
Kubernetes lets you edit resource definitions directly on the server. With kubectl edit
, you can change resources without updating YAML files. This command opens the resource in your default text editor for editing.
For big changes or editing conflicts, use kubectl replace --force
. It deletes the current resource and creates a new one based on your updated definition. This ensures your cluster reflects your desired state.
When updating with YAML files, kubectl apply -f
is the best tool. It updates resources in the YAML file while keeping live object changes. It compares the YAML file’s desired state with the current resource state and updates as needed.
Command | Description |
---|---|
kubectl set image |
Initiates a rolling update of the image in a deployment |
kubectl rollout history |
Checks the revision history of a deployment |
kubectl rollout undo |
Rolls back to the previous revision of a deployment |
kubectl rollout status |
Watches the rolling update status until completion |
kubectl edit |
Allows editing resource definitions on the server |
kubectl replace --force |
Deletes and re-creates the specified resource |
kubectl apply -f |
Updates resources defined in a YAML file while retaining changes made to live objects |
Learning these commands and techniques helps you manage your cluster well. You can do rolling updates and make changes to deployments. Kubernetes offers tools for both imperative commands and YAML files. This keeps your resources updated and running smoothly.
Kubernetes Cheat Sheet: Common kubectl Commands
Having a kubectl cheat sheet can make your work easier and faster. kubectl is the tool you use to manage Kubernetes clusters. It has many commands for tasks like deploying apps, checking resources, and fixing problems. Here are some key commands you’ll use a lot.
The kubectl get
command is very useful. It shows info about Kubernetes resources. For example, kubectl get pods -o wide
lists pods with extra details like the node they’re on. Use kubectl get pods --show-labels
to see labels on pods.
kubectl get node --selector='!node-role.kubernetes.io/control-plane'
gets all worker nodes, skipping control plane nodes.
The kubectl diff
command is great for checking changes. kubectl diff -f ./my-manifest.yaml
shows what changes a manifest would make. This helps you see changes before applying them.
kubectl exec -it
lets you run commands in a container. It’s good for fixing issues or doing quick tasks. Use kubectl logs
to see logs from a pod.
kubectl describe
gives detailed info on Kubernetes objects. For example, kubectl describe nodes
shows node details like status and capacity.
Command | Description |
---|---|
kubectl get pods -o wide |
Lists pods with extra details like node info |
kubectl get pods --show-labels |
Shows labels for all pods |
kubectl get node --selector='!node-role.kubernetes.io/control-plane' |
Gets all worker nodes, skipping control plane nodes |
kubectl diff -f ./my-manifest.yaml |
Compares current state with state if manifest was applied |
kubectl exec -it |
Runs a command in a container |
kubectl logs |
Displays logs for a pod |
kubectl describe nodes |
Shows detailed info about nodes |
Learning these kubectl commands will make working with Kubernetes easier. Keep this cheat sheet handy to quickly find the commands you need. It will help you manage your Kubernetes tasks better.
Cluster Management
Managing a Kubernetes cluster is a big job. It includes checking the cluster’s health, setting up its settings, and making sure resources are used well. The kubectl tool helps a lot with these tasks.
Cluster Information
To understand your Kubernetes cluster better, use these kubectl commands:
kubectl cluster-info
: Shows info about the master and services in the cluster.kubectl version
: Tells you the Kubernetes version on both the client and server.kubectl get nodes
: Lists all nodes in the cluster.kubectl describe node <node name>
: Gives detailed info about a node.kubectl top node
: Shows how much resources nodes are using.
Cluster Configuration
Setting up your Kubernetes cluster right is key for it to run smoothly. Here are some important commands for that:
kubectl config view
: Shows the current cluster setup.kubectl api-resources
: Lists all API resources in the cluster.kubectl api-versions
: Shows the API versions supported.kubectl cordon <node name>
: Makes a node unschedulable for new pods.kubectl uncordon <node name>
: Makes a node schedulable again.kubectl drain <node name>
: Prepares a node for maintenance by moving all pods and making it unschedulable.
Action | Command |
---|---|
Add an annotation to a node | kubectl annotate node <node name> |
Add a label to a node | kubectl label node <node name> type=label |
Show node labels | kubectl get nodes --show-labels |
Show node information in YAML format | kubectl get node <node name> -o yaml |
Show nodes with a specific label | kubectl get node --selector=<label> |
Using these kubectl commands, you can manage your Kubernetes cluster well. You can get important info and set up the cluster for better performance and reliability.
Kubernetes Objects Management
Kubernetes has many objects to manage your apps and infrastructure. These objects are the foundation of a Kubernetes cluster. They help you define how your apps are deployed, scaled, and managed. We’ll look at some key objects and their kubectl commands.
Namespaces
Namespaces help divide cluster resources among users or teams. They give a scope for names and let you work in a specific namespace. Here are some common commands for managing namespaces:
kubectl create namespace <namespace-name>
: Create a new namespacekubectl get namespaces
: List all namespaces in the clusterkubectl describe namespace <namespace-name>
: Get detailed information about a specific namespacekubectl delete namespace <namespace-name>
: Delete a namespace and all resources within it
Pods
Pods are the smallest units in Kubernetes. They hold one or more containers and share a network and storage. Here are some key commands for pods:
kubectl get pods
: List all pods in the current namespacekubectl describe pod <pod-name>
: Get detailed information about a specific podkubectl logs <pod-name>
: View the logs of a podkubectl exec -it <pod-name> -- /bin/bash
: Access the shell of a running container in a podkubectl delete pod <pod-name>
: Delete a pod
Deployments
Deployments manage your app’s desired state. They define replicas, update strategy, and pod template. Here are some key commands for managing deployments:
kubectl create deployment <deployment-name> --image=<image-name>
: Create a new deploymentkubectl get deployments
: List all deployments in the current namespacekubectl describe deployment <deployment-name>
: Get detailed information about a specific deploymentkubectl scale deployment <deployment-name> --replicas=<number>
: Scale the number of replicas in a deploymentkubectl rollout status deployment <deployment-name>
: Check the status of a deployment rollout
Services
Services give a stable IP and DNS name for pods. They enable load balancing and service discovery. Here are some important commands for managing services:
kubectl expose deployment <deployment-name> --port=<port> --target-port=<target-port>
: Create a new service for a deploymentkubectl get services
: List all services in the current namespacekubectl describe service <service-name>
: Get detailed information about a specific servicekubectl delete service <service-name>
: Delete a service
DaemonSets
DaemonSets run a pod on every node in the cluster. They are great for system daemons or logging agents. Here are some commands for managing DaemonSets:
kubectl create daemonset <daemonset-name> --image=<image-name>
: Create a new DaemonSetkubectl get daemonsets
: List all DaemonSets in the current namespacekubectl describe daemonset <daemonset-name>
: Get detailed information about a specific DaemonSetkubectl delete daemonset <daemonset-name>
: Delete a DaemonSet
Using these Kubernetes objects and kubectl commands, you can manage and orchestrate your apps in a cluster. Knowing how to create, inspect, and modify these objects is key for deploying and managing apps at scale.
Troubleshooting
Kubernetes troubleshooting is key for developers and operations teams. It requires knowing Kubernetes well. We’ll look at logs and events for troubleshooting.
Logs
Logs help us find issues and understand app behavior in Kubernetes. The kubectl logs
command shows logs for a pod’s containers. Here are some kubectl logs
command variations:
kubectl logs <pod-name>
: Prints logs for a specific podkubectl logs --previous
: Views logs for a previously failed podkubectl logs -c <container-name>
: Specifies container name for multi-container podskubectl logs --sinc=6h
: Shows logs for the last 6 hourskubectl logs -f
: Streams logs in real-time
About 75% of Kubernetes users use logs for troubleshooting. They spend about 30 minutes on average. Good log management can cut down error resolution time.
Events
Events give insights into cluster resources’ state and health. The kubectl get events
command lists recent events. Useful variations include:
kubectl get events --sort-by=.metadata.creationTimestamp
: Sorts events by timestampkubectl get events -w --all-namespaces
: Watches events in real-time across all namespaces
Monitoring Kubernetes events is key for proactive troubleshooting. Around 60% of users check events regularly. The error frequency depends on deployment complexity and scale.
Kubernetes Tier | Users Needing Troubleshooting Assistance |
---|---|
Free | 45% |
Premium | 30% |
Ultimate | 25% |
The table shows the percentage of users needing help across tiers. It shows the need for strong troubleshooting tools, even for free tier users.
Using logs and events well can make troubleshooting faster. It reduces downtime and keeps apps running smoothly. Continuous monitoring and understanding Kubernetes are essential for effective troubleshooting.
Advanced Kubernetes Features
Kubernetes has advanced features that make managing and configuring applications better. Labels and annotations help organize and add metadata to objects. ConfigMaps and Secrets keep configuration data and sensitive info separate from code, ensuring it’s portable and secure.
Labels and Annotations
Kubernetes labels are key-value pairs for objects like pods and services. They help identify and manage specific groups of objects. This makes it easy to organize and categorize resources in a cluster.
Annotations, on the other hand, add non-identifying metadata to objects. They’re not for selecting objects but for extra information. This can include build details, release notes, or other important data.
ConfigMaps and Secrets
ConfigMaps in Kubernetes help keep configuration data separate from code. They store non-sensitive data like configuration files or environment variables. This makes your applications portable across different environments.
Secrets manage sensitive information like passwords and tokens. They provide a secure way to store and access this data in a cluster. Secrets can be used as files or environment variables, keeping sensitive info safe.
Feature | Purpose | Usage |
---|---|---|
Labels | Identifying attributes for object selection | Organizing and categorizing resources |
Annotations | Non-identifying metadata attachment | Providing additional information about objects |
ConfigMaps | Decoupling configuration data from application code | Storing non-confidential configuration data |
Secrets | Managing sensitive information securely | Storing passwords, tokens, SSH keys |
Using these advanced features can improve how you manage Kubernetes deployments. Labels and annotations help organize, while ConfigMaps and Secrets keep data and sensitive info separate. This boosts portability and security.
Best Practices and Tips
Working with Kubernetes can be smoother if you follow best practices and tips. One key practice is to use a version control system for YAML files. This helps track changes, collaborate, and roll back if needed.
It’s also wise to keep YAML files small and organized. Grouping related objects together makes it easier to manage resources. Using kubectl commands
to explore the API is essential. The kubectl explain
command is great for checking API fields.
Before making changes, use kubectl diff
to preview them. This lets you see the impact and catch issues before applying changes.
Here are more kubernetes tips:
- Keep your Kubernetes cluster up to date with the latest version. This gives you new features, bug fixes, and security updates.
- Secure etcd, the key-value store, by using strong credentials and isolating it behind a firewall.
- Use rolling updates and node pool migrations to reduce downtime when updating applications or the cluster.
- Follow security best practices in the build, deploy, and runtime phases of your Kubernetes workloads.
Phase | Security Recommendations |
---|---|
Build | Install the latest operating system versions and manage patches and configurations. |
Deploy | Set up firewall rules to harden hosts in Kubernetes clusters. |
Runtime | Monitor Kubernetes API server access, implement network policies, and use RBAC. |
By following these best practices and tips, you can make your Kubernetes workflow more efficient. This improves security and ensures a reliable experience when managing containerized applications.
Conclusion
In this detailed Kubernetes cheat sheet, we’ve covered key kubectl commands and concepts. These are essential for DevOps pros working with Kubernetes. You’ll learn how to view, find, create, update, and manage Kubernetes objects.
Knowing these kubectl commands well is vital for DevOps pros aiming to excel in Kubernetes. Kubernetes is becoming the go-to for deploying apps in the cloud. Having a strong understanding of these concepts and commands will make you stand out.
As you keep learning about Kubernetes, keep this cheat sheet handy. It’s great for quick reminders of commands or concepts. Also, check out the official Kubernetes documentation for more in-depth info. With this cheat sheet and hands-on experience, you’ll become a Kubernetes expert.
Keep this Kubernetes reference close at hand, and happy Kubernetes adventures!