Category Archives: kubernetes

Your AKS Pod Says “Running” — But Your App Is Dying. Here’s the PVC Disk Full – The Fix Takes 15 Minutes

An AKS PVC disk full condition is one of the most deceptive problems in Kubernetes operations. When a PersistentVolumeClaim (PVC) fills to 100% on Azure Kubernetes Service (AKS), the pod using it does not crash immediately — and that is what makes it so dangerous. The pod keeps showing Running in kubectl. No alert fires. Everything looks fine. Then suddenly your application starts throwing cryptic errors that seem completely unrelated to disk space.

This guide covers the fix for any workload running on AKS — whether you are running Solr, PostgreSQL, MongoDB, Elasticsearch, Redis, or any other stateful application that writes data to a PVC. The kubectl commands and the recovery steps are identical regardless of what is running inside the pod.

In our case, the workload was Sitecore with Solr on AKS. The disk-full condition showed up as this IndexWriter is closed — a misleading Lucene error that buried the real cause: java.io.IOException: No space left on device. But whether you see that error or a Postgres could not write to file, a MongoDB No space left on device, or an Elasticsearch flood stage disk watermark exceeded — the fix is exactly the same.

In this guide, you will learn how to confirm the root cause, safely expand your Solr PVC on AKS, recover the application, and rebuild the Sitecore index — all without losing any data. In my environment, Sitecore and Solr are deployed as custom Docker images running on AKS.

Prerequisites

  • kubectl configured and connected to your AKS cluster.
  • Permissions to manage PVCs, StatefulSets, Deployments, and pods in your Kubernetes namespace.
  • Solr deployed on AKS using the Azure managed-premium storage class.
  • Access to the Sitecore Control Panel for index management (for the Sitecore-specific recovery step).

Which Workloads Does This Affect?

Any stateful pod that writes data to a PVC can hit this problem. The AKS PVC disk full fix is identical for all of them. What changes is only the application-level error message and the final recovery step. Here are the most common workloads and the errors each one throws when disk space runs out:

  • Solr / Elasticsearch: java.io.IOException: No space left on devicethis IndexWriter is closed
  • PostgreSQL: could not write to file base/pgsql_tmp: No space left on device
  • MongoDB: No space left on device: couldn't open file for writing
  • MySQL / MariaDB: ERROR 3 (HY000): Error writing file '/tmp/...' (Errcode: 28 - No space left on device)
  • Redis: MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist on disk
  • Any custom application pod: write failures, silent data loss, or application-level errors that bury the real No space left on device cause deep in the logs.

💡 The kubectl fix is identical for all workloads — expand the PVC, restart the pod, verify recovery. Only the final application-level recovery step differs per workload.

Why the Error Message Is Always Misleading

The most important thing to understand before you touch anything is this: the top-level error your application throws is almost never the real cause. It is a downstream symptom. Always scroll to the very bottom of the stack trace to find the true root cause.

For Sitecore with Solr, the index rebuild job logs show something like this:

Job started: Index_Update_IndexName=sitecore_jss_web_index
#Exception: System.Reflection.TargetInvocationException
---> SolrNet.Exceptions.SolrConnectionException:
  this IndexWriter is closed
Caused by: org.apache.lucene.store.AlreadyClosedException: this IndexWriter is closed
Caused by: java.io.IOException: No space left on device

Here is the exact chain of events that causes this error. First, the Solr PVC fills to 100% capacity. Next, Lucene tries to merge index segments during the rebuild — a process that requires significant temporary extra disk space. Because no space is available, the write fails. As a result, the IndexWriter closes itself as a safety measure to protect data integrity. After that, Sitecore detects the closed IndexWriter and throws the AlreadyClosedException. Finally, the rebuild job fails — and keeps failing on every retry until the underlying disk problem is resolved.

⚠️ Until you fix the AKS PVC disk full condition, every single index rebuild will fail with the same error — no matter how many times you retry it from Sitecore.

Step-by-Step: AKS PVC Disk Full Fix

Step 1: Confirm the AKS PVC Disk Is Full

Before making any changes, confirm that disk exhaustion is actually the root cause. First, check your PersistentVolumeClaims in the relevant namespace:

kubectl get pvc -n solr

The output will show all PVCs in a Bound status — which looks completely healthy. However, Bound only means the PVC is attached to the pod. It tells you nothing about how much space is actually used inside it:

NAME              NAMESPACE  STATUS  CAPACITY  STORAGECLASS
solr-leader-disk  solr       Bound   10Gi      managed-premium

Next, exec directly into the pod to check actual disk usage:

kubectl exec -it <solr-pod-name> -n solr -- df -h

Look for the mount point where your application stores data — typically /var/solr for Solr, /var/lib/postgresql for Postgres, or /data/db for MongoDB. If you see Use% at 100%, you have confirmed the root cause. Furthermore, grep the pod logs directly for the IOException to be certain:

kubectl logs <solr-pod-name> -n solr | grep -i "no space"

Step 2: AKS PVC Disk Full Fix — Expand the PVC Online

Azure’s managed-premium storage class supports online volume expansion by default. Consequently, you can grow the PVC without stopping the pod, without losing data, and without any application downtime. Note that you can only ever expand a PVC — Kubernetes does not support shrinking.

You have two methods to expand. Choose whichever fits your workflow:

Method 1: kubectl patch (faster — one command)

kubectl patch pvc solr-leader-disk-2023081617 -n solr \
  -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'

Method 2: kubectl edit (visual — easier to verify)

kubectl edit pvc solr-leader-disk-2023081617 -n solr

In the editor, find the spec.resources.requests.storage field and change it from 10Gi to 20Gi:

spec:
  resources:
    requests:
      storage: 20Gi   # changed from 10Gi

After saving, watch the PVC status in real time. You will briefly see FileSystemResizePending — that is completely normal. Wait for it to return to Bound:

kubectl get pvc -n solr -w

The resize typically takes 5–10 minutes on Azure. The pod keeps running and all data remains accessible throughout the entire process.

💡 Pro tip: During a Solr index rebuild, Lucene needs up to 3× the current index size as temporary working space. If your current index is 8Gi, plan for at least 30Gi total — not just 20Gi. The same rule applies to Elasticsearch index merges and PostgreSQL VACUUM operations.

Step 3: Restart the Pod to Complete Recovery

This is the step most guides skip — and it is the one that trips people up most often. Even after the AKS PVC disk is expanded, the application process inside the pod is still in a broken state from the original crash. Simply having more disk space does not automatically fix this. You must restart the pod so the application remounts the expanded volume cleanly and resets its internal error state.

For Solr running as a StatefulSet (the most common AKS setup):

kubectl rollout restart statefulset/solr -n solr

Alternatively, if your workload runs as a Deployment:

kubectl rollout restart deployment/solr -n solr

For other workloads, simply replace solr with your StatefulSet or Deployment name and adjust the namespace accordingly. The restart causes a brief interruption of around 1–2 minutes. As a result of the restart, three things happen automatically — the broken application state is cleared, the expanded volume is remounted with the full new capacity, and the application performs its own internal recovery on startup.

Step 4: Verify the Pod and Disk Are Healthy

Before touching the application layer, confirm the pod is fully healthy at the infrastructure level. First, check that all pods are back in a Running state:

kubectl get pods -n solr

Next, check the pod logs for clean startup output with no errors:

kubectl logs <solr-pod-name> -n solr --tail=50

In addition, confirm the new disk size is visible and showing healthy usage inside the pod:

kubectl exec -it <solr-pod-name> -n solr -- df -h

The mount point should now show 20Gi total with plenty of free space. If it still shows 10Gi, the filesystem resize has not completed yet — wait a few more minutes and check again. If it still has not updated after 15 minutes, the pod restart itself will trigger the filesystem resize on remount.

Step 5: Application-Level Recovery (Per Workload)

Once the pod is healthy at the infrastructure level, perform the application-specific recovery step for your workload. Furthermore, this step varies depending on what was running in the pod:

  • Sitecore + Solr: Log in to Sitecore → Control Panel → Indexing Manager → select sitecore_jss_web_index → click Rebuild. The job should now complete successfully with no IndexWriter errors.
  • Elasticsearch: Check cluster health with GET /_cluster/health. If any indices are red or yellow, trigger a manual shard allocation using the Cluster Reroute API.
  • PostgreSQL: Run VACUUM ANALYZE on affected tables to clean up any incomplete transactions. Check for replication lag if running a replica set.
  • MongoDB: Check replica set status with rs.status(). Run db.repairDatabase() if any collections show corruption flags.
  • Redis: Verify persistence is working again with INFO persistence — confirm rdb_last_bgsave_status: ok.
  • Custom app pod: Trigger whatever write operation was failing before the disk was full. Check the application logs to confirm the error is gone.

How to Prevent AKS PVC Disk Full in the Future

The most frustrating thing about this problem is that it is completely preventable. Here is what we put in place after this incident — and what I recommend for every production AKS deployment running stateful workloads:

  • Set Azure Monitor alerts at 80% PVC usage. By the time you hit 100% it is already too late. An alert at 80% gives you comfortable time to expand before anything breaks. In Azure Portal, go to Monitor → Alerts and create a metric alert on Persistent Volume Used Bytes.
  • Use Prometheus and Grafana on AKS. The kubelet_volume_stats_used_bytes metric gives you real-time disk usage per PVC across every namespace. Pair it with a Grafana dashboard and a Slack alert — you will never be caught off guard again.
  • Start bigger for production. A 10Gi PVC is fine for development. In production, start at 50Gi or more for any write-heavy workload like Solr, Elasticsearch, or PostgreSQL. Storage is cheap — downtime is not.
  • Plan for 3× headroom during operations. Lucene index rebuilds, PostgreSQL VACUUM, and MongoDB compaction all need temporary space that can be 2–3× the current data size. Always leave enough headroom before triggering these operations.
  • Schedule regular maintenance operations. For Solr, run periodic OPTIMIZE commands to merge segments and reduce disk footprint. For Postgres, schedule regular VACUUM. These can reduce disk usage by 20–40% over time.
  • Verify allowVolumeExpansion on your storage class. Run kubectl describe storageclass managed-premium and confirm AllowVolumeExpansion: true is set. Azure managed-premium and managed-csi-premium both support it by default — but custom storage classes may not.

Conclusion : AKS PVC Disk Full Fix in Under 15 Minutes

An AKS PVC disk full condition is one of the most deceptive problems in Kubernetes operations. The pod stays Running, no obvious alert fires, and the error your application throws is almost never the one that points to disk space. In our case it was this IndexWriter is closed for Sitecore Solr — but it could just as easily be a Postgres write failure, a MongoDB corruption error, or a Redis persistence warning.

In summary, the fix is always the same three steps — confirm the disk is full with df -h inside the pod, expand the PVC online using kubectl patch or edit, and restart the pod to clear the broken application state. Furthermore, the entire process takes under 15 minutes and preserves all your data completely. Most importantly, it is 100% preventable with the right Azure Monitor alerts in place before the next incident hits.

Quick Reference: Commands for AKS PVC Disk Full Fix

  • Check PVCs: kubectl get pvc -n <namespace>
  • Check disk inside pod: kubectl exec -it <pod> -n <namespace> -- df -h
  • Grep for disk error: kubectl logs <pod> -n <namespace> | grep -i "no space"
  • Expand PVC: kubectl patch pvc <name> -n <namespace> -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'
  • Watch resize: kubectl get pvc -n <namespace> -w
  • Restart StatefulSet: kubectl rollout restart statefulset/<name> -n <namespace>
  • Restart Deployment: kubectl rollout restart deployment/<name> -n <namespace>
  • Verify pod health: kubectl get pods -n <namespace>

Frequently Asked Questions

Q: Will expanding the PVC delete my data?
No. PVC expansion on AKS is completely non-destructive. Azure grows the underlying managed disk and extends the filesystem. Your data — whether it is Solr index segments, Postgres tables, or MongoDB collections — is fully preserved throughout.

Q: Does the application go down during PVC expansion?
No. The disk expansion itself causes zero downtime. The only brief interruption — around 1–2 minutes — happens when you restart the pod in Step 3. The application itself stays up during the disk resize.

Q: Can I shrink the PVC back after fixing the issue?
No. Kubernetes does not support PVC shrinking. Once expanded, the size is permanent. Plan your initial PVC sizes carefully — especially for production write-heavy workloads.

Q: The df -h still shows the old size after PVC expansion. Why?
The Kubernetes PVC resize and the filesystem resize inside the pod are two separate operations. If the filesystem has not caught up, wait a few more minutes and recheck. If it still shows the old size after 15 minutes, the pod restart in Step 3 will trigger the filesystem resize on the next mount.

Q: My storage class does not support volume expansion. What do I do?
Run kubectl describe storageclass <name> and check for AllowVolumeExpansion: true. If it is not set, you will need to provision a new larger PVC and migrate the data manually using a tool like kubectl cp or a pod-to-pod rsync job.

Q: I have multiple Solr leader and follower PVCs. Do I need to expand all of them?
Yes. Expand every PVC that is full. If only the leader PVC is full, start there — but check the follower PVCs too, as they often fill at a similar rate.

Related Articles

SNAT Port Exhaustion in AKS: The Silent Killer of Outbound Connectivity (Step-by-Step Fix)

For cloud engineers and DevOps professionals managing applications on Azure Kubernetes Service (AKS), one of the most common yet overlooked issues is SNAT (Source Network Address Translation) port exhaustion. This problem can severely impact outbound connectivity. In particular, it hits hard when applications create a high number of simultaneous connections to a small set of external destinations — such as databases or third-party APIs.

In this article, you will learn what SNAT port exhaustion is, how to detect it, and step-by-step methods to fix it using Azure CLI. You will also learn how to increase outbound ports and frontend IPs to keep your AKS cluster stable under heavy workloads.

Introduction

When SNAT ports run out, your applications can no longer open outbound connections. As a result, you get downtime, timeouts, and performance degradation — often at the worst possible moment. Fortunately, Azure gives you direct control over outbound rules, allocated ports, and frontend IPs on your AKS load balancer. In this guide, we walk through how to identify the problem and fix it step by step.

What Is SNAT Port Exhaustion?

To understand the problem, it helps to know how outbound traffic flows in AKS. Each outbound connection from a pod uses a combination of the pod’s IP address and a port number. SNAT then translates those internal addresses and ports to the load balancer’s public IP and a different port number.

However, the load balancer only has a limited number of ports available for this translation. When your app opens many connections to the same destination IP — for example, a database — it consumes those ports quickly. If all ports are used up, new connections fail. That failure is called SNAT port exhaustion.

💡 In simple terms: think of SNAT ports like phone lines. If all lines are busy, no new calls can get through — even if your app keeps trying.

Real-Life Scenario: SNAT Port Exhaustion in AKS

Imagine you have a high-traffic frontend application running on AKS. It connects to a database hosted on a public IP address. Over time, users start reporting intermittent connectivity errors. After investigating, you discover that the root cause is SNAT port exhaustion — the app has run out of outbound ports to open new connections to the database.

This is a very common pattern in production AKS clusters. Moreover, it is easy to miss because the app appears to work fine under normal load. Only under peak traffic does the exhaustion show up.

How to Identify SNAT Port Exhaustion

Before making any changes, first confirm that SNAT port exhaustion is the actual root cause. Specifically, look for these symptoms:

  • Connection failures: Applications fail to open new outbound connections, even though the destination is reachable.
  • Timeout errors: Connections time out because no SNAT port is available to complete the handshake.
  • Intermittent connectivity: Everything works at low traffic but fails under heavy load — a classic sign of port exhaustion.
  • Azure Monitor alerts: The metric SNATPortExhaustion appears in your Load Balancer metrics dashboard.

To confirm the issue, check your application logs for connection refused or timeout errors. In addition, open the Azure Portal → Load Balancer → Metrics and monitor the SNAT Connection Count and Used SNAT Ports metrics. A spike close to your allocated limit confirms exhaustion.

⚠️ Do not skip this step. Increasing ports without confirming the root cause wastes resources and may not solve the actual problem.

Once confirmed, you need to take two actions:

  • Identify the current outbound rule configuration on the AKS load balancer.
  • Increase the allocated outbound ports and frontend IPs to handle more simultaneous connections.

Using Azure CLI to Fix SNAT Port Exhaustion in AKS

The following steps use Azure CLI to inspect and fix the outbound configuration on your AKS cluster’s load balancer. Follow each step in order.

Step 1: Get the Node Resource Group

First, you need to find the node resource group. In AKS, the underlying infrastructure — including VMs and load balancers — is managed in a separate, auto-generated resource group. Run this command to get its name:

NODE_RG=$(az aks show --resource-group myResourceGroup --name myAKSCluster --query nodeResourceGroup -o tsv)

What each part does:

  • az aks show — retrieves details about your AKS cluster.
  • –resource-group myResourceGroup — the resource group where your AKS cluster lives.
  • –name myAKSCluster — the name of your AKS cluster.
  • –query nodeResourceGroup — extracts only the node resource group name from the response.
  • -o tsv — outputs the result as plain text, ready to use in the next command.

Step 2: List Current Outbound Rules

Next, inspect the current outbound rule configuration on your load balancer. This shows you exactly how many ports are currently allocated and how many frontend IPs are in use:

az network lb outbound-rule list --resource-group $NODE_RG --lb-name kubernetes -o table

What each part does:

  • az network lb outbound-rule list — lists all outbound rules for the specified load balancer.
  • –resource-group $NODE_RG — uses the node resource group from Step 1.
  • –lb-name kubernetes — targets the load balancer (always named kubernetes in AKS by default).
  • -o table — formats the output as a readable table so you can easily spot the current port allocation.

Review the output carefully. Look at the AllocatedOutboundPorts and FrontendIPConfigurations columns. If the allocated ports are low and your app is high-traffic, that is your problem confirmed.

Step 3: Increase Outbound Ports and Frontend IPs

Now that the problem is confirmed, fix it by increasing the allocated outbound ports and the number of frontend IPs. More frontend IPs means more total SNAT ports available across the load balancer. Run the command below — adjust the values to match your cluster name and resource group:

az aks update \
  --resource-group myResourceGroup \
  --name myAKSCluster \
  --load-balancer-managed-outbound-ip-count 7 \
  --load-balancer-outbound-ports 2000

What each part does:

  • az aks update — updates the configuration of an existing AKS cluster.
  • –load-balancer-managed-outbound-ip-count 7 — increases the number of managed outbound IPs to 7. Each IP adds 64,000 available SNAT ports.
  • –load-balancer-outbound-ports 2000 — sets the number of outbound ports allocated per node to 2,000. Adjust this based on your expected connection volume.

📊 Example calculation: 7 IPs × 64,000 ports per IP = 448,000 total SNAT ports available. That is a significant increase over the default configuration.

For a real production cluster, replace the placeholder values with your actual cluster details:

az aks update \
  --resource-group rg-dgtl-dot-prd-we-01 \
  --name aks-dgtl-ms-dot-we-01 \
  --load-balancer-managed-outbound-ip-count 7 \
  --load-balancer-outbound-ports 2000

Step 4: Verify the Fix

After applying the update, verify the new configuration by running the outbound rule list command again:

az network lb outbound-rule list --resource-group $NODE_RG --lb-name kubernetes -o table

Confirm that the AllocatedOutboundPorts and FrontendIPConfigurations columns now reflect your new values. In addition, monitor your Azure Load Balancer metrics over the next 30–60 minutes. Specifically, watch the Used SNAT Ports metric — it should stay well below your new limit.

How to Choose the Right Port Count

Choosing the right values depends on your cluster size and traffic pattern. Here is a simple way to calculate what you need:

  • Ports per node = Total SNAT ports ÷ Number of nodes. For example, 7 IPs × 64,000 = 448,000 ports ÷ 10 nodes = 44,800 ports per node.
  • Start conservative — set --load-balancer-outbound-ports to 1,000 or 2,000 per node and monitor the metrics.
  • Scale up gradually — if Used SNAT Ports still approaches the limit under peak load, increase the IP count or port count further.

⚠️ Important: Setting –load-balancer-outbound-ports too high reduces the number of ports available per backend instance. Always test in a staging environment before applying to production.

Conclusion

For cloud engineers and DevOps teams, managing SNAT port exhaustion in AKS is a critical part of keeping applications reliable under load. By using simple Azure CLI commands, you can identify your current outbound rule configuration, confirm whether exhaustion is occurring, and increase allocated ports and frontend IPs to fix it.

In summary, the fix involves three steps — get the node resource group, inspect the outbound rules, and update the load balancer configuration. Furthermore, adding more managed outbound IPs is the most scalable solution. With 7 IPs, for example, you unlock 448,000 SNAT ports — more than enough for most high-traffic workloads.

Most importantly, always monitor your Used SNAT Ports metric in Azure Monitor after applying changes. Consequently, you will catch any future exhaustion early — before it impacts your users.

Quick Reference: Commands Used in This Guide

  • Get node resource group: az aks show ... --query nodeResourceGroup
  • List outbound rules: az network lb outbound-rule list ... -o table
  • Increase outbound ports and IPs: az aks update ... --load-balancer-managed-outbound-ip-count 7 --load-balancer-outbound-ports 2000
  • Verify the fix: Re-run the outbound rule list and check Azure Monitor metrics.

Top Kubectl Commands Every DevOps Engineer Needs for Kubernetes Troubleshooting

Introduction

In the fast-paced world of cloud-native applications, Azure Kubernetes Service (AKS) has become a go-to platform for DevOps teams across the world. However, managing and troubleshooting Kubernetes clusters can be challenging, especially when dealing with issues in pods, deployments, or containers. Thankfully, Kubernetes provides a powerful command-line tool called kubectl that allows you to interact with your AKS cluster. This article will walk you through the most essential kubectl commands to help DevOps engineers and cloud professionals effectively Kubernetes Troubleshooting  issues in their AKS clusters.

When to Use These Commands

You should use these kubectl commands when:

  • Pods are in a CrashLoopBackOff or Error state.
  • A deployment is not scaling as expected.
  • Containers fail to start or exhibit unexpected behavior.
  • Networking issues prevent services from communicating.
  • You need to inspect logs to understand what’s happening inside a container.
  • You want to check the status and events related to a pod or deployment.
  • You need to execute commands inside a running container for debugging purposes.

Essential Kubectl Commands for Troubleshooting in AKS

1. Get the Status of Pods, Deployments, and Services

This command lists all the pods, deployments, or services in a specific namespace. It helps you quickly identify if any pods are in a CrashLoopBackOff, Pending, or Error state.

kubectl get pods
kubectl get deployments
kubectl get services
#Example: 
kubectl get pods -n <namespace>

2. Describe a Pod or Deployment

The describe command provides detailed information about a specific pod or deployment, including events, configuration, and status. This is useful for understanding why a pod might be failing or why a deployment isn’t scaling correctly.

The kubectl describe command provides detailed information about various Kubernetes resources, such as pods, nodes, and deployments. By running kubectl describe <resource> <resource-name> -n <namespace>, you can access a wealth of data, including events, conditions, and configuration details, helping you pinpoint the root cause of problems.

kubectl describe pod 
kubectl describe deployment 
#Example: 
kubectl describe pod my-pod -n <namespace>
kubectl describe deployment customer-service -n customer

The output will contain detailed information about the specified pod, including its metadata, container information, conditions, and events. This information can be invaluable for troubleshooting issues with the pod, such as initialization problems, readiness issues, or events related to its lifecycle.

3. View Pod Logs

This command fetches the logs from a specific pod, which is crucial for debugging issues within the container. You can also use the -f flag to follow the logs in real-time.

When application-level issues arise, examining pod logs is crucial. Use kubectl logs <pod-name> -n <namespace> to view the logs of a specific pod in a given namespace. This command is invaluable for identifying errors, exceptions, or issues within your application code.

kubectl logs 
#Example: 
kubectl logs my-pod -n 

4. Execute Commands in a Running Container

This command allows you to open a shell inside a running container. It’s useful for running diagnostic commands or inspecting the file system directly within the container.

#Linux pod: 
kubectl exec -it  -- /bin/bash
#Window pod: 
kubectl exec -it  -- powershell
#Example: 
kubectl exec -it my-pod -n  -- /bin/bash

5. Check Event Logs for a Namespace

This command lists all events in the cluster, sorted by creation time. Events can provide insights into what’s happening in your cluster, such as why a pod was evicted or why a deployment failed.

kubectl get events --sort-by=.metadata.creationTimestamp
#Example: 
kubectl get events -n <namespace> --sort-by=.metadata.creationTimestamp

Real-World Scenario: Troubleshooting Pod Initialization

Suppose you encounter an issue where pods are not initializing correctly. You can use kubectl get events –all-namespaces to identify events related to pod initialization failures, helping you pinpoint the root cause.

6. View Node Resource Utilization

This command shows the CPU and memory usage of pods or nodes. It’s useful for identifying resource bottlenecks that might be causing issues in your AKS cluster.

kubectl top pod
kubectl top node
#Example: 
kubectl top pod -n <namespace>

Conclusion

Troubleshooting issues in Azure Kubernetes Service (AKS) can be challenging, but with the right kubectl commands, you can quickly identify and resolve problems in your pods, deployments, and containers. By using commands like kubectl get, kubectl describe, kubectl logs, and kubectl exec, you can gain deep insights into the state of your AKS cluster and take corrective actions. Whether you’re dealing with a crashing pod, a misbehaving deployment, or a container that’s not responding, these commands are essential tools in your Kubernetes troubleshooting toolkit.

By mastering these essential kubectl commands, you can minimize downtime, improve operational efficiency, and keep your AKS workloads running smoothly.

Troubleshooting DNS Failures in Azure Kubernetes Service (AKS) Clusters

Introduction

Monitoring DNS resolution inside Azure Kubernetes Service (AKS) is essential for maintaining reliable application connectivity. When DNS failures occur, services can experience intermittent connectivity or complete outages. One effective way to diagnose these issues is by using tcpdump with CoreDNS — the DNS server used by AKS.

In this guide, you’ll learn how to configure tcpdump within your CoreDNS deployment to capture and analyze DNS request/response traffic in real time

Prerequisites:

  • You need kubectl configured and connected to your AKS cluster.
  • Ensure you have permissions to manage deployments and pods in your Kubernetes cluster.

Step-by-Step Guide to Configure tcpdump to Find DNS failures

Step 1: Identify the CoreDNS Deployment

First, you need to find the CoreDNS deployment in your Kubernetes cluster: Look for a deployment named coredns in the kube-system namespace.

kubectl get deployments -n kube-system

Look for a deployment named coredns in the kube-system namespace.

Step 2 : Backup the coredns to Local

As a precautionary measure, create a local backup of your CoreDNS deployment YAML file before making any changes. You can achieve this using the following command:

kubectl get deployment coredns -n kube-system -o yaml > coredns.yaml

Step 3 : Add tcpdump Container to CoreDNS Deployment

Method 1: Edit the CoreDNS Deployment

Edit the coredns deployment and add the tcpdump container under the spec.template.spec.containers section of the CoreDNS deployment YAML. Here’s an example of how you can add it and save:

spec:
template:
spec:
containers:
- name: tcpdump
image: docker.io/corfr/tcpdump
args: ["-C", "100", "-W", "20", "-v", "-w", "/data/dump" ]

When you use tcpdump to capture packets, it writes them into a file (like dump00.pcap). If you keep capturing for a long time, that file can grow very large — potentially filling up the pod’s disk.

1️⃣ -C <file_size> — Limit the size of each capture file

This flag sets the maximum size (in megabytes) of a single capture file.

🔹 Example: -C 100
→ Each .pcap file will be limited to 100 MB.
Once the file reaches 100 MB, tcpdump automatically starts a new file.

2️⃣ -W <file_count> — Limit how many files to keep

This flag sets the number of rotated files tcpdump should keep.

🔹 Example: -W 20
→ tcpdump will keep 20 files maximum, rotating them like a circular buffer.
When it reaches the 21st file, it overwrites the oldest file.

Method 2: patch the deployment

Create patch.yaml file with above spec content and save to local and execute using below kubectl.

kubectl patch deployment coredns -n kube-system –patch-file patch.yaml


Post either followed Method 1 or 2, This changes will apply and trigger a rollout of the CoreDNS deployment.

Step 4 : Check the tcpdump container status

Once the rollout is complete, use the following command to check if the tcpdump container is running within a coredns pod: The output should display the tcpdump container listed among the containers running within the pod.

kubectl describe pod coredns -n kube-system

Step 5 : Verify the dump 

Access the core dns pod using the following command, replacing <coredns-pod-name> with the actual pod name:

kubectl exec -it <coredns-pod-name> -n kube-system -c tcpdump — sh

Once inside the pod, navigate to the /data directory to view the captured packets. You should find a file named “dump00” containing the captured network traffic data.

ls /data

There should be a dump00 file present.

Step 6: Downloading Logs from coredns 

At this point we wait for a few occurrences of the issue. Not sure how long this will take, that would depend on how often you see the error which you expect to collect in dumps. Once enough data is collected, you can exec into each of the pods and rename the file to apply the proper extension and then copy it to your local directory.

After enter in to the coredns pod, execute the below cmd ( you can able to see more dumps like dump00 , dump01, dump01….) to rename all the dump files as you required (XX replace with the your own name). Ensure you executing this command after moving to /data directory. Repeat this step, based on how much dump file present inside the coredns pod.

mv dump00 dumpXX.pcap

Finally exit the pod and in powershell/cmd, you can start to download from coredns to you local

kubectl cp kube-system/coredns-86c697cd8-6qtx9:/data/dump00.pcap -c tcpdump ./coredns-dump00

Step 7: Cleanup (Optional)

Remember to remove the tcpdump container from the CoreDNS deployment once you have completed your troubleshooting to avoid unnecessary resource usage and potential security risks. By restarting the coredns pods, the latest change will removed and back to its original state.

Conclusion

Configuring tcpdump on CoreDNS in AKS allows you to monitor DNS traffic effectively for troubleshooting and analysis purposes. By integrating tcpdump with CoreDNS, you can observe real DNS traffic patterns and isolate failures within your AKS cluster. This approach is invaluable for diagnosing name resolution issues that affect microservice communication or external dependencies. Use it in a controlled manner, and remove the tcpdump container once troubleshooting is complete. 

Notes

  • Security: Exercise caution with tcpdump as it can capture sensitive information. Ensure appropriate access controls and secure practices are in place.
  • Performance: Running tcpdump may impact pod performance and network throughput. Use it judiciously, especially in production environments.
  • Logging and Monitoring: Consider integrating tcpdump logs with your existing logging and monitoring solutions for better visibility and analysis.

Mastering Persistent Storage in Azure Kubernetes Service (AKS): A Step-by-Step Guide Using Azure Disks

Kubernetes is the leading managed container orchestration platform preferred by customers deploying microservices-based architectures in the cloud. Azure Kubernetes Service offers Kubernetes as a managed service, where the container orchestration platform is handled by Azure, enabling customers to focus on the developments of applications. Then how does AKS meet Kubernetes storage demands?

Containers are stateless, which means data is not stored locally—these containers depend on attached persistent volumes to handle the data lifecycle. This blog will walk through the steps required for provisioning persistent volumes and configuring them to be used by containers in Azure Kubernetes Service clusters.

What is Persistent Storage?

Persistent Storage is a mechanism to store data outside the lifecycle of a container or application, ensuring that critical information (like databases, user uploads, or configuration files) persists even if the container restarts, crashes, or is replaced. It’s essential for stateful applications (e.g., databases, CMS) that require data durability.

By default, the storage associated with pods is deleted when the pod lifecycle ends. For stateful applications, however, storage is expected to be persistent so that the data can remain available every time the pods gets recreated in the cluster. Container persistent storage in a Kubernetes cluster is provisioned using the PersistentVolume subsystem, which provides PersistentVolume and PersistentVolumeClaim API resources.

The PersistentVolumeClaim requests for a specific storage class, say Azure disks or Azure Files, and the underlying storage resource gets provisioned. This PersistentVolumeClaim is referenced in the pod definition so that the provisioned storage is mounted to the pod. In this way the PersistentVolume is linked to the PersistentVolumeClaim whenever the provisioned storage is mounted to the pod requesting the resource.

Note: The following steps will assume that the AKS cluster is already provisioned and that the administrator has access to execute the commands listed in this blog.

Provision Persistent Storage Using Azure Disks

There are four major steps in creating and attaching persistent storage using Azure disks in Azure Kubernetes Service.

1. Define/Create of storage class.
2. Configuration of persistent volume claim (PVC) that references of storage class.
3. Create the persistent volume claim and provision the volume.
4. Reference the PVC in the Pod specification to attach the Azure Disk ie., Attaching the provisioned volume to the pod by referencing the specific pod in the pod definition file.’

Let’s explore this process in detail with sample configuration files.

How AKS Uses Azure Disk Storage Classes

Azure Kubernetes Service (AKS) simplifies persistent storage management by offering two pre-configured storage classes for Azure Disks: default and managed-premium. These classes let teams provision storage tailored to workload requirements while abstracting backend complexity. Here’s how they work and where they shine—or fall short.

  • Built-in Storage Classes
  • default (Standard HDD)
  1. default (Standard HDD)
    • Backend: Relies on cost-effective Azure Standard HDD storage.
    • Use Case: Ideal for non-critical workloads like backups, logs, or dev/test environments where high throughput isn’t a priority.
  2. managed-premium (Premium SSD)
    • Backend: Leverages Azure Premium SSD for low latency and high IOPS.
    • Use Case: Suited for production workloads (e.g., databases, transactional apps) demanding consistent performance and faster data access.

Limitations of Built-in Classes

While convenient, the pre-built storage classes come with constraints:

No Post-Provisioning Resizing: Once a volume is created, you can’t expand its size—a hurdle for growing datasets or scaling applications.

Fixed Configuration: Default settings (e.g., performance tiers, redundancy) may not align with specialized needs.

Default: This storage class uses the standard Azure storage which leverages HDDs in the backend.

Creating Custom Storage Classes

In this section we’ll show you how users can create custom storage classes to suit their specific requirements.

1. Make Ready of StorageClass YAML

Connect to the AKS cluster from your management tool of choice (here i used powershell/CMD to connect the cluster using kubectl). For this demonstration we will be using Azure CL. From the Azure CLI, save the following manifest as storage-class.yaml

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: managed-standard-custom
provisioner: disk.csi.azure.com
reclaimPolicy: retain
allowVolumeExpansion: true
parameters:
  storageaccounttype: Premium_LRS
  kind: Managed

This file can be used to create a storage class that uses Premium_LRS managed disks. The reclaimPolicy is set to retain so that the persistent volume is not deleted even if the pod to which it is attached gets deleted. With the parameter allowVolumeExpansion set to true, the volume can now be resized even after provisioning.

 

ProvisionerStorage TypeRecommended UseNotes
disk.csi.azure.comAzure Managed Disks (Block Storage)High-performance workloads requiring dedicated block storage on a single nodeCSI-based; supports dynamic provisioning, volume expansion, and advanced features. Recommended for new deployments. :contentReference[oaicite:0]{index=0}
kubernetes.io/azure-disk (deprecated)Azure Managed Disks (Block Storage)Legacy setups using in-tree driversDeprecated in favor of the CSI-based disk.csi.azure.com provisioner.
file.csi.azure.comAzure Files (File Storage)Workloads needing shared storage (ReadWriteMany), such as content management or shared configuration filesCSI-based; supports SMB or NFS file shares with dynamic provisioning. :contentReference[oaicite:1]{index=1}
kubernetes.io/azure-file (deprecated)Azure Files (File Storage)Legacy deployments requiring shared file storageDeprecated in favor of the CSI-based file.csi.azure.com provisioner.
azureblob-csiAzure Blob Storage (Object Storage mounted as a filesystem)Workloads that use large unstructured datasets, such as logs or archival dataEnables mounting of Blob storage via CSI as a filesystem (using protocols like NFS or BlobFuse). Suitable for applications that do not require block storage.

 

2. Apply the yaml file using the following command

$ kubectl apply -f storage-class.yaml

Upon successful execution, you will get a message that the storage class has been created.

Create Persistent Volume Claim and Persistent Volume

The next step is to create a persistent volume claim (PVC), which uses the storage class defined in the above to provision an Azure disk as a persistent volume.

1. Create custom-pvc.yaml file in the Azure CLI window

Create the PVC creation YAML as shown below,

The PVC will request for an Azure disk of 10 GB with accessmode as ReadWriteOnce. That means only one node can mount the volume as read-write.

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: custom-pvc
  namespace: default
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: managed-standard-custom
  volumeMode: Filesystem
Access ModeDescription
ReadWriteOnceThe volume can be mounted as read-write by a single node. It can allow multiple pods to access it when running on the same node.
ReadOnlyManyThe volume can be mounted as read-only by many nodes.
ReadWriteManyThe volume can be mounted as read-write by many nodes.
ReadWriteOncePodFEATURE STATE: Kubernetes v1.29 [stable]
The volume can be mounted as read-write by a single Pod. This ensures that only one pod across the whole cluster can read or write to the PVC.

 

2. To create the volume itself, run the following command:

kubectl apply -f custom-pvc.yaml

On successful execution you will see a message that the persistent volume claim has been created.

After creation, the provisioned volume can also be seen from the Azure portal. Browse to the resource group where the AKS nodes are created to find the newly provisioned disk listed there. 

As highlighted in yellow, you can able to view  Persistent Volume has created with name of  “pvc-ae14b4f9-68d5-4aed-baf3-6addfe4e8b3d”

Once PVC is create successfully (status is bound) then the Persistent volume will create automatically and mapped to the PVC (refer above and below image)

 

And you can also verify disk with name of Persistent Volume by searching in the Azure portal as shown in below, where our mount data will be stored.

You can also run the following command to list the pvc status. It will be listed as “bound” to the created persistent volume:

You can also get all the PVC in your cluster, you can use kubectl get pvc

Attach a Persistent Volume to AKS

After creating the persistent volume claim and the Azure disk, it can be attached to a new pod by referencing the name of the persistent volume claim in the deployment or pod yaml.

1. Create file Nginx.yaml with the following content

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      restartPolicy: Always
      containers:
        - name:  nginx
          image: crdgtlshared02.azurecr.io/nginx:latest
          volumeMounts:
            - name: volume
              mountPath: /tmp/
      volumes:
        - name: volume
          persistentVolumeClaim:
            claimName: custom-pvc
      nodeSelector:
        kubernetes.azure.com/agentpool: userlnxpool
        kubernetes.azure.com/mode: user
        kubernetes.io/os: linux

The volume is mounted at /tmp/ as specified by the mountpath parameter.

Note that the image for the container is taken from my Azure container registry. Alternatively, it can also be downloaded from the Azure container registry.

2. Next, create the pod using the following command:

kubectl apply -f Nginx.yaml

When successfully executed, we can able to view the deployment is created successfully as shown below.

We also ensure in Azure portal by viewing pod will be created as shown below images under default namespace.

3. Verify that the persistent volume is attached to the pod 

kubectl describe pod nginx

The PVC will request for an Azure disk of 10 GB with access mode as ReadWriteOnce. That means only one node can mount the volume as read-write.

You can see that the volume is listed and and uses the claim name “custom-pv.”

Check Volume mount in your pod

To connect to the running Azure container instance, use the following command and run the df command to view the volumes:

kubectl exec -it <pod-name> -n <namespace> -- /bin/bash
kubectl exec -it nginx-7466c47dd6-h9tvz -n default -- /bin/bash

/dev/sdb : >> This indicates the device file associated with the storage. In this case, /dev/sdb refers to the second SCSI disk on the system.]

1K-blocks: 10218772 >>This shows the total size of the filesystem in 1-kilobyte blocks. Here, it amounts to approximately 10,218,772 KB, or roughly 9.75 GB.

Use%: 1% >> This shows the percentage of the filesystem’s capacity that is currently used. In this case, only 1% of the space is utilized.

Mounted on: /tmp >>This specifies the mount point, which is the directory where the filesystem is attached to the system. Here, the device /dev/sdb is mounted on /tmp, the standard directory for temporary files in Unix-like systems.

When AKS Won’t Scale Down: How We Fixed a Real Node Pool Autoscaling Failure in Production

Managing autoscaling in Azure Kubernetes Service (AKS) is not always straightforward. Recently, we ran into a problem where node pool scale down was not happening in both regions, and workloads were consuming resources beyond the defined cluster threshold. This article walks through the scenario, investigation, and resolution.

Scenario: Node Pool Not Scaling Down

The Context: A Planned Node Migration

Our production AKS cluster was running a node pool named mslnxpool02 (D-series VMs) on Kubernetes version 1.31.9. Following a performance review, Microsoft recommended migrating our workloads to E-series VMs for better resource utilization and cost-efficiency aligned with our application’s profile.

  1. To execute this migration, our team proceeded with a blue-green approach:
  2. Created a new node pool with E-series VMs.
  3. Used identical node labels on both the old (D-series) and new (E-series) node pools.

Relied on our Deployments, which used these labels as node Selectors (from starting we having this node selectors so only applied same label to new node pool), to automatically schedule new pods onto the E-series nodes as we cordoned and drained the D-series nodes.

The strategy was to incrementally scale up the E-series pool while simultaneously scaling down the D-series pool, allowing the cluster auto scaler to seamlessly re-schedule pods and reduce node count.

The Problem: Scale-Down Stalls, Incurring Cost

The initial phase of scaling up the new node pool and migrating pods worked as expected. However, we soon noticed a critical issue: the D-series node pool failed to scale down.

Despite workloads being successfully migrated and cluster resource usage dropping significantly, several nodes in the mslnxpool02 pool remained active. Even after waiting for an extended period to account for the cluster auto scaler’s cooldown delays, the node count remained stubbornly high. This resulted in unnecessary cloud costs and a cluster full of underutilized nodes.

The question was: Why was the scale-down stuck?

The following sections detail our investigation and the root cause we uncovered.

Step 1: Investigating the Node health

In my cluster, I had a node pool mslnxpool02 with multiple nodes running Kubernetes v1.31.9. Despite low workloads, the cluster auto scaler wasn’t scaling down the pool. Checking the nodes showed that they were all in a Ready state:

#check with powershell
kubectl get nodes | findstr lnxpool02

At first glance, the nodes looked healthy, but the auto scaler wasn’t freeing up any of them.

Step 2: Describe the Each Node for cause

To understand why the node couldn’t be scaled down, I began with a detailed inspection of one of the stuck nodes: aks-mslnxpool02-33931444-vmss000017.

kubectl describe node aks-lnxpool02-33931444-vmss000017

This command provides a comprehensive overview of the node’s status, capacity, and all the pods running on it. Here’s a breakdown of what I looked for and what I found:

  1. The node was Ready.
  2. Multiple workloads were running on it, including system pods (e.g., kube-proxy, csi-azure*, ama-logs, myapplication pods).
  3. One workload (my service) (customerfeed-service) had large CPU and memory requests as shown below:

CPU Requests: 6100m of 7820m (78%)
CPU Limits: 13 cores (166%)
Memory Requests: 2688Mi
Memory Limits: 10Gi

 

This explained part of the problem: auto scaler cannot evict pods that request a large percentage of node resources unless they can be rescheduled elsewhere.

Now we found the cause, the scaling down was not happened due to the high utilization of some application pods, which not allowing Node pool to scale down.

Step 3: Isolating the Node with Cordon Command

After identifying that the node was blocked from scaling down due to the customerfeed-service pod, the next step was to manually intervene and signal to the cluster that this node was a candidate for removal. This is where the kubectl cordon command comes in.

The primary goal of cordoning a node is to isolate it from receiving any new workloads. Think of it as putting up a “Do Not Enter” sign for the Kubernetes scheduler. This is a crucial, non-disruptive first step in any node maintenance or decommissioning process.

In simple , To prepare the node for scale-down, I manually cordoned it so no new pods would schedule on it:

kubectl cordon aks-mslnxpool02-33931444-vmss000017

Now the node appeared as Ready,SchedulingDisabled

kubectl get nodes | findstr mslnxpool02

aks-lnxpool02-33931444-vmss000017 Ready,SchedulingDisabled <none> 47d v1.31.9

This change told the cluster auto scaler that the node was un-schedulable.

In my case, i had done cordon for all the node pool and  you can confirm in the UI as well like below

Key Takeaways Highlights:

  • cordon is Non-Disruptive: It’s a safe first step that doesn’t affect running pods.

  • It’s a Signal: It tells both the Kubernetes scheduler and the Cluster Autoscaler to avoid this node.

  • It’s Not a Solution by Itself: Cordoning prepares the node but doesn’t solve the underlying resource fragmentation problem. It’s often the prelude to a drain operation.

Step 4: Allocation adjustment or restart the effected pod

After cordoning the node pool, we needed to address the affected pods that were preventing the autoscaler from acting. Simply cordoning ensures no new pods are scheduled on the node, but the existing high-utilization pod continues running and blocking scale down.

To resolve this, we took two possible actions:

Option A:  Restart the Affected Pod (Quick Fix)

If adjusting manifests immediately isn’t feasible (for example, in production during peak hours), a faster approach is to restart the affected pod so it can be rescheduled to a healthier node pool(as old node pool is restricted to schedule so it will map to new node pool):

1. Delete the Pod

 
kubectl delete pod <pod-name> -n <namespace>

2. Kubernetes Rescheduling

Kubernetes automatically recreates the pod on another available node pool.

This helps free up utilization on the cordoned pool, enabling the Cluster Auto scaler to scale it down.

⚠️ Note: This is a temporary workaround. Without fixing the resource requests in the deployment, the issue may reappear.

Option B:  Allocation Adjustment (Preferred)

1. Review Pod Resource Requests and Limits

Check the resources.requests and resources.limits configuration in the deployment manifest. In our case, the application pod had very high actual CPU utilization, but its configuration did not reflect realistic usage, keeping the node pinned.

In our case, the application pod had very high CPU requests, which forced the scheduler to keep nodes active.

Example snippet:

resources:
  requests:
    cpu: "2000m"   # 2 cores requested
    memory: "4Gi"
  limits:
    cpu: "3000m"
    memory: "6Gi"

2. Adjust Resource Requests

Increase the CPU or memory requests (based on observed utilization) to match actual needs. This ensures Kubernetes schedules pods more accurately and avoids overcommitting nodes.

Example snippet:

resources:
  requests:
    cpu: "6000m"   # increased to 4 core
    memory: "4Gi"
  limits:
    cpu: "4000m"
    memory: "6Gi"

This alignment gives the auto scaler a true view of resource usage, enabling it to correctly evaluate which nodes can safely scale down.

Conclusion

Node pool scale-down issues in AKS often come down to workload placement and resource requests. In this scenario, a single oversized pod was preventing the auto scaler from acting. By analyzing node workloads, cordoning, and draining, I was able to resolve the problem and allow auto scaler to scale down efficiently.

Boost Application Reliability with Kubernetes postStart Hooks (Real-World Examples Inside)

Introduction

Hooks allow developers to run custom logic at critical points in a container’s lifecycle. These hooks help with initialization and graceful shutdown, ensuring applications are reliable, performant, and consistent. In this article, we’ll explore lifecycle hooks in Kubernetes, with a focus on the postStart hook, real-world use cases, and practical examples using Windows IIS containers.

Types of Hooks in Kubernetes

Kubernetes offers two primary lifecycle hooks for containers:

postStart Hook:

Triggered immediately after a container is started.

Commonly used for initializing services, setting up configurations, or performing other preparatory tasks before the application is fully operational. PostStart Hook provides us ability to perform some task before the pod is completely initialized. This hook is executed immediately after a container is created. However, there is no guarantee that the hook will execute before the container ENTRYPOINT command. This is useful for scenarios where you want to perform some setup before the main container in the pod starts running.

preStop Hook:

Triggered just before a container is terminated.

Often used to gracefully shut down services, close connections, or clean up resources to ensure data integrity and prevent resource leaks. This is particularly useful for applications that need to gracefully shut down, ensuring that ongoing processes complete before the container stops. Examples of tasks include closing database connections, finalizing transactions, or notifying external systems about impending shutdown.

In this post, we are going to discuss more deep in to the postStart Hook

Use Case : When and Where is the postStart Hook Required?

The postStart lifecycle hook is useful in scenarios where specific tasks need to be performed before the main application in a container becomes functional. Some common use cases include:

Environment Setup: Copying necessary files or templates. Modifying configuration files dynamically based on the environment.

Application Warm-up: Performing application-specific warm-up tasks to reduce the latency of initial requests.

Service Initialization: Setting up dependencies or configurations required by the application. Starting background services or processes necessary for the container’s operation.

Example Scenario

Consider a scenario where an ASP.NET application hosted on IIS requires a startup script (startup.ps1) to configure IIS settings, initialize application-specific environment configuration substitution, or perform other preparatory tasks. Using the postStart hook ensures that these configurations are executed as soon as the container starts.

Configuring the postStart Lifecycle Hook

Here’s an example Kubernetes pod specification that uses the postStart lifecycle hook to execute a PowerShell script: In the provided example, the postStart hook logs a message to C:\poststart.log in a Windows IIS container, confirming successful initialization. By leveraging postStart hooks, you can add flexibility and control to your containerized applications, ensuring they are fully prepared to handle their workloads upon startup.

For this example, i had explain with simple logging the message in the poststart. Based on requirement, you can have .ps1 (startup.ps1)/configuration file to execute during the container creation.

Example 1: Create Simple log file in PostStart

STEP 1: Create the pod using below YAML

Save the below YAML as iis-pod and run the below kubectl cmd to create the pods in AKS, as shown in the STEP 2

kind: Pod
metadata:
name: iis-pod
spec:
containers:
- name: iis-container
image: mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2022
lifecycle:
postStart:
exec:
command:
- cmd
- /c
- echo PostStart hook executed > C:\poststart.log
ports:
- containerPort: 80
#Execute the YAML to create the pod
kubectl create -f iis-pod.yaml

STEP 2: Check the pod status

Execute the below Kubectl comments to ensure pod is running successfully.

# Command to get pods’ status:

kubectl get pods

# Command to view the details of Pod:

kubectl describe pod iis-pod

STEP 3: Get in to the pod to verify poststart.log file

The postStart hook executes the specified command and the text “PostStart hook executed” is written to the file C:\poststart.log. The container initializes and becomes ready to handle requests on port 80

Explanation of the Configuration (Command Breakdown)

  • The exec : field specifies the command to be executed:
  • cmd: Specifies the Windows Command Prompt as the executor.
  • /c: Tells the Command Prompt to execute the provided command and then terminate.
  • echo PostStart hook executed > C:\poststart.log: Writes the text “PostStart hook executed” into the file C:\poststart.log. If the file does not exist, it is created automatically. If it exists, the content is overwritten.
  • Port 80 : The container exposes port 80, which is the default HTTP port for IIS.
# Enter in to the pod using Kubectl
kubectl exec -n default iis-pod -it -- powershell

Example 2: Create Warmup in PostStart

The postStart hook waits 5 seconds for IIS to initialize. It sends an HTTP GET request to http://localhost to ensure the default page is accessible and finally the HTTP response is saved to C:\warmup.log, which can be inspected for debugging or verification.

Explanation of the Configuration (Command Breakdown)

  • Start-Sleep -Seconds 5; : Introduces a short delay to ensure IIS has started before making a request.
  • Invoke-WebRequest -Uri http://localhost: Sends an HTTP request to the IIS default page hosted on the same container.
  • Out-File -FilePath C:\warmup.log -Force; : Saves the HTTP response to the file C:\warmup.log. The -Force option ensures the file is created or overwritten if it exists.
  • Error Handling: A try block handles successful execution, and the catch block logs errors if the warm-up process fails.
  • Ports 80: The container exposes port 80, which is used by IIS to serve the application.
apiVersion: v1
kind: Pod
metadata:
name: iis-pod-warmup
spec:
containers:
- name: iis-container
image: mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2022
lifecycle:
postStart:
exec:
command:
- powershell
- '-Command'
- >
try {
Start-Sleep -Seconds 5; # Wait for IIS to start
Invoke-WebRequest -Uri http://localhost -UseBasicParsing | Out-File -FilePath C:\warmup.log -Force;
Write-Host "Warm-up request completed successfully.";
} catch {
Write-Error "Warm-up request failed: $_";
}
ports:
- containerPort: 80

Output

Conclusion

Kubernetes lifecycle hooks like postStart give developers greater control over container startup behavior. Whether you’re initializing services, warming up applications, or preparing IIS environments, hooks can significantly improve reliability and user experience.

 

Mastering the Kubernetes kubectl Patch Command with Examples in Azure AKS

Managing Kubernetes resources efficiently is essential for scalable cloud-native applications. The kubectl patch command lets you quickly update running Kubernetes resources — such as labels, container images, or replicas — without redeploying entire configurations. In this article, you’ll learn how to use kubectl patch within Azure Kubernetes Service (AKS), complete with practical examples.

What is the kubectl patch Command?

Patch is a command line option for updating Kubernetes API objects. You can use it to update a running configuration. You do this by supplying it with the section to update, instead of a completely new configuration, as you would with kubectl apply.

The command works by “patching” changes onto the current resource configuration. Unlike a kubectl replace operation, the patch operation only modifies specific fields in the resource configuration.

What can we do using Kubectl patch command?

With kubectl patch, you can quickly fix issues with updating the name, image, label, replicas, affinity/tolerations, environment variables, configaps, secrets, volumes, ports, etc. kubectl patch supports YAML and JSON formats. Using either format, you can drill into the specific field of the resource and change it to your desired value. Kubectl supports three different patching strategies: Strategic Merge (the default) and JSON Merge. You utilize these formats through the patching strategy.

“kubectl patch supports three strategies: Strategic Merge Patch (default), JSON Merge Patch, and JSON Patch. Each has different use cases depending on the complexity of your update.”

Sample deployment YAML file

Let’s say we have the following Nginx deployment YAML file, we originally had only one label (environment: prod), and we want to add a new label to specify the app we are running (app: nginx). We will use the –patch command to enter the new labels:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.14.2
          ports:
            - containerPort: 80

Example 1: Patch the label to the deployment

Method 1: Patch using Inline JSON 

In our case, we would like to add environment for the deployment as prod, for this we would run the following command to add the new labels:

kubectl patch deployment nginx-deployment --patch '{\"metadata\": {\"labels\": {\"environment\": \"prod\"}}}'

For the patch command to work, you must correctly include the map and lists in the original YAML file, so Kubernetes knows exactly where to go to add/update the new value properly.

We are going to discuss very simple example of using the kubectl patch command to update fields in your Kubernetes deployment file.

If you want to patch from the YAML file, you can create file with the required update and save as .YAML as shown in below and execute the file using kubectl.

Method 2: Patch using YAML file

“This patch file only contains the section you want to update, not the full deployment manifest.

#Save the file using below manifest (patch.yaml)
metadata:
  labels:
    environment: prod
#execute the command to apply the new changes in the existing pod
kubectl patch deployment nginx-deployment --patch-file ./thi/patch.yaml


You can run the following to check the YAML for the new updates:

#View the YAML in the notpad
kubectl edit deployment nginx-deployment
#View the YAML in the console itself
kubectl get deployment nginx-deployment -o yaml

In return, we get the following YAML file:

Example 2: Patch the label to the Pod level

In this same scenario, if we wanted to update the labels within the Pod template, you would have to drill into the spec field instead of the metadata.

Usually, you would drill into the metadata and spec fields for kubectl patch, but this would also work with other YAML fields, such as status or even a new custom field you created through a CRD (custom resource definition).

In the following example, we are attempting to add a new label environment: prod to the existing labels within the pod template, as the following:

#replace : Modifies the value of an existing field.
#add: Adds/replace a new field or value to an array.
#remove: Removes a field or an element from an array.
#copy: Copies the value of one field to another
#test: Verifies that a specific field has a certain value. The patch operation will fail if the condition is not met
#move: Moves a value from one location to another within the object
kubectl patch deployment nginx-deployment --type='json' --patch='[{"op": "add", "path": "/spec/template/metadata/labels/environment", "value":"prod"}]

The above cmd will be used for both adding new or updating the existing fields. To check if the deployment got the new labels, you can run the following:

kubectl get deployment nginx-deployment --show-labels

Example 3: Update Pod label and container image

We will attempt to update the image of the ingress from older version to new version and update the label value together . This will require us to drill further into the list (the – is a list and will use [ ] to tap into it from the kubectl patch command) instead of a map (uses { }):

kubectl patch deployment nginx-deployment --patch '{\"spec\": {\"template\": {\"metadata\": {\"labels\": {\"environment\": \"production\"}}, \"spec\": {\"containers\": [{\"name\": \"nginx\", \"image\": \"nginx:1.14.2\"}]}}}}'

Conclusion

The kubectl patch command is a versatile tool for managing Kubernetes resources, particularly in dynamic environments like Azure Kubernetes Service. It allows for targeted updates with minimal effort, making it ideal for quick fixes and operational adjustments. By mastering the kubectl patch command, AKS administrators can maintain agility and efficiency in managing their clusters.

Whether you are adding labels, scaling deployments, or updating container images, kubectl patch ensures you can implement changes quickly and confidently. Embrace this command to streamline your Kubernetes workflows and keep your AKS environment optimized.

“Next time you’re troubleshooting or making small updates in AKS, try kubectl patch instead of redeploying. What’s your favorite kubectl command? Drop it in the comments 👇”

Frequently Asked Questions (FAQ)

1. When should I use kubectl patch instead of kubectl apply?

Use kubectl patch when you want to make quick, targeted changes to a Kubernetes resource without redeploying the entire manifest. For example, updating a label, changing an image tag, or adding an environment variable can be done faster with kubectl patch. If you need to manage large or version-controlled manifests, kubectl apply is still the better choice.

2. Can I rollback a kubectl patch?

No, kubectl patch itself does not provide a rollback mechanism. Once applied, the changes are immediately reflected in the resource. To revert, you must either:

  • Manually patch again with the previous values, or

  • Redeploy the original manifest using kubectl apply -f <file.yaml>.
    Using GitOps or storing manifests in source control is recommended to track and revert changes easily.

3. What are common errors with kubectl patch?

Some common errors include:

  • Incorrect JSON/YAML syntax – forgetting quotes, brackets, or commas.

  • Missing path values – targeting the wrong field (e.g., metadata vs spec.template.metadata).

  • Unsupported patch type – not specifying --type=json when using JSON Patch operations.

  • Read-only fields – trying to patch fields like status or metadata.uid, which cannot be modified.

4. Does kubectl patch work for all Kubernetes resources?

Yes, kubectl patch works for most standard Kubernetes resources like Deployments, Pods, Services, ConfigMaps, and Secrets. However, some Custom Resource Definitions (CRDs) may not fully support all patch types depending on their schema.

5. Is kubectl patch safe to use in production?

Yes, but with caution. Since it makes live changes to resources, there is no automatic rollback. It is best used for small, urgent fixes in production. For long-term changes, update your manifests and use kubectl apply to keep your deployments consistent.

 

 

Update AKS Node Pools with Labels: A Comprehensive Guide Using Azure CLI

In today’s dynamic cloud environments, effectively managing your Azure Kubernetes Service (AKS) clusters is paramount. Labels offer a robust mechanism for organizing and optimizing your AKS resources, enabling efficient workload management and cost control. This comprehensive guide will delve into the az aks nodepool update command (azure aks nodepool update), demonstrating how to apply labels to your AKS node pools using the Azure CLI. We’ll explore practical use cases, essential prerequisites, and provide a step-by-step implementation guide.

What is the az aks nodepool update Command?

The az aks nodepool update command is an integral part of the Azure CLI toolkit. In essence, it empowers administrators to update specific properties of an existing AKS node pool. Moreover, utilizing labels with this command enables better management and resource allocation by categorizing node pools for specific workloads.

When to Use ?

This command proves particularly useful in the following scenarios:

  • Workload Segmentation: Assign specific workloads, such as .NET applications, to designated node pools. For example, you can label a node pool as “dotnet” to easily identify nodes suitable for .NET applications.
  • Cost Management: Apply labels to categorize node pools by environments (e.g., production, staging) to track costs more effectively. Consequently, this facilitates accurate cost allocation and budgeting.
  • Efficient Scheduling: Utilize Kubernetes label selectors in deployment manifests to target workloads to specific node pools. As a result, you can optimize resource utilization and improve application performance
  • Cluster Management: Enhance visibility and filtering when managing multiple node pools. In addition, labels simplify cluster management by providing a clear and organized structure.

Prerequisites

Before executing the az aks nodepool update command, ensure the following prerequisites are met:

       1. Azure CLI Installed:

Ensure the Azure CLI is installed and updated to the latest version. You can install it from the Azure CLI Documentation. Verify the installation using: az --version

Verify installation using:  az  –version

       2. Access Permissions:

You must possess the appropriate permissions to manage AKS resources. Typically, you’ll require the Azure Kubernetes Service Contributor or Owner role.

       3. Existing AKS Cluster and Node Pool:

An AKS cluster and the node pool you intend to label must already exist

      4. Resource Details:

Identify the resource group, cluster name, and node pool name.

How to Use the Command

To update labels on an AKS node pool using the Azure CLI, employ the following command:

az aks nodepool update \
  --resource-group <resource-group> \
  --cluster-name <aks-cluster-name> \
  --name <node-pool-name> \
  --labels <key=value>

For instance, to add a label nodepooltype=dotnet to the node pool prdnxpool01 in a production AKS cluster:

az aks nodepool update \
--resource-group rg-apps-prd-01 \
--cluster-name aks-dgtl-app-prd-we-01 \
--name prdnxpool01 \
--labels nodepooltype=dotnet

Command Breakdown

–resource-group: Specifies the resource group of the AKS cluster.
–cluster-name: The name of the AKS cluster.
–name: The name of the node pool to be updated.
–labels: Key-value pairs for the labels to apply to the node pool.

Validating the Update

Once the command executes successfully, you can verify the labels using the following method:

az aks nodepool show \
--resource-group rg-apps-prd-01 \
--cluster-name aks-dgtl-app-prd-we-01 \
--name prdnxpool01

OUTPUT

Conclusion:

In conclusion, effectively labeling AKS node pools is a critical practice for optimizing your Kubernetes workloads, improving resource utilization, and streamlining cluster management. The az aks nodepool update command within the Azure CLI provides a user-friendly and efficient method for applying and managing labels. By implementing the strategies outlined in this guide, you can enhance your AKS cluster’s performance, reduce operational overhead, and gain greater control over your Kubernetes deployments.

For more insights on Kubernetes and Azure, stay tuned to our blog!
Got questions or additional tips? Share them in the comments below!

 

Mastering Kubernetes HPA: How to Filter Horizontal Pod Autoscalers on Linux and Windows

Introduction to Horizontal Pod Autoscalers (HPAs)

In Kubernetes, a Horizontal Pod Autoscaler (HPA) is a critical resource that automatically scales the number of pods in a deployment, replica set, or stateful set based on observed CPU utilization, memory usage, or custom metrics. HPAs ensure that your applications can handle varying workloads efficiently by scaling out (adding more pods) during high demand and scaling in (removing pods) during low demand and another activity to monitor hpa by kubernetes hpa filtering.

When managing Kubernetes clusters, you often need to monitor and filter HPAs across multiple namespaces. For example, you might want to list all HPAs in specific namespaces or filter them based on certain criteria. On Linux, the grep command is commonly used for filtering text output. However, Windows does not natively support grep, so alternative methods are required.

In this article, we’ll explore how to filter kubectl get hpa output on both Linux and Windows systems (kubernetes hpa filtering) , using native tools and third-party utilities.

kubernetes hpa filtering

Filtering kubectl get hpa Output on Linux

Linux systems natively support the grep command, which is a powerful tool for filtering text. Here’s how you can use grep to filter kubectl get hpa output.

Example: Filter HPAs in Specific Namespaces

Suppose you want to list all HPAs in the namespace1 and namespace2 namespaces. You can use the following command:

kubectl get hpa -A -o wide | grep -E 'namespace1|namespace2'

kubectl get hpa -A -o wide | grep -E 'customer|identity'

Explanation:

  • kubectl get hpa -A -o wide: Fetches all HPAs across all namespaces (-A) and displays them in a wide format (-o wide).
  • grep -E ‘namespace1|namespace2’: Filters the output to show only lines containing namespace1 or namespace2.

Filtering kubectl get hpa Output on Windows

Windows does not natively support grep, but you can achieve similar functionality using PowerShell or by installing Unix-like tools.

Option 1: Use PowerShell’s Select-String

PowerShell has a built-in command called Select-String that works similarly to grep.

Example: Filter HPAs for all Namespaces

Fetches all HPAs across all namespaces.

kubectl get hpa -A
kubectl get hpa -A -o wide

Example: Filter HPAs in Specific Namespaces

kubectl get hpa -A -o wide | Select-String -Pattern 'namespace1|namespace2'

kubectl get hpa -A -o wide | Select-String -Pattern 'customer|identity'

Select-String -Pattern ‘namespace1|namespace2’: Filters the output to show only lines containing namespace1 or namespace2.

Option 2: Use findstr & Where-object (Native Windows Command)

Windows has a built-in command called findstr that can be used for basic text filtering.

Example: Filter HPAs in Specific Namespaces

kubectl get hpa -A -o wide | findstr "namespace1 namespace2"

kubectl get hpa -A -o wide | Where-Object { $_ -match 'customer|identity' }

findstr “namespace1 namespace2”: Filters the output to show only lines containing namespace1 or namespace2.

Using grep in Window’s Machine

Windows does not natively support grep, but you can achieve similar functionality using PowerShell or by installing Unix-like tools as shown in below.

choco install grep

Post installation, you can use the grep in you window machine. Ensure you are installing grep by opening the PowerShell console in the Admin mode to have successful installation.

Conclusion

For US-based teams, mastering kubectl HPA filtering and monitoring is essential for cost-efficient, high-performance Kubernetes clusters. By combining Linux/Windows command-line tools with enterprise-grade observability platforms, organizations can achieve seamless autoscaling aligned with industry best practices