<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raja Gupta  on Medium]]></title>
        <description><![CDATA[Stories by Raja Gupta  on Medium]]></description>
        <link>https://medium.com/@rajagup05?source=rss-b7e087bd8431------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SQbX67PKnA8MLD4UnUtEEw.png</url>
            <title>Stories by Raja Gupta  on Medium</title>
            <link>https://medium.com/@rajagup05?source=rss-b7e087bd8431------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:31:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajagup05/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Access a Private GKE Cluster from Cloud Shell and Compute Engine VM]]></title>
            <link>https://medium.com/@rajagup05/how-to-access-a-private-gke-cluster-from-cloud-shell-and-compute-engine-vm-dfcc522f8d40?source=rss-b7e087bd8431------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfcc522f8d40</guid>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Raja Gupta ]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 12:53:39 GMT</pubDate>
            <atom:updated>2026-11-03T12:53:39.197Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with private Google Kubernetes Engine (GKE) clusters, you probably know that accessing the Kubernetes API server can sometimes be a little frustrating.</p><p>Recently, I worked on a scenario where a customer had a private GKE cluster with both public and private control plane endpoints enabled, along with authorized networks.</p><p>The challenge?</p><p>Every time the customer opened a new Google Cloud Shell session, the external IP address changed. This meant they had to manually add the new Cloud Shell IP to the GKE Control Plane Authorized Networks before running kubectl commands.</p><p>To reduce this manual effort, I created a small automation script that automatically identifies the Cloud Shell public IP and updates the GKE authorized networks.</p><p>I also explored how to connect to the same private GKE cluster from a Compute Engine VM.</p><p>Let’s walk through both approaches.</p><h3>1. Understanding the Customer’s GKE Network Configuration</h3><p>The customer had a private GKE cluster with the following control plane networking configuration:</p><p>Configuration Value</p><p>DNS endpoint =&gt; Disabled</p><p>Control plane access using IPv4 =&gt; Enabled</p><p>Public endpoint =&gt; <strong>34.1.1.1</strong></p><p>Private endpoint =&gt;<strong>10.1.0.1</strong></p><p>Internal IP access from any region =&gt; Disabled</p><p>Authorized networks =&gt; <strong>Enabled</strong></p><p>Cloud Shell authorized IP =&gt; <strong>136.6.1.1/32</strong></p><p>Enforce authorized networks on internal endpoint =&gt; Enabled</p><p>Add Google Cloud external IPs to authorized networks =&gt; Disabled</p><p><em>Note: The IP addresses above are illustrative and VM Ip should be added under authorized ip for section 3.</em></p><h3>What was the actual problem?</h3><p>Cloud Shell provides an external IP address that can change when a new session is created.</p><p>For example:</p><pre>Cloud Shell Session 1<br>External IP: 136.6.1.1<br><br>Cloud Shell Session 2<br>External IP: 136.6.2.1<br><br>Cloud Shell Session 3<br>External IP: 136.6.3.1</pre><p>Since GKE authorized networks only allow requests from configured IP ranges, a new Cloud Shell session could lose access to the Kubernetes API server.</p><p>The customer had to:</p><ol><li>Open Cloud Shell.</li><li>Retrieve the current public IP.</li><li>Navigate to GKE networking settings.</li><li>Add the IP to authorized networks.</li><li>Wait for the configuration update.</li><li>Run kubectl commands.</li></ol><p>This became repetitive manual work.</p><p><strong>My goal was to automate this process whenever a new Cloud Shell session was initialized.</strong></p><h3>2. Automating Cloud Shell IP Authorization Using .bashrc</h3><p>Instead of manually updating authorized networks every time, I used the .bashrc file.</p><p>The .bashrc file is executed when an interactive Bash shell starts, making it useful for automating environment initialization tasks.</p><h3>Step 1: Open the .bashrc file</h3><pre>nano ~/.bashrc</pre><h3>Step 2: Add the following script</h3><pre># Automatically whitelist ephemeral Cloud Shell IP for GKE<br>authorize_gke_shell() {<br>    local CLUSTER=&quot;cluster-private-check&quot;<br>    local ZONE=&quot;asia-south1-a&quot;<br>    echo &quot;Checking Cloud Shell IP authorization for GKE...&quot;<br>    local MY_IP=$(curl -s https://ifconfig.me)<br>    if [ ! -z &quot;$MY_IP&quot; ]; then<br>        echo &quot;Current Cloud Shell IP: $MY_IP&quot;<br>        gcloud container clusters update &quot;$CLUSTER&quot; \<br>            --zone &quot;$ZONE&quot; \<br>            --enable-master-authorized-networks \<br>            --master-authorized-networks &quot;$MY_IP/32&quot; \<br>            --async<br>        gcloud container clusters get-credentials &quot;$CLUSTER&quot; \<br>            --zone &quot;$ZONE&quot; &amp;&gt; /dev/null<br>        echo &quot;Authorization update triggered.&quot;<br>    else<br>        echo &quot;Failed to retrieve Cloud Shell public IP.&quot;<br>    fi<br>}<br>authorize_gke_shell</pre><h3>Step 3: Reload .bashrc</h3><p>After saving the file, execute:</p><pre>source ~/.bashrc</pre><p>Now, whenever a new interactive Cloud Shell session starts, the script:</p><ol><li>Retrieves the current Cloud Shell public IP using curl.</li><li>Appends /32 to authorize only that specific IPv4 address.</li><li>Triggers a GKE authorized networks update.</li><li>Retrieves the cluster credentials in the background.</li></ol><p>The idea is simple: automate the repetitive networking configuration so that the customer doesn’t need to manually update authorized networks for every new Cloud Shell session.</p><h3>Important: Zone vs Region</h3><p>In the example, I used:</p><pre>--zone &quot;$ZONE&quot;</pre><p>because the cluster is a zonal cluster.</p><p>If you are working with a regional GKE cluster, replace the zone argument with:</p><pre>--region &quot;$REGION&quot;</pre><p>Also, one important consideration: the --master-authorized-networks flag sets the authorized networks list supplied to the update command. It does not safely append an IP to the existing list by itself.</p><p>If you want to preserve existing authorized IP ranges, retrieve the current list and merge it with the new Cloud Shell IP before applying the update.</p><p>For production use, I would also recommend validating the retrieved IP and checking whether the update operation has actually completed before running kubectl commands.</p><h3>3. Connecting to a Private GKE Cluster from a Compute Engine VM</h3><p>The second requirement was to access the private GKE cluster directly from a Compute Engine VM.</p><p>This is another common scenario, especially when teams use a jump host or administration VM to manage Kubernetes workloads.</p><p>I used my environment to validate the connectivity steps.</p><h3>Step 1: Add the VM’s IP to GKE Authorized Networks</h3><p>First, retrieve the VM’s public IP:</p><pre>curl ifconfig.me</pre><p>Add this IP as a /32 entry in the GKE Control Plane Authorized Networks.</p><p>This allows the VM’s public source IP to access the authorized control plane endpoint.</p><h3>Step 2: Assign the Required IAM Role</h3><p>The Compute Engine VM’s service account needs permission to retrieve cluster information.</p><p>I assigned:</p><pre>Kubernetes Engine Cluster Viewer</pre><p>to the VM’s service account.</p><p>This provides the required cluster metadata access for retrieving credentials.</p><p>The service account also needs appropriate Kubernetes RBAC permissions to perform the intended kubectl operations. Cluster Viewer alone does not automatically grant permission to list Kubernetes nodes or manage workloads.</p><h3>Step 3: Install kubectl and the GKE Authentication Plugin</h3><p>Update the package repositories:</p><pre>sudo apt-get update</pre><p>Install kubectl:</p><pre>sudo apt-get install -y kubectl</pre><p>Install the GKE authentication plugin:</p><pre>sudo apt-get install -y google-cloud-cli-gke-gcloud-auth-plugin</pre><p>The gke-gcloud-auth-plugin is required for GKE authentication with kubectl in modern GKE environments, including GKE v1.26 and later.</p><h3>Step 4: Authenticate with Google Cloud</h3><p>For an interactive user-based login:</p><pre>gcloud auth login</pre><h3>Step 5: Retrieve GKE Cluster Credentials</h3><p>Run:</p><pre>gcloud container clusters get-credentials cluster-private-check \<br>    --location asia-south1-a</pre><p>This command retrieves the cluster connection details and updates the local kubeconfig file.</p><p>Here, --location can accept either a zone or a region, depending on your cluster configuration.</p><h3>Step 6: Validate Connectivity</h3><p>Now execute:</p><pre>kubectl get nodes</pre><p>If the authentication, IAM permissions, network routing, firewall rules, and authorized networks are configured correctly, you should be able to retrieve the cluster nodes.</p><h3>3.1 Still Unable to Connect? Check Your Kubeconfig</h3><p>One additional troubleshooting step I recommend is checking which control plane endpoint kubectl is trying to access.</p><p>Execute:</p><pre>kubectl config view</pre><p>Look for the following field:</p><pre>clusters:<br>- cluster:<br>    server: https://34.1.1.1</pre><p>The server field identifies the Kubernetes API endpoint configured in your kubeconfig.</p><p>If you intended to connect through the private endpoint but see the public endpoint, verify your cluster configuration and connection method.</p><p>For example, the expected private endpoint would look like:</p><pre>clusters:<br>- cluster:<br>    server: https://10.1.0.1</pre><h3>5. Final Takeaway</h3><p>In this scenario, I handled two common requirements when working with private GKE clusters:</p><p><strong>Problem 1: Cloud Shell IP changes with every new session.</strong></p><p>Solution: Automate public IP detection and authorized network updates through .bashrc.</p><p><strong>Problem 2: Accessing a private GKE cluster from a Compute Engine VM.</strong></p><p>Solution: Configure authorized networks where applicable, assign the necessary IAM permissions, install kubectl and the GKE authentication plugin, retrieve cluster credentials, and validate connectivity.</p><p>A few things worth remembering:</p><ul><li>GKE authorized networks control which client IP ranges can access the applicable control plane endpoint.</li><li>Cloud Shell public IPs can change between sessions.</li><li>IAM permissions and Kubernetes RBAC permissions are two different things.</li><li>A successful get-credentials command does not guarantee network connectivity.</li><li>Always verify whether kubectl is using the public or private control plane endpoint.</li></ul><p><strong>The bigger takeaway:</strong> Small automation scripts can eliminate repetitive operational tasks, while understanding the difference between authentication, authorization, and network connectivity makes GKE troubleshooting much easier.</p><p>I hope this helps someone facing a similar private GKE connectivity challenge!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfcc522f8d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshooting a Kubernetes API Server Write Stall in GKE: Investigation and Root Cause Analysis]]></title>
            <link>https://medium.com/@rajagup05/troubleshooting-a-kubernetes-api-server-write-stall-in-gke-investigation-and-root-cause-analysis-6c7084718a51?source=rss-b7e087bd8431------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c7084718a51</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Raja Gupta ]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 18:00:23 GMT</pubDate>
            <atom:updated>2026-10-25T18:00:23.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Happened?</h3><p>For approximately three minutes, the Kubernetes API server experienced a severe stall in write requests across all namespaces. As a consequence, a workload in the customer’s prod namespace crashed twice.</p><h3>Symptoms</h3><p>Approximately 100 write operations failed or exceeded standard client timeouts of 5s, 10s, and 34s.</p><p>Both system and user control-plane clients were affected, including:</p><ul><li>kube-scheduler</li><li>cluster-autoscaler</li><li>konnectivity-server</li><li>gke-common-webhooks</li><li>Kubelet leases</li><li>CiliumEndpoints</li><li>Istio services</li></ul><p>The following errors were observed:</p><pre>Timeout: request did not complete within requested timeout - context canceled</pre><pre>Timeout: request did not complete within requested timeout - context deadline exceeded</pre><h3>Additional Diagnostic Data</h3><p>The initial investigation revealed the following:</p><ul><li><strong>API Priority and Fairness (APF):</strong> Queue wait was negligible, at approximately 30 microseconds.</li><li><strong>Authentication, authorization, and admission webhooks:</strong> Requests completed within milliseconds.</li><li><strong>API write rate:</strong> Remained steady at approximately 900 writes per minute.</li><li><strong>Pod churn:</strong> Low, accounting for less than 1% of write volume, with a seven-day peak of approximately 600 pods per day.</li><li><strong>API server identity leases:</strong> Renewed consistently every 10 seconds, indicating that the kube-apiserver processes had not restarted.</li><li><strong>Cluster operations:</strong> No operations or upgrades were recorded during the incident.</li><li><strong>Regional comparison:</strong> Three other GKE clusters in the same region showed zero errors during the same period.</li></ul><p>These observations helped narrow the investigation toward the backend write path rather than request queuing, webhook latency, or an API server restart.</p><h3>1. Foundational Architecture: How the GKE Control Plane and Cluster State Database Work</h3><h3>Where Does the Control Plane Run?</h3><p>In GKE Standard, the cluster control plane is hosted in a Google-managed project rather than directly in the customer’s Google Cloud project. This environment is commonly referred to as the GKE tenant project.</p><p>For a regional GKE cluster, the control plane is designed for high availability across multiple zones.</p><p>The kube-apiserver handles Kubernetes API requests, while the cluster state database stores Kubernetes object state.</p><p><strong>An important architectural detail:</strong> The underlying cluster state database depends on the GKE configuration. Some GKE clusters use etcd-based storage, while others use a Spanner-based system. This distinction becomes important when investigating storage-related incidents.</p><h3>The Life of a Kubernetes Write Request</h3><p>When a client such as kubectl, a controller, or the kubelet modifies an object using CREATE, UPDATE, PATCH, or DELETE, the request passes through several stages.</p><pre>Client Request<br>      |<br>      v<br>API Server Ingress<br>      |<br>      v<br>API Priority and Fairness (APF)<br>      |<br>      v<br>Authentication and Authorization<br>      |<br>      v<br>Admission Webhooks<br>      |<br>      v<br>Cluster State Database<br>      |<br>      v<br>HTTP Response to Client</pre><p><strong>API Priority and Fairness (APF):</strong> Controls request concurrency and queuing to help prevent API server overload.</p><p><strong>Authentication and Authorization (AuthN/AuthZ):</strong> Verifies the caller’s identity and whether the request is permitted.</p><p><strong>Admission Webhooks:</strong> Invokes applicable validating and mutating webhooks, such as those used by Istio, Cilium, or Gatekeeper.</p><p><strong>Database Transaction:</strong> The API server persists the change in the cluster state database. In an etcd-based architecture, writes involve the etcd leader and replication to maintain consistency.</p><p><strong>HTTP Response:</strong> Once the request completes successfully, the API server returns a response to the client.</p><p>The overall client-perceived latency can be represented approximately as:</p><p>[T_{{total}} = T_{{APF}} + T_{\text{Auth}} + T_{{Webhooks}} + T_{{Database}} +{Other}} ]</p><p>The exact stages and their timing depend on the request and the underlying implementation.</p><p>In this incident, APF queue wait was negligible, and authentication, authorization, and webhook processing completed in milliseconds. This made the database and other downstream processing stages important areas to investigate.</p><h3>2. The Core Mechanism: etcd Compaction vs. Defragmentation</h3><p>In an etcd-based Kubernetes cluster, etcd stores data as key-value pairs.</p><p>When a Kubernetes object is updated or deleted, etcd maintains revisions rather than simply overwriting every previous version in place. Over time, historical revisions accumulate.</p><p>Two maintenance operations are important to understand.</p><h3>Compaction</h3><p>Compaction removes the availability of historical revisions before a specified revision.</p><p>It allows etcd to discard old versions from its logical history, but it does not necessarily reclaim the corresponding disk space immediately.</p><p>Compaction is a normal database maintenance operation. It should not automatically be assumed to be the cause of a write stall.</p><h3>Defragmentation</h3><p>Defragmentation reclaims storage space occupied by deleted or obsolete data within the database’s backend storage.</p><p>Unlike compaction, defragmentation can involve expensive storage operations and may affect database responsiveness, depending on the implementation and workload.</p><p>However, <strong>compaction and defragmentation were not established as the cause of this incident</strong>. The investigation first needed to confirm which cluster state database the customer’s GKE cluster actually used.</p><h3>3. Breaking Down the Customer’s Evidence</h3><h3>A. Write Requests Timed Out</h3><p>Approximately 100 write requests experienced significant delays or exceeded their client deadlines.</p><p>The observed errors included:</p><pre>context canceled<br>context deadline exceeded</pre><p>These errors indicate that the requests did not complete within the applicable client deadlines or were canceled before completion.</p><p>They do not, by themselves, identify the underlying component responsible for the delay.</p><p>The key observation was that requests across different namespaces and multiple system components were affected during the same short time window.</p><h3>B. Affected Callers: Node Leases and System Controllers</h3><p>Kubernetes worker nodes periodically renew their leases to report that they are alive and functioning.</p><p>Control-plane components also use leases for mechanisms such as leader election.</p><p>When lease updates cannot be persisted promptly, components can experience timeouts and may temporarily lose the ability to renew their leases.</p><p>Depending on the component and its configuration, this can trigger retries, leadership changes, or other recovery behavior.</p><p>In this incident, the API server identity leases continued to renew every 10 seconds, and the kube-apiserver processes did not restart.</p><p>This was an important distinction: the control plane remained running even though write requests were experiencing severe delays.</p><h3>C. Why Did the Workload Crash Twice?</h3><p>The workload in the customer’s namespace restarted twice during the incident.</p><p>Distributed production applications may depend on Kubernetes API operations for leader election, lease renewal, or coordination with other components.</p><p>Applications may also use liveness probes to detect internal failures.</p><p>If the API server becomes unresponsive to required operations, an application may:</p><ul><li>Fail to renew a leadership lease.</li><li>Lose leadership or coordination state.</li><li>Fail an application-specific health check.</li><li>Restart because of a failed liveness probe or an internal process failure.</li></ul><p>These are possible mechanisms through which API server write stalls can affect an application. In this case, the workload failures were observed during the incident, but the precise application-level restart mechanism should be distinguished from the confirmed control-plane symptoms.</p><h3>D. Why Did the Other Regional Clusters Remain Healthy?</h3><p>Three other GKE clusters in the same region showed no errors during the incident.</p><p>This indicated that the observed issue was not affecting every cluster in the region uniformly.</p><p>It was useful comparative evidence, although it did not by itself establish the exact underlying cause.</p><h3>4. Key Checks Performed During the further Investigation</h3><h3>1. etcd Database Size and Historical Trends</h3><p>I checked Google Cloud Monitoring’s Metrics Explorer to review database usage and limits over the preceding two weeks.</p><p>The observed values were approximately:</p><ul><li>Database usage: <strong>0.03 GB</strong></li><li>Reported limit: <strong>6 GB</strong></li></ul><p>Both remained consistent throughout the period.</p><p>These observations did not indicate an obvious database capacity increase or saturation.</p><h3>2. Compaction and Defragmentation Events</h3><p>I verified the cluster’s state database architecture and confirmed that the customer was using a Spanner-based system rather than the etcd-based storage architecture assumed initially.</p><p>GKE documentation describes the available cluster state database architecture:</p><p><a href="https://docs.cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture#cluster-state-database">https://docs.cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture#cluster-state-database</a></p><p>This was an important finding because <strong>etcd compaction and defragmentation were not applicable as direct maintenance operations for the customer’s Spanner-based state database</strong>.</p><p>The investigation therefore needed to account for the actual backend implementation instead of assuming etcd behavior.</p><h3>3. API Server and Component Restarts</h3><p>I checked whether the API server or other control-plane components had restarted or experienced leader changes.</p><p>The evidence showed that:</p><ul><li>API server identity leases continued to renew every 10 seconds.</li><li>The kube-apiserver processes remained running.</li><li>Some components experienced restarts or recovery behavior associated with lease failures.</li></ul><p>This supported the observation that the affected components were reacting to the temporary backend unresponsiveness rather than all being independently unhealthy.</p><h3>4. Control-Plane VM Host and Live-Migration Events</h3><p>I checked for possible host-level events and control-plane VM live migrations.</p><p>The control-plane nodes had been running for approximately six days and remained on the same hosts and the incident took place the previous day.</p><p>No host change or control-plane live migration was identified during the incident that happened one day prior to this investigation.</p><p>This reduced the likelihood of a host transition explaining the observed stall.</p><h3>5. Conclusion</h3><p>The Kubernetes API server experienced approximately three minutes of severe write-request delays, affecting both system and user workloads.</p><p>The investigation established several important facts:</p><ul><li>API Priority and Fairness queue wait was negligible.</li><li>Authentication, authorization, and admission webhook processing completed in milliseconds.</li><li>API write traffic remained steady.</li><li>The kube-apiserver processes remained running, with identity leases renewing consistently.</li><li>The cluster used a Spanner-based state database, making etcd-specific compaction and defragmentation checks inapplicable.</li><li>No control-plane host change or live migration was identified.</li><li>Three other GKE clusters in the same region showed no corresponding errors.</li></ul><p>The cluster subsequently recovered once backend connectivity stabilized, and no further action was required from the customer to maintain stability.</p><p><strong>The key lesson from this incident:</strong></p><p><strong>Understand the system before troubleshooting it </strong>🤔</p><p>When Kubernetes API write requests stall, avoid jumping immediately to etcd, webhook latency, or API server restarts as the explanation. First, establish which part of the request path is delayed, confirm the underlying cluster state database architecture, and correlate the symptoms with component health, lease behavior, and infrastructure events.</p><p>A structured investigation helps separate the observed symptoms from the underlying cause and avoids spending time troubleshooting components that are not part of the customer’s actual architecture.</p><p>The cluster eventually recovered, but the investigation reinforced a lesson that applies far beyond Kubernetes:</p><p><strong>Errors tell you where to start looking. Evidence tells you where to look next.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c7084718a51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Binary Authorization in GKE: A Complete End-to-End Guide]]></title>
            <link>https://medium.com/@rajagup05/how-to-set-up-binary-authorization-in-gke-a-complete-end-to-end-guide-e0127ad9a051?source=rss-b7e087bd8431------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0127ad9a051</guid>
            <category><![CDATA[binary-authorization]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Raja Gupta ]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 12:25:22 GMT</pubDate>
            <atom:updated>2026-09-13T12:25:22.557Z</atom:updated>
            <content:encoded><![CDATA[<p>Step-by-step guide to enabling Binary Authorization on GKE — from creating a PKIX KMS key and attestor to signing images with gcloud and deploying via YAML.</p><h3>Why I wrote this</h3><p>If you’ve tried setting up <strong>Binary Authorization on GKE</strong>, you’ve probably noticed the same thing I did: the official Google Cloud documentation covers each piece — enabling the feature, creating a KMS key, creating an attestor, signing an image — but it’s spread across <em>multiple separate docs</em>, none of which walk you through the full pipeline in one place.</p><p>I recently set this up end-to-end in my own environment, and this post is the single walkthrough I wish I’d had — from enabling Binary Authorization at the cluster level, all the way to a signed image successfully deploying through a policy that requires attestation.</p><p>If you’re securing your GKE supply chain and want to make sure only verified, signed container images can be deployed to your cluster, this guide covers the full path.</p><h3>What is Binary Authorization?</h3><p>Binary Authorization is a deploy-time security control for GKE (and Cloud Run) that lets you enforce a policy requiring container images to be signed by trusted authorities — called <strong>attestors</strong> — before they can be deployed to your cluster. If an image doesn’t have the required attestation, Kubernetes simply refuses to schedule it.</p><p>This is especially useful for enforcing that only images which passed your CI/CD pipeline, vulnerability scanning, or a manual security review can reach production.</p><h3>Prerequisites</h3><p>Before starting, make sure you have:</p><ul><li>A GKE cluster (Standard mode) with appropriate IAM permissions</li><li>gcloud CLI installed and authenticated</li><li>A Cloud KMS keyring and key location decided in advance</li><li>An image already pushed to Artifact Registry</li></ul><h3>Step 1: Enable Binary Authorization at the Cluster Level</h3><p>Binary Authorization is not on by default — it has to be explicitly enabled per GKE cluster.</p><p>In the Google Cloud Console:</p><ol><li>Go to <strong>Kubernetes Engine → Clusters</strong></li><li>Select your cluster and click <strong>Edit</strong></li><li>Under <strong>Security</strong>, find <strong>Binary Authorization</strong> and toggle it <strong>On</strong></li><li>Save the changes</li></ol><p>You can also do this via gcloud if you prefer CLI-first workflows, but the console path is the quickest way to confirm it&#39;s applied correctly the first time.</p><h3>Step 2: Create a PKIX KMS Key Pair</h3><p>Next, you need a <strong>PKIX key pair</strong> stored in Cloud KMS — this is the cryptographic key your attestor will use to verify signatures.</p><p>Google’s official steps for this are here: <a href="https://docs.cloud.google.com/binary-authorization/docs/creating-attestors-console#create-pkix-key-pair">Create a PKIX key pair</a></p><p>At a high level:</p><ol><li>Create (or select) a Cloud KMS <strong>keyring</strong> in a chosen region</li><li>Create a new <strong>key</strong> within that keyring, selecting <strong>asymmetric sign</strong> as the purpose and an appropriate elliptic curve or RSA algorithm</li><li>Once created, Cloud KMS generates a key version — this version is what you’ll reference later during both attestor creation and image signing</li></ol><p>Keep note of the <strong>project, location, keyring name, key name, and key version</strong> — you’ll need all five values again in Step 5.</p><h3>Step 3: Create an Attestor and Attach the KMS Key</h3><p>An <strong>attestor</strong> is the entity whose signature Binary Authorization checks for at deploy time. You create the attestor, then attach the PKIX public key from Step 2 as its verification key.</p><p>Follow Google’s guide here: <a href="https://docs.cloud.google.com/binary-authorization/docs/creating-attestors-console#create-the-attestor">Create the attestor</a></p><p>In short:</p><ol><li>Go to <strong>Security → Binary Authorization → Attestors</strong> in the console</li><li>Click <strong>Create Attestor</strong>, give it a name, and link it to a Container Analysis note (created automatically if it doesn’t exist)</li><li>Add a <strong>public key</strong> to the attestor — select <strong>PKIX public key</strong>, and provide the <strong>KMS key resource ID</strong> you created in Step 2</li></ol><p>This step is where the two pieces — your KMS key and your policy enforcement — actually get connected.</p><h3>Step 4: Set the Binary Authorization Policy to Require Attestations</h3><p>With the attestor in place, you now need to tell your cluster’s policy to actually enforce it.</p><ol><li>Go to <strong>Security → Binary Authorization → Policy</strong></li><li>Under the <strong>Default rule</strong>, select <strong>Require attestations</strong></li><li>Add the <strong>attestor name</strong> you created in Step 3 to the list of required attestors</li><li>Save the policy</li></ol><p>From this point forward, any image that doesn’t carry a valid attestation from this attestor will be <strong>blocked from deployment</strong> on this cluster.</p><h3>Step 5: Sign the Image and Create the Attestation</h3><p>This is the step that actually produces a valid, verifiable signature for a specific image digest, using the gcloud CLI.</p><p>Reference doc: <a href="https://docs.cloud.google.com/sdk/gcloud/reference/beta/container/binauthz/attestations/sign-and-create">gcloud beta container binauthz attestations sign-and-create</a></p><pre>gcloud beta container binauthz attestations sign-and-create \<br>    --project=&quot;${ATTESTATION_PROJECT_ID}&quot; \<br>    --artifact-url=&quot;${IMAGE_TO_ATTEST}&quot; \<br>    --attestor=&quot;${ATTESTOR_NAME}&quot; \<br>    --attestor-project=&quot;${ATTESTOR_PROJECT_ID}&quot; \<br>    --keyversion-project=&quot;${KMS_KEY_PROJECT_ID}&quot; \<br>    --keyversion-location=&quot;${KMS_KEY_LOCATION}&quot; \<br>    --keyversion-keyring=&quot;${KMS_KEYRING_NAME}&quot; \<br>    --keyversion-key=&quot;${KMS_KEY_NAME}&quot; \<br>    --keyversion=&quot;${KMS_KEY_VERSION}&quot;</pre><p>A few things worth calling out from real-world testing:</p><ul><li>--artifact-url must reference the image <strong>by digest (SHA)</strong>, not by a mutable tag like :latest. Binary Authorization attests to a specific immutable image, not a tag.</li><li>ATTESTATION_PROJECT_ID and ATTESTOR_PROJECT_ID will often be the same project, but Binary Authorization supports cross-project setups if your attestor lives elsewhere.</li></ul><h3>Step 6: Deploy the Signed Image via YAML</h3><p>With the image signed and the policy enforced, deployment works exactly like a normal Kubernetes deployment — as long as the image reference uses the <strong>same digest</strong> that was signed in Step 5.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: link-bio-app-deployment<br>  labels:<br>    app: link-bio-app<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: link-bio-app<br>  template:<br>    metadata:<br>      labels:<br>        app: link-bio-app<br>    spec:<br>      containers:<br>      - name: link-bio-app<br>        image: &lt;image with SHA ID stored in artifact registry&gt;<br>        ports:<br>        - containerPort: 8080 # Adjust this to match your application&#39;s listening port</pre><p>Apply it as usual:</p><pre>kubectl apply -f deployment.yaml</pre><p>If everything in Steps 1–5 was configured correctly, the deployment is admitted and the pods roll out normally. If the image digest doesn’t match a valid attestation, Kubernetes will reject the pod creation with a Binary Authorization denial message instead — which is exactly the enforcement you’re testing for.</p><h3>Result</h3><p>In my test environment, this exact flow produced a successful deployment named scc-test5 — confirming that the signed image passed policy validation and was admitted to the cluster.</p><h3>Wrapping Up</h3><p>Binary Authorization is one of those GKE security features that’s genuinely simple in concept — only deploy images that are signed and verified — but the setup is scattered across enough separate docs that it’s easy to get stuck halfway through. Hopefully having all six steps in one place saves you the same trial-and-error I went through.</p><p>If you run into issues specific to cross-project attestor setups or CI/CD integration (e.g., signing automatically in a Cloud Build pipeline), that’s a natural next post — let me know if that’s useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0127ad9a051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Probes in GKE: Startup, Readiness, Liveness and How They Actually Work]]></title>
            <link>https://medium.com/@rajagup05/kubernetes-probes-in-gke-startup-readiness-liveness-and-how-they-actually-work-d42bb99cc25e?source=rss-b7e087bd8431------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42bb99cc25e</guid>
            <category><![CDATA[kubernetes-probes]]></category>
            <category><![CDATA[google-kubernetes-engine]]></category>
            <category><![CDATA[livenessprobe]]></category>
            <category><![CDATA[kubernetes-pods]]></category>
            <category><![CDATA[readinessprobe]]></category>
            <dc:creator><![CDATA[Raja Gupta ]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 09:32:45 GMT</pubDate>
            <atom:updated>2026-08-29T09:34:29.717Z</atom:updated>
            <content:encoded><![CDATA[<p>When running applications on <strong>Google Kubernetes Engine (GKE)</strong>, Kubernetes needs to answer three simple questions:</p><ol><li><strong>Has the application started?</strong></li><li><strong>Can the application receive traffic?</strong></li><li><strong>Is the application still healthy?</strong></li></ol><p>Kubernetes provides three probes for this:</p><ul><li><strong>Startup Probe</strong></li><li><strong>Readiness Probe</strong></li><li><strong>Liveness Probe</strong></li></ul><p>Each probe has a different purpose, and understanding their execution flow is important when designing reliable deployments.</p><h3>1. Startup Probe</h3><p>A <strong>startup probe</strong> answers:</p><blockquote><strong><em>“Has my application successfully started?”</em></strong></blockquote><p>It is useful for applications that take a long time to initialize and their start times are unpredictable (Like an app can start within 10 seconds and sometimes can start in 60 seconds).</p><p>For example:</p><pre>startupProbe:<br>  httpGet:<br>    path: /<br>    port: 80<br>  periodSeconds: 5<br>  failureThreshold: 12</pre><p>Here:</p><pre>periodSeconds: 5<br>failureThreshold: 12</pre><p>allows approximately:</p><pre>5 × 12 = 60 seconds</pre><p>for the application to successfully start before Kubernetes considers the startup probe failed.</p><h3>Why is startupProbe important?</h3><p>When a startup probe is configured, Kubernetes does <strong>not</strong> run the liveness and readiness probes until the startup probe succeeds.</p><p>Conceptually:</p><pre>Container starts<br>      │<br>      ▼<br>Startup Probe<br>      │<br>      ├── FAIL → keep waiting/retry<br>      │<br>      └── SUCCESS<br>             │<br>             ▼<br>       Readiness + Liveness</pre><p>This prevents a slow-starting application from being restarted by its liveness probe before it has finished initialization.</p><h3>2. Readiness Probe</h3><p>A readiness probe answers:</p><blockquote><strong><em>“Can this pod receive traffic right now?”</em></strong></blockquote><p>Example:</p><pre>readinessProbe:<br>  httpGet:<br>    path: /<br>    port: 80<br>  periodSeconds: 5<br>  failureThreshold: 3</pre><p>If the readiness probe fails, Kubernetes does <strong>not necessarily restart the container</strong>.</p><p>Instead, the pod becomes <strong>NotReady</strong>, and Kubernetes removes it from the endpoints used for normal Service traffic.</p><p>Conceptually:</p><pre>Readiness = FAIL<br>       │<br>       ▼<br>Pod becomes NotReady<br>       │<br>       ▼<br>Traffic stops being sent to the pod<br>       │<br>       ▼<br>Container continues running</pre><p>This is useful when an application is temporarily unable to serve requests but does not need to be restarted.</p><p>For example:</p><pre>Application starts<br>       ↓<br>Database connection unavailable<br>       ↓<br>Readiness = FAIL<br>       ↓<br>Pod stays running<br>       ↓<br>Traffic is removed<br>       ↓<br>Database becomes available<br>       ↓<br>Readiness = SUCCESS<br>       ↓<br>Traffic returns</pre><h3>3. Liveness Probe</h3><p>A liveness probe answers:</p><blockquote><strong><em>“Is my application still healthy, or should the container be restarted?”</em></strong></blockquote><p>Example:</p><pre>livenessProbe:<br>  httpGet:<br>    path: /<br>    port: 80<br>  periodSeconds: 10<br>  failureThreshold: 3</pre><p>If the liveness probe fails enough consecutive times, Kubernetes restarts the container.</p><pre>Liveness = FAIL<br>       │<br>       ▼<br>failureThreshold reached<br>       │<br>       ▼<br>Container restarted</pre><p>This is useful for situations such as:</p><ul><li>deadlocks</li><li>application hangs</li><li>unrecoverable internal state</li><li>application process becoming unhealthy</li></ul><h3>4. Types of Probe Checks</h3><p>Kubernetes supports four main probing mechanisms.</p><h3>HTTP GET</h3><p>Checks an HTTP endpoint.</p><pre>httpGet:<br>  path: /health<br>  port: 8080</pre><p>Example:</p><pre>GET /health<br>       │<br>       ├── HTTP 2xx/3xx → SUCCESS<br>       └── failure      → FAIL</pre><p>This is commonly used for HTTP applications.</p><p>You can also configure fields such as:</p><pre>httpGet:<br>  path: /health<br>  port: 8080<br>  scheme: HTTP<br>  httpHeaders:<br>    - name: Custom-Header<br>      value: probe</pre><h3>5. Exec Probe</h3><p>Exec runs a command inside the container.</p><pre>livenessProbe:<br>  exec:<br>    command:<br>      - cat<br>      - /tmp/healthy</pre><p>Kubernetes considers the probe successful when the command exits with status code 0.</p><p>For example:</p><pre>cat /tmp/healthy<br>       │<br>       ├── exit 0 → SUCCESS<br>       └── non-zero → FAIL</pre><p>One important detail:</p><p>exec.command is <strong>not automatically executed through a shell</strong>.</p><p>If shell syntax is required, explicitly use:</p><pre>exec:<br>  command:<br>    - /bin/sh<br>    - -c<br>    - &quot;test -f /tmp/healthy&quot;</pre><h3>6. TCP Socket Probe</h3><p>A TCP probe checks whether a TCP connection can be established.</p><pre>livenessProbe:<br>  tcpSocket:<br>    port: 8080</pre><p>Conceptually:</p><pre>Kubernetes<br>    │<br>    │ TCP connection<br>    ▼<br>Container :8080<br>    │<br>    ├── connection succeeds → SUCCESS<br>    └── connection fails    → FAIL</pre><p>This can be useful when the application does not expose an HTTP health endpoint.</p><p>However, a TCP connection only proves that something is accepting connections. It does not necessarily prove that the application is functioning correctly.</p><h3>7. gRPC Probe</h3><p>Kubernetes also supports native gRPC health probing.</p><pre>livenessProbe:<br>  grpc:<br>    port: 50051<br>    service: my-service</pre><p>The application needs to implement the gRPC health checking protocol.</p><p>Conceptually:</p><pre>Kubernetes<br>    │<br>    ▼<br>gRPC Health Check<br>    │<br>    ├── SERVING → SUCCESS<br>    └── otherwise → FAIL</pre><p>This is useful for gRPC-based applications where HTTP endpoints may not exist.</p><h3>8. Common Probe Configuration Fields</h3><p>Most probe types use these timing-related fields:</p><pre>periodSeconds: 5<br>timeoutSeconds: 2<br>failureThreshold: 3<br>successThreshold: 1<br>initialDelaySeconds: 5</pre><h3>initialDelaySeconds</h3><p>How long Kubernetes waits before starting the probe (readiness and liveness).</p><pre>initialDelaySeconds: 5</pre><h3>periodSeconds</h3><p>How frequently the probe runs. For eg. here probe check happens every 5 seconds.</p><pre>periodSeconds: 5</pre><h3>timeoutSeconds</h3><p>How long Kubernetes waits for a probe response from the application.</p><pre>timeoutSeconds: 2</pre><h3>failureThreshold</h3><p>Number of consecutive failures required before the probe is considered failed.</p><pre>failureThreshold: 3</pre><h3>successThreshold</h3><p>Number of consecutive successes required to consider the probe successful.</p><p>Usually:</p><pre>successThreshold: 1</pre><p>For liveness and startup probes, the success threshold must be 1.</p><h3>9. Complete Example</h3><p>The following example puts startup, readiness, liveness, initialization, and termination behavior together:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: production-demo</pre><pre>spec:<br>  terminationGracePeriodSeconds: 30</pre><pre>  initContainers:<br>    - name: init<br>      image: busybox:1.36<br>      command:<br>        - sh<br>        - -c<br>        - |<br>          echo &quot;Initialization complete&quot;</pre><pre>  containers:<br>    - name: app<br>      image: nginx:1.27</pre><pre>      startupProbe:<br>        httpGet:<br>          path: /<br>          port: 80<br>        periodSeconds: 5<br>        failureThreshold: 12</pre><pre>      readinessProbe:<br>        httpGet:<br>          path: /<br>          port: 80<br>        periodSeconds: 5<br>        failureThreshold: 3</pre><pre>      livenessProbe:<br>        httpGet:<br>          path: /<br>          port: 80<br>        periodSeconds: 10<br>        failureThreshold: 3</pre><pre>      lifecycle:<br>        preStop:<br>          exec:<br>            command:<br>              - /bin/sh<br>              - -c<br>              - &quot;sleep 5&quot;</pre><p>Now let’s understand the execution flow.</p><h3>10. Complete Pod Execution Flow</h3><p>The lifecycle looks roughly like this:</p><pre>Pod created<br>    │<br>    ▼<br>Init container starts<br>    │<br>    ▼<br>Init container completes<br>    │<br>    ▼<br>Application container starts<br>    │<br>    ▼<br>Startup Probe<br>    │<br>    ├── FAIL → retry<br>    │<br>    └── SUCCESS<br>          │<br>          ├───────────────┐<br>          ▼               ▼<br>     Readiness         Liveness<br>          │               │<br>          │               ├── FAIL repeatedly<br>          │               │       ↓<br>          │               │   Container restart (crashloopbackoff)<br>          │               │<br>          ├── FAIL        │<br>          │     ↓         │<br>          │  No traffic   │<br>          │               │<br>          └── SUCCESS     │<br>                ↓         │<br>             Traffic      │<br>                         │<br>                         ▼<br>                  Container remains<br>                       healthy</pre><h3>11. What Happens During Pod Termination?</h3><p>Now consider:</p><pre>terminationGracePeriodSeconds: 30</pre><p>When Kubernetes terminates the pod, it provides a grace period for the container to shut down cleanly by sending a SIGTERM. If container fails to stop within grace period, Kubernetes sends a SIGKILL signal to foecibly kill the container.</p><p>If you define:</p><pre>lifecycle:<br>  preStop:<br>    exec:<br>      command:<br>        - /bin/sh<br>        - -c<br>        - &quot;sleep 5&quot;</pre><p>the preStop hook runs before Kubernetes terminates the container.</p><p>Conceptually:</p><pre>Pod termination requested<br>        │<br>        ▼<br>Termination grace period starts<br>        │<br>        ▼<br>preStop hook<br>   sleep 5<br>        │<br>        ▼<br>Container receives termination signal (SIGTERM)<br>        │<br>        ▼<br>Application shuts down<br>        │<br>        ▼<br>Grace period expires<br>        │<br>        ▼<br>Container is forcefully terminated if still running (SIGKILL)</pre><p>The important point is that <strong>the </strong><strong>preStop hook consumes time from the termination grace period</strong>.</p><p>So with:</p><pre>terminationGracePeriodSeconds: 30</pre><p>and:</p><pre>preStop:<br>  sleep 5</pre><p>you should not think of this as:</p><pre>5 seconds preStop + 30 seconds termination</pre><p>It is approximately:</p><pre>30 seconds total termination grace period<br> ├── preStop: 5 seconds<br> └── remaining time for graceful shutdown</pre><p>The application should therefore be designed to shut down within the available grace period.</p><h3>12. A Practical Liveness Example</h3><p>Now let’s make the liveness probe fail intentionally.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: probe-demo<br>  labels:<br>    app: probe-demo</pre><pre>spec:<br>  containers:<br>    - name: app<br>      image: nginx:1.27</pre><pre>      command:<br>        - sh<br>        - -c<br>        - |<br>          touch /liveness-probe-path</pre><pre>          (sleep 30 &amp;&amp; rm /liveness-probe-path) &amp;</pre><pre>          exec nginx -g &#39;daemon off;&#39;</pre><pre>      startupProbe:<br>        httpGet:<br>          path: /<br>          port: 80<br>        periodSeconds: 5<br>        failureThreshold: 10</pre><pre>      livenessProbe:<br>        exec:<br>          command:<br>            - cat<br>            - /liveness-probe-path<br>        periodSeconds: 5<br>        initialDelaySeconds: 5<br>        failureThreshold: 2</pre><pre>      readinessProbe:<br>        httpGet:<br>          path: /<br>          port: 80<br>        timeoutSeconds: 2<br>        failureThreshold: 3<br>        periodSeconds: 5</pre><p>The important part is:</p><pre>touch /liveness-probe-path</pre><pre>(sleep 30 &amp;&amp; rm /liveness-probe-path) &amp;</pre><p>Initially:</p><pre>/liveness-probe-path exists<br>        ↓<br>cat succeeds<br>        ↓<br>Liveness = SUCCESS</pre><p>After approximately 30 seconds:</p><pre>/liveness-probe-path removed<br>        ↓<br>cat fails<br>        ↓<br>Liveness = FAIL</pre><p>Because:</p><pre>failureThreshold: 2<br>periodSeconds: 5</pre><p>two consecutive failed checks are required before Kubernetes restarts the container.</p><p>Meanwhile, the readiness probe is checking:</p><pre>httpGet:<br>  path: /<br>  port: 80</pre><p>Nginx continues serving HTTP, so readiness can remain successful.</p><p>This demonstrates an important concept:</p><blockquote><strong><em>Liveness and readiness are independent.</em></strong></blockquote><p>A container can be:</p><pre>Liveness:  FAIL<br>Readiness: SUCCESS</pre><p>for a period of time before Kubernetes acts on the repeated liveness failures.</p><h3>Think about probes this way:</h3><pre>Container<br>                     │<br>                     ▼<br>              ┌─────────────┐<br>              │ Startup     │<br>              │ &quot;Started?&quot;  │<br>              └──────┬──────┘<br>                     │<br>                  SUCCESS<br>                     │<br>             ┌───────┴────────┐<br>             ▼                ▼<br>      ┌─────────────┐  ┌─────────────┐<br>      │ Readiness   │  │ Liveness    │<br>      │ &quot;Traffic?&quot;  │  │ &quot;Healthy?&quot;  │<br>      └──────┬──────┘  └──────┬──────┘<br>             │                │<br>          FAIL               FAIL<br>             │                │<br>             ▼                ▼<br>       Remove traffic     Restart container</pre><p>And the probe mechanisms are simply <strong>how Kubernetes asks the question</strong>:</p><pre>HTTP GET<br>TCP Socket<br>Exec<br>gRPC</pre><h3>Final Takeaway</h3><p>For GKE workloads, don’t treat all probes as the same thing.</p><p><strong>Startup probe</strong> protects slow or unpredictable starting applications.</p><p><strong>Readiness probe</strong> controls whether the pod should receive traffic.</p><p><strong>Liveness probe</strong> determines whether the container needs to be restarted.</p><p>And the actual health check can be implemented using:</p><pre>HTTP GET<br>TCP Socket<br>Exec<br>gRPC</pre><p>Finally, Kubernetes pod lifecycle settings such as:</p><pre>terminationGracePeriodSeconds: 30</pre><p>and:</p><pre>lifecycle:<br>  preStop:<br>    ...</pre><p>control what happens when a container is being terminated.</p><p>A simple way to remember the entire lifecycle is:</p><pre>INIT container<br>  ↓<br>STARTUP probe checks<br>  ↓<br>READY ────────────────┐<br>  ↓                   │<br>SERVING (readiness)   │<br>  ↓                   │<br>LIVENESS ── FAIL ──→ RESTART<br>  │<br>  └── Pod termination<br>          ↓<br>       preStop<br>          ↓<br>    Graceful shutdown<br>          ↓<br>       Terminate</pre><p>Once this execution flow is clear, configuring Kubernetes probes becomes much easier because you’re no longer asking <em>“Which probe should I use?”</em> — you’re asking the more useful question:</p><blockquote><strong><em>“What state of my application am I trying to detect?”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42bb99cc25e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Topology Spread Constraints vs Pod Anti-Affinity for scheduling Singleton Workloads in GKE]]></title>
            <link>https://medium.com/@rajagup05/topology-spread-constraints-vs-pod-anti-affinity-for-scheduling-singleton-workloads-in-gke-9b9acea1f038?source=rss-b7e087bd8431------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b9acea1f038</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Raja Gupta ]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 02:14:36 GMT</pubDate>
            <atom:updated>2026-08-26T02:14:36.034Z</atom:updated>
            <content:encoded><![CDATA[<p>When running applications on Google Kubernetes Engine (GKE), a common requirement is:</p><blockquote><strong><em>Run only one replica of an application, but when that pod is replaced during a deployment, make sure the new pod is not scheduled onto the same node as the previous pod.</em></strong></blockquote><p>At first, this sounds like a simple scheduling requirement. However, there are a couple of Kubernetes scheduling mechanisms that can be used to achieve it:</p><ul><li><strong>Pod anti-affinity</strong></li><li><strong>Topology spread constraints</strong></li></ul><p>Both can influence where a pod is scheduled, but they behave differently and are designed for slightly different purposes.</p><p>This article explains how they behave for <strong>singleton workloads (</strong><strong>replicas: 1)</strong>, and how to configure them in GKE.</p><h3>The Requirement</h3><p>Imagine we have a Deployment:</p><pre>spec:<br>  replicas: 1</pre><p>At any given time, we want only one application pod running.</p><p>Now imagine a rolling deployment.</p><p>The existing pod is running on:</p><pre>node-1</pre><p>A new version of the application needs to be deployed.</p><p>The requirement is:</p><pre>Before:<br>node-1<br>  └── demo-app-v1</pre><pre>During rollout:<br>node-1<br>  └── demo-app-v1</pre><pre>node-2<br>  └── demo-app-v2</pre><pre>After:<br>node-2<br>  └── demo-app-v2</pre><p>The important part is that the new pod should <strong>not</strong> be placed on node-1 while the old pod is still running.</p><p>This is particularly useful when the goal is to make the replacement pod land on a different node, for example to reduce the impact of a node-level failure during a rollout.</p><h3>Why replicas: 1 Makes This Interesting</h3><p>With a normal Deployment using:</p><pre>replicas: 1</pre><p>you might expect Kubernetes to simply terminate the old pod and create the new one.</p><p>However, that depends on the Deployment strategy.</p><p>If we use:</p><pre>strategy:<br>  type: RollingUpdate<br>  rollingUpdate:<br>    maxSurge: 1<br>    maxUnavailable: 0</pre><p>Kubernetes can temporarily create an additional pod during the rollout.</p><p>Conceptually:</p><pre>Desired replicas = 1</pre><pre>Old pod:<br>  demo-app-v1</pre><pre>New pod:<br>  demo-app-v2</pre><pre>Temporary total = 2</pre><p>This temporary overlap is important.</p><p>It gives the scheduler an opportunity to make a placement decision for the new pod <strong>while the old pod is still running</strong>.</p><p>Without that overlap, there may be no existing pod for the scheduler to consider when placing the replacement.</p><h3>Option 1: Pod Anti-Affinity</h3><p>Pod anti-affinity is the more direct solution when the requirement is:</p><blockquote><strong><em>Do not schedule this pod on the same node as another matching pod.</em></strong></blockquote><p>For our example, we can use:</p><pre>affinity:<br>  podAntiAffinity:<br>    requiredDuringSchedulingIgnoredDuringExecution:<br>      - labelSelector:<br>          matchExpressions:<br>            - key: app<br>              operator: In<br>              values:<br>                - demo<br>            - key: env<br>              operator: In<br>              values:<br>                - st<br>        topologyKey: kubernetes.io/hostname</pre><p>The important part is:</p><pre>topologyKey: kubernetes.io/hostname</pre><p>kubernetes.io/hostname represents the node topology domain.</p><p>In practical terms, this says:</p><blockquote><em>Find pods matching these labels and do not schedule this pod into the same hostname/topology domain.</em></blockquote><p>Because the rule uses:</p><pre>requiredDuringSchedulingIgnoredDuringExecution</pre><p>the requirement is hard during scheduling.</p><p>If the scheduler cannot find a node satisfying the anti-affinity rule, the pod remains unscheduled rather than ignoring the rule.</p><h3>How Anti-Affinity Behaves</h3><p>Suppose the old pod is running here:</p><pre>node-1<br>└── demo-app-v1</pre><p>And the new pod has the required anti-affinity rule.</p><p>The scheduler evaluates:</p><pre>node-1<br>  demo-app-v1<br>  ❌ new pod cannot be scheduled here</pre><pre>node-2<br>  no matching pod<br>  ✅ eligible</pre><pre>node-3<br>  no matching pod<br>  ✅ eligible</pre><p>The new pod can therefore be scheduled onto another node.</p><p>After the new pod becomes ready, the old pod can be terminated.</p><p>The final state becomes:</p><pre>node-1<br>  └── empty</pre><pre>node-2<br>  └── demo-app-v2</pre><h3>Why requiredDuringSchedulingIgnoredDuringExecution?</h3><p>There are two common forms of pod anti-affinity:</p><pre>requiredDuringSchedulingIgnoredDuringExecution</pre><p>and:</p><pre>preferredDuringSchedulingIgnoredDuringExecution</pre><p>The difference is important.</p><h3>Required</h3><pre>requiredDuringSchedulingIgnoredDuringExecution</pre><p>means:</p><blockquote><em>This rule must be satisfied when scheduling the pod.</em></blockquote><p>If no suitable node exists, the pod remains Pending.</p><h3>Preferred</h3><pre>preferredDuringSchedulingIgnoredDuringExecution</pre><p>means:</p><blockquote><em>Try to satisfy this rule, but it is okay to violate it if necessary.</em></blockquote><p>For a strict requirement such as:</p><blockquote><em>“The replacement pod must not run on the same node”</em></blockquote><p>requiredDuringSchedulingIgnoredDuringExecution is generally the appropriate choice.</p><h3>Option 2: Topology Spread Constraints</h3><p>Kubernetes also provides:</p><pre>topologySpreadConstraints</pre><p>Topology spread constraints are primarily designed to <strong>spread pods across topology domains</strong>.</p><p>For example, you can spread workloads across:</p><ul><li>nodes</li><li>zones</li><li>regions</li><li>other topology domains</li></ul><p>The important distinction is that topology spread is fundamentally a <strong>distribution/balancing mechanism</strong>, whereas required pod anti-affinity is a <strong>hard separation rule</strong>.</p><p>For our singleton workload, however, topology spread can also be useful.</p><h3>Topology Spread with a Singleton Workload</h3><p>Consider:</p><pre>topologySpreadConstraints:<br>  - maxSkew: 1<br>    topologyKey: kubernetes.io/hostname<br>    whenUnsatisfiable: DoNotSchedule<br>    labelSelector:<br>      matchLabels:<br>        app: demo<br>        env: st</pre><p>The key settings are:</p><pre>maxSkew: 1<br>topologyKey: kubernetes.io/hostname<br>whenUnsatisfiable: DoNotSchedule</pre><p>Let’s understand what they mean.</p><h3>topologyKey</h3><pre>topologyKey: kubernetes.io/hostname</pre><p>This tells Kubernetes that the topology domains are nodes.</p><p>For example:</p><pre>node-1<br>node-2<br>node-3</pre><p>If instead we use:</p><pre>topologyKey: topology.kubernetes.io/zone</pre><p>then the domains become zones:</p><pre>us-central1-a<br>us-central1-b<br>us-central1-c</pre><p>This distinction is very important.</p><h3>maxSkew</h3><p>maxSkew defines how uneven the distribution is allowed to become.</p><p>For example:</p><pre>maxSkew: 1</pre><p>means Kubernetes should not allow the pod counts between eligible topology domains to become more than one apart, subject to the topology-spread scheduling rules.</p><p>Suppose we have:</p><pre>node-1: 1 pod<br>node-2: 0 pods<br>node-3: 0 pods</pre><p>This is a valid distribution for a single pod.</p><p>Now imagine the scheduler is considering putting a second matching pod on node-1:</p><pre>node-1: 2 pods<br>node-2: 0 pods<br>node-3: 0 pods</pre><p>The distribution becomes too skewed for:</p><pre>maxSkew: 1</pre><p>Therefore, with suitable eligible nodes and DoNotSchedule, the scheduler can reject node-1 and consider another node.</p><h3>whenUnsatisfiable: DoNotSchedule</h3><p>This is another critical setting:</p><pre>whenUnsatisfiable: DoNotSchedule</pre><p>It means:</p><blockquote><em>If scheduling the pod would violate the topology spread constraint, do not schedule it on that node.</em></blockquote><p>The alternative is:</p><pre>whenUnsatisfiable: ScheduleAnyway</pre><p>which tells the scheduler to make a best effort to spread the pods but allow scheduling even when the constraint cannot be satisfied.</p><p>For a strict requirement, DoNotSchedule is the important setting.</p><h3>Complete Deployment Example</h3><p>Here is the Deployment configuration for the singleton workload:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: demo-app<br>  labels:<br>    app: demo<br>    env: st</pre><pre>spec:<br>  replicas: 1</pre><pre>  strategy:<br>    type: RollingUpdate<br>    rollingUpdate:<br>      maxSurge: 1<br>      maxUnavailable: 0</pre><pre>  selector:<br>    matchLabels:<br>      app: demo<br>      env: st</pre><pre>  template:<br>    metadata:<br>      labels:<br>        app: demo<br>        env: st</pre><pre>    spec:<br>      topologySpreadConstraints:</pre><pre>        # Spread across zones<br>        - maxSkew: 1<br>          topologyKey: topology.kubernetes.io/zone<br>          whenUnsatisfiable: DoNotSchedule<br>          labelSelector:<br>            matchLabels:<br>              app: demo<br>              env: st</pre><pre>        # Spread across nodes<br>        - maxSkew: 1<br>          topologyKey: kubernetes.io/hostname<br>          whenUnsatisfiable: DoNotSchedule<br>          labelSelector:<br>            matchLabels:<br>              app: demo<br>              env: st</pre><pre>      containers:<br>        - name: app-container<br>          image: nginx:alpine</pre><pre>          ports:<br>            - containerPort: 80</pre><pre>          resources:<br>            requests:<br>              cpu: 100m<br>              memory: 128Mi</pre><pre>            limits:<br>              cpu: 200m<br>              memory: 256Mi</pre><p>There are actually two independent constraints here.</p><h3>Zone-level spreading</h3><pre>topologyKey: topology.kubernetes.io/zone</pre><p>This attempts to distribute matching pods across zones.</p><h3>Node-level spreading</h3><pre>topologyKey: kubernetes.io/hostname</pre><p>This attempts to distribute matching pods across nodes.</p><p>For the singleton rollout scenario, the hostname-level constraint is the one directly related to:</p><blockquote><em>“Don’t put the replacement pod on the same node.”</em></blockquote><h3>Topology Spread vs Pod Anti-Affinity</h3><p>This is where the distinction becomes important.</p><p>So if the requirement is specifically:</p><blockquote><em>“The new singleton pod must not run on the same node as the old pod during a rollout.”</em></blockquote><p>I would generally start with <strong>required pod anti-affinity</strong>.</p><p>If the broader requirement is:</p><blockquote><em>“Keep matching replicas evenly distributed across nodes/zones.”</em></blockquote><p>then <strong>topology spread constraints</strong> are a better conceptual fit.</p><h3>An Important Detail About Singleton Workloads</h3><p>There is a subtle point that is easy to miss.</p><p>A topology spread constraint does <strong>not</strong> mean:</p><blockquote><em>“Always choose a different node.”</em></blockquote><p>It means:</p><blockquote><em>“Maintain the requested distribution across eligible topology domains according to the spread rules.”</em></blockquote><p>For example, if the cluster only has one eligible node, Kubernetes cannot magically move the pod to another node.</p><p>Similarly, if node selectors, node affinity, taints/tolerations, resource availability, or other scheduling constraints leave only one eligible topology domain, the scheduler may not be able to satisfy the desired separation.</p><p>With:</p><pre>whenUnsatisfiable: DoNotSchedule</pre><p>the pod can remain Pending instead.</p><p>This is why you should always consider the available node topology when designing these rules.</p><h3>Why maxSurge: 1 Matters</h3><p>This part of the Deployment is particularly important for the rollout scenario:</p><pre>rollingUpdate:<br>  maxSurge: 1<br>  maxUnavailable: 0</pre><p>It allows one additional pod above the desired replica count.</p><p>For:</p><pre>replicas: 1</pre><p>the rollout can temporarily have:</p><pre>1 old pod + 1 new pod</pre><p>instead of immediately removing the old pod.</p><p>That gives the scheduler the opportunity to evaluate the new pod while the old pod still exists.</p><p>The sequence can therefore look like:</p><pre>Step 1 - old pod running</pre><pre>node-1<br>└── demo-app-v1</pre><pre>Step 2 - rollout starts</pre><pre>node-1<br>└── demo-app-v1</pre><pre>node-2<br>└── demo-app-v2<br></pre><pre>Step 3 - new pod becomes Ready</pre><pre>node-1<br>└── demo-app-v1</pre><pre>node-2<br>└── demo-app-v2<br></pre><pre>Step 4 - old pod terminated</pre><pre>node-2<br>└── demo-app-v2</pre><p>This is especially useful when you want the replacement workload to be moved away from the node hosting the previous version.</p><h3>One More Consideration: Zone and Node Constraints Together</h3><p>The example uses both:</p><pre>topology.kubernetes.io/zone</pre><p>and:</p><pre>kubernetes.io/hostname</pre><p>This can be useful, but it also makes scheduling more restrictive.</p><p>For a singleton workload, ask what the actual availability requirement is.</p><p>If the only requirement is:</p><blockquote><em>New pod must not use the same node.</em></blockquote><p>Then node-level anti-affinity may be sufficient.</p><p>If the requirement is:</p><blockquote><em>New pod should move to another node and preferably another zone.</em></blockquote><p>Then combining node and zone topology constraints can make sense.</p><p>However, always verify that your GKE cluster has enough eligible nodes and zones to satisfy the constraints. Otherwise, a strict DoNotSchedule rule can leave the replacement pod Pending.</p><h3>How to Troubleshoot When the Pod Stays Pending</h3><p>If the new pod is not scheduling, start with:</p><pre>kubectl get pods -o wide</pre><p>Then:</p><pre>kubectl describe pod &lt;pod-name&gt;</pre><p>Look at the <strong>Events</strong> section.</p><p>You may see scheduling messages indicating that nodes were excluded because of:</p><ul><li>pod anti-affinity</li><li>topology spread constraints</li><li>insufficient CPU or memory</li><li>taints</li><li>node affinity</li><li>node selectors</li><li>other scheduling constraints</li></ul><p>Also check the nodes:</p><pre>kubectl get nodes -L topology.kubernetes.io/zone</pre><p>This helps you understand which nodes belong to which zones.</p><p>You can also inspect the Deployment:</p><pre>kubectl describe deployment demo-app</pre><p>During a rollout, it is particularly useful to check where both the old and new pods are running:</p><pre>kubectl get pods -l app=demo,env=st -o wide</pre><p>The -o wide output lets you see the node assigned to each pod.</p><h3>Final Takeaway</h3><p>For singleton workloads, <strong>pod anti-affinity and topology spread constraints can look similar but solve different problems</strong>.</p><p><strong>Pod anti-affinity</strong> answers:</p><blockquote><em>“Where should this pod NOT be scheduled?”</em></blockquote><p><strong>Topology spread constraints</strong> answer:</p><blockquote><em>“How should these pods be distributed across topology domains?”</em></blockquote><p>For the specific requirement of keeping a new singleton pod away from the node hosting the previous pod during a rolling deployment, <strong>required pod anti-affinity with </strong><strong>kubernetes.io/hostname is the most direct expression of the requirement</strong>.</p><p>Topology spread constraints can also achieve node separation in the appropriate topology configuration, but their purpose is broader: controlling the distribution of matching pods.</p><p>The other important piece is the Deployment strategy:</p><pre>maxSurge: 1<br>maxUnavailable: 0</pre><p>This allows the new pod to exist while the old pod is still running, giving Kubernetes’ scheduler the opportunity to make a different placement decision.</p><p>In short:</p><pre>Singleton workload<br>       │<br>       ├── Need strict &quot;different node&quot;?<br>       │        └── Pod Anti-Affinity<br>       │<br>       └── Need controlled distribution?<br>                └── Topology Spread Constraints</pre><p>Understanding this distinction becomes especially important in GKE when designing deployment strategies for workloads where <strong>node-level failure isolation and controlled pod replacement</strong> matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b9acea1f038" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>