100 Kubernetes Tips & Useful Tricks With Usecases Part 1,2,3,4,5
100 Kubernetes Tips & Useful Tricks With Usecases Part 1,2,3,4,5
2. Get Resources
kubectl get all
• Use Case: Safely evacuate all pods from a node for maintenance.
• Use Case: Monitor the usage of CPU and memory resources across nodes in the
cluster.
• Use Case: Assign labels to nodes to target them with specific pods that require
higher specifications.
• Use Case: Fetch detailed information about a node, including its status, labels,
conditions, and assigned pods.
• Use Case: Apply a taint to a node to prevent pods from being scheduled on it unless
they tolerate the taint.
• Use Case: Update a specific aspect of a running pod, such as the container image.
• Use Case: Decode and view Kubernetes secrets, which are stored encoded by default.
• Use Case: Save the current state of a deployment or any other resource to a YAML
file for backup or replication.
• Use Case: Restart all pods in a deployment, useful for refreshing the application
without changing the deployment configuration.
• Use Case: Customize the output of kubectl commands to display specific data fields
in a specified format.
• Use Case: Switch the default namespace of the current context, simplifying
commands that follow.
• Usage:
• Use Case: Manage application configuration with Kustomize, which allows for
template-free customization of multiple Kubernetes manifests.
• Use Case: Ensure that the minimum number of replicas of an application remain
available during voluntary disruptions.
33. Schedule Jobs for Specific Times
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: example-cronjob
spec:
schedule: "*/5 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: example-container
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
• Use Case: Run batch jobs at specific times using CronJob resources.
• Use Case: Launch an interactive shell session within a pod for troubleshooting and
debugging.
• Use Case: Use a temporary pod with network troubleshooting tools to test and
debug network policies.
• Use Case: Identify pods that have been evicted due to resource constraints or node
failures.
• Use Case: Quickly create a service that exposes a deployment externally, allocating a
public IP if on a supported cloud provider.
38. Force Delete Pods in Terminating State
kubectl delete pods [POD_NAME] --grace-period=0 --force
• Use Case: Forcefully delete pods that are stuck in a terminating state, which can
occur due to various issues.
• Backup:
• Restore:
• Use Case: Safeguard and recover the Kubernetes cluster's state by backing up and
restoring the Etcd datastore.
• Command:
• Use Case: Tail logs from multiple pods matching the name pattern, useful for
debugging applications spanning multiple pods.
• Use Case: Ensure pods are scheduled on nodes in specific availability zones,
enhancing performance and reliability.
• Use Case: Scale applications dynamically based on custom metrics like processed
packets, optimizing resource use and application responsiveness.
• Use Case: Prioritize critical service pods over others, ensuring they are scheduled and
run preferentially.
• Use Case: Enhance security by default denying all ingress and egress traffic in
sensitive namespaces, requiring explicit allowances.
• Use Case: Identify which components or services are consuming the most CPU
resources on the API server, helping in diagnosing performance issues.
• Use Case: Ensure that services handle termination signals gracefully, allowing them
to finish critical tasks before shutdown.
• Use Case: Define storage classes with different performance characteristics, such as
SSDs for high-throughput applications.
• Use Case: Collect logs from all nodes and pods, forwarding them to a central logging
service like Elasticsearch for more sophisticated analysis.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-egress
namespace: default
spec:
podSelector:
matchLabels:
role: gateway
egress:
- to:
- ipBlock:
cidr: 1.2.3.4/32
Use Case: Regulate and monitor outbound traffic from your cluster to meet
compliance and security requirements.
• Use Case: Execute preliminary setup tasks before the main application starts,
ensuring that all dependencies or prerequisites are met.
• Use Case: Automatically identify and remove nodes that are not in the 'Ready' state,
ensuring the cluster's health and reliability.
• Use Case: Enforce specific CPU and memory limits at the namespace level to prevent
any one project from consuming excessive cluster resources.
• Use Case: Deploy pods using a custom scheduler tailored to specific needs or
optimizations, instead of the default Kubernetes scheduler.
• Use Case: Secure your Kubernetes environment by specifying who can access which
resources, ensuring users only have the necessary permissions.
55. Advanced Pod Scheduling with Affinity and Anti-Affinity
apiVersion: v1
kind: Pod
metadata:
name: with-pod-affinity
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: security
operator: In
values:
- S1
topologyKey: "kubernetes.io/hostname"
containers:
- name: myapp
image: myapp
• Use Case: Place pods based on the labels of other pods and the nodes they are
located on, enhancing the co-location or distribution of workloads across the cluster.
• Configuration:
• Use Case: Protect sensitive data, ensuring that secrets like passwords or API keys are
encrypted in storage, not just in transit.
• Use Case: Automatically add an Istio sidecar proxy to eligible pods within a
namespace to secure and manage network traffic.
• Use Case: Display current CPU and memory usage for each container in a pod,
helping in quick diagnostics and resource management.
• Install Cert-Manager:
• Use Case: Automate the issuance and renewal of SSL/TLS certificates, ensuring secure
communication within the cluster.
• Use Case: Safely evacuate all pods from a node while respecting Kubernetes' data
management policies, ideal for performing maintenance or upgrades without data
loss.
kubectl apply -f
https://raw.githubusercontent.com/kubernetes/autoscaler/master/vertical-
pod-autoscaler/deploy/recommended.yaml
• Use Case: Automatically adjust the CPU and memory reservations of pods based on
their usage, optimizing resource allocation.
• Use Case: Define rules that restrict how pods communicate with each other,
improving the security posture of your environment by preventing unauthorized
access.
• Install Velero:
• Use Case: Establish a default deny all network posture, forcing all traffic to be
explicitly permitted, which enhances the security of pod communications.
• Command:
• Use Case: Run the CIS Kubernetes Benchmark to check for dozens of common best-
practices around deploying Kubernetes securely.
• Use Case: Ensure that your applications are running smoothly and are accessible with
probes that check the health of containers.
70. Optimize Cluster Logs with EFK Stack (Elasticsearch, Fluentd, Kibana)
• Setup:
kubectl apply -f https://github.com/elastic/cloud-on-
k8s/tree/master/config/samples
• Use Case: Centralize logging across the cluster for better insights and debugging
capabilities using a robust logging stack.
• Use Case: Schedule regular database backups to ensure data durability and
recoverability.
• Setup Istio:
• Use Case: Enhance security, observability, and traffic management of services with a
service mesh that offers fine-grained control and encryption.
• Integration:
• Use Case: Secure, store, and tightly control access to tokens, passwords, certificates,
and other secrets in modern computing environments.
• Use Case: Manage stateful applications with stable, unique network identifiers, stable
persistent storage, and ordered deployment and scaling.
• Use Case: Manage configuration data and sensitive information separately from the
pod specification, allowing for easier application configuration and security.
allowPrivilegeEscalation: false
• Use Case: Update applications with no downtime by ensuring that the new version is
tested and rolled out gradually while the old version is still running.
• Use Case: Monitor resource usage of nodes and pods in your cluster, enabling auto-
scaling and more informed resource allocation decisions.
• Setup Dashboard:
kubectl apply -f
https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/re
commended.yaml
• Use Case: Access an intuitive web-based user interface for managing and
troubleshooting Kubernetes cluster resources.
• Install Kured:
kubectl apply -f
https://github.com/weaveworks/kured/releases/download/1.6.1/kured-
1.6.1.yaml
• Use Case: Use Kured (KUbernetes REboot Daemon) to safely automate node reboots
after security updates, minimizing manual intervention and maintaining security
compliance.
• Use Case: Secure all data in transit within the cluster by enabling mutual TLS,
ensuring that all communications between services are encrypted.
• Install Stash:
• Use Case: Implement a robust backup and recovery strategy for Kubernetes
resources and persistent volumes, ensuring data integrity and availability.
• Use Case: Enforce fine-grained, context-aware policies across the Kubernetes stack to
maintain compliance and governance standards.
95. Optimize Cost with Spot Instances
apiVersion: autoscaling.k8s.io/v1
kind: ClusterAutoscaler
metadata:
name: cluster-autoscaler
spec:
behavior:
scaleDown:
enabled: true
utilizationThreshold: 0.5
• Use Case: Leverage spot instances for non-critical workloads to significantly reduce
costs without compromising performance.
• Setup ArgoCD:
• Use Case: Manage and synchronize Kubernetes resources directly from Git
repositories, enabling version-controlled and declarative infrastructure.
• Install Loki:
kubectl apply -f
https://raw.githubusercontent.com/grafana/loki/main/production/ksonnet/loki
/install.yaml
• Use Case: Manage multiple Kubernetes clusters as a single entity with unified
deployment and scaling strategies, improving global availability and load distribution.
kubectl apply -f
https://raw.githubusercontent.com/datreeio/datree/blame/main/installation.y
aml
• Use Case: Utilize service mesh capabilities to control traffic flow, implement
advanced routing rules, and gain in-depth telemetry insights.