<?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 Muhaned Yahya on Medium]]></title>
        <description><![CDATA[Stories by Muhaned Yahya on Medium]]></description>
        <link>https://medium.com/@yahya.muhaned?source=rss-a5805f1335fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fWH08MeynYyZzUJa3eZIlg.jpeg</url>
            <title>Stories by Muhaned Yahya on Medium</title>
            <link>https://medium.com/@yahya.muhaned?source=rss-a5805f1335fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:02:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yahya.muhaned/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[Architecting Production-Grade .NET Microservices on Kubernetes (Part 1)]]></title>
            <link>https://medium.com/@yahya.muhaned/architecting-production-grade-net-microservices-on-kubernetes-eb829c2084b3?source=rss-a5805f1335fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb829c2084b3</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Muhaned Yahya]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 19:15:52 GMT</pubDate>
            <atom:updated>2026-10-28T19:26:58.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWND_6V3fY4hLScXx2kcwA.png" /></figure><p>Running a handful of .NET microservices on Kubernetes is straightforward. But when your ecosystem scales past <strong>30+ applications</strong>, standard development habits break down. Local paradigms like launchSettings.json, default ports, and ad-hoc configuration files no longer cut it.</p><p>In this first part of our series on managing .NET at scale on Kubernetes, we will break down the production-grade patterns required to keep your pods secure, resilient, and performant — covering everything from container hardening and secret management to resource tuning and Horizontal Pod Autoscaling (HPA).</p><h3>1. Ditch launchSettings.json: Standardized Configuration &amp; Secrets</h3><p>In local development, launchSettings.json and user secrets rule the day. In production Kubernetes, your application must be environment-agnostic.</p><ul><li><strong>Single Source of Truth:</strong> Your .NET application should look for a standardized configuration file (e.g., appsettings.json) mounted dynamically by an external secret provider (such as HashiCorp Vault, External Secrets Operator, or Sealed Secrets).</li><li><strong>Git Ignore Discipline:</strong> To prevent credential leaks, always add all environment-specific appsettings.*.json files (except the base appsettings.json) to your .gitignore and .dockerignore files. Production secrets should <em>never</em> touch Git history.</li><li><strong>Dynamic Reloads with Reloader:</strong> When you rotate database passwords or API keys in your secret store, your pods need to pick up the changes without a manual rollout. Using an operator like <strong>Reloader</strong> watches your Kubernetes Secrets and triggers a rolling restart of the deployment automatically whenever the underlying secret changes.</li></ul><h3>2. Hardening the Dockerfile</h3><p>Security best practices dictate that containers should never run as root, and binding to privileged ports (like port 80) should be avoided.</p><p>Here is a secure, multi-stage production Dockerfile optimized for .NET 8, running as a non-root user on a non-standard port (8080):</p><pre># Base runtime image<br>FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base<br>WORKDIR /app<br>EXPOSE 8080<br><br># Build stage<br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build<br>ARG BUILD_CONFIGURATION=Release<br>WORKDIR /src<br><br># Copy project files and restore dependencies<br>COPY [&quot;Shop.Api/Shop.Api.csproj&quot;, &quot;Shop.Api/&quot;]<br>RUN dotnet restore &quot;Shop.Api/Shop.Api.csproj&quot;<br><br># Copy source code and publish<br>COPY . .<br>RUN dotnet publish &quot;Shop.Api/Shop.Api.csproj&quot; -c &quot;$BUILD_CONFIGURATION&quot; -o /app/publish<br><br># Final secure runtime image<br>FROM base AS final<br>WORKDIR /app<br><br># Run as a non-root user for security compliance<br>RUN useradd -u 10001 -ms /bin/bash appuser<br>USER 10001<br><br>COPY --from=publish /app/publish .<br><br># Bind to non-privileged port 8080<br>ENV ASPNETCORE_URLS=http://+:8080<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;Shop.Api.dll&quot;]</pre><h3>3. Kubernetes Deployment &amp; Resource Engineering</h3><p>When deploying your microservice manifest, environmental variables, probes, and resource allocations require careful tuning to handle .NET’s runtime behavior.</p><p><strong>Environment &amp; Health Probes</strong></p><p>Environment-specific variables (like timezone or application name) belong cleanly inside your Helm values or deployment YAML:</p><pre>env:<br>  - name: TZ<br>    value: &quot;Europe/London&quot;<br>  - name: ASPNETCORE_ENVIRONMENT<br>    value: &quot;Production&quot;<br>  - name: API_NAME<br>    value: &quot;ShopService&quot;</pre><p>For health checks, expose dedicated endpoints (/healthz and /healthz/ready) so Kubernetes can accurately route traffic and manage pod lifecycles without false positives during heavy database connection phases.</p><p><strong>The Golden Rule for .NET Resources: Memory Requests Equal Limits</strong></p><ul><li><strong>Memory (</strong><strong>requests == limits):</strong> For .NET applications, set your memory requests and limits to the exact same value. If limits are higher than requests, the .NET Garbage Collector (GC) may miscalculate the available system memory, leading to unexpected memory bloat, aggressive collection spikes, or sudden Out-Of-Memory (OOM) kills when traffic surges.</li><li><strong>CPU Requests &amp; Limits:</strong> Set your CPU requests high enough to ensure the application can open database connections and handle JIT compilation smoothly during startup. Give CPU limits healthy headroom above requests to prevent CPU throttling during request spikes, which can otherwise cause latency spikes and timeout cascades.</li></ul><h3>4. Tailoring the Horizontal Pod Autoscaler (HPA) for .NET</h3><p>When managing high-density .NET microservices, scaling reactively is crucial. Because we pin memory requests equal to limits to protect the GC, memory utilization tracks closely per pod rather than scaling dynamically with replica counts. Therefore, <strong>CPU should drive your primary scaling metric</strong>, with memory acting as a high-watermark safety backstop.</p><p>Here is how a production HPA manifest looks in practice:</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: shop-api-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: shop-api<br>  minReplicas: 3<br>  maxReplicas: 10<br>  metrics:<br>    # Primary trigger: Scale out early on CPU utilization before saturation hits<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target:<br>          type: Utilization<br>          averageUtilization: 60<br>    # Secondary safety backstop: Memory guard<br>    - type: Resource<br>      resource:<br>        name: memory<br>        target:<br>          type: Utilization<br>          averageUtilization: 85<br>  behavior:<br>    scaleUp:<br>      stabilizationWindowSeconds: 15<br>      policies:<br>        - type: Pods<br>          value: 2<br>          periodSeconds: 30<br>    scaleDown:<br>      stabilizationWindowSeconds: 300<br>      policies:<br>        - type: Pods<br>          value: 1<br>          periodSeconds: 60</pre><ul><li><strong>Early CPU Scaling (60%):</strong> Scaling out at 60% average CPU utilization gives the cluster plenty of breathing room to absorb sudden traffic bursts before the .NET JIT or thread pool gets overwhelmed.</li><li><strong>Asymmetric Behavior:</strong> Scale up rapidly (15s stabilization window) to absorb sudden traffic spikes, but scale down conservatively (300s window) to prevent thrashing and keep active backend database sessions stable.</li></ul><p>What’s Next?</p><p>By locking down your multi-stage Dockerfile, standardizing your configuration through secret providers, setting precise resource boundaries, and implementing a robust HPA, your .NET microservices are now production-ready on Kubernetes.</p><p>However, when scaling out to dozens of pods interacting with PostgreSQL, you will inevitably run into database connection exhaustion. In <strong>Part 2</strong>, we will dive straight into how to solve this using <strong>PgBouncer in transaction mode</strong>, navigating .NET connection pooling quirks, and balancing pool sizes safely. Stay tuned!</p><p>#<strong>Kubernetes #Dotnet #Microservices #DevOps</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb829c2084b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Merge: Declarative Promotion Stages with Akuity Kargo and Helm]]></title>
            <link>https://medium.com/@yahya.muhaned/beyond-the-merge-declarative-promotion-stages-with-akuity-kargo-and-helm-54742178eed0?source=rss-a5805f1335fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/54742178eed0</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[promotionstages]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kargo]]></category>
            <dc:creator><![CDATA[Muhaned Yahya]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 17:16:15 GMT</pubDate>
            <atom:updated>2026-07-18T17:16:15.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6Crl1iXueOLZ77r3.png" /><figcaption>kargo logo</figcaption></figure><p>The biggest challenge in modern GitOps isn’t getting code into your development cluster — it’s managing the promotional lifecycle that follows. While continuous integration excels at building images and validating initial pull requests, it frequently stumbles when propagating those exact same validated artifacts across a tiered promotion path. Moving an application configuration safely from dev to preprod, and ultimately to production, shouldn’t require reinventing the wheel for every environment boundary.</p><p>Traditionally, this required engineering teams to maintain intricate custom workflows packed with automated find-and-replace routines, file manipulations, and multi-layered repository synchronizations. The industry needed a native way to express the lifecycle of a change across environments without treating every single stage transition as an isolated commit event</p><p>Enter <strong>Akuity Kargo</strong>, an open-source tool designed to orchestrate declarative application promotions across environments. In this post, we will look at how Kargo works under the hood and how we can fully automate its setup across dozens of services using a unified Helm architecture.</p><h3>The Core Concepts of Kargo</h3><p>Kargo does not replace your GitOps controller (like ArgoCD); it sits on top of it. It orchestrates the lifecycle by formalizing three core Custom Resource Definitions (CRDs):</p><ol><li><strong>Warehouse:</strong> The entry point. A Warehouse watches your upstream resources — like container registries or Helm repositories — and bundles updates into unique, immutable units of change called <strong>Freight</strong>.</li><li><strong>Stage:</strong> A distinct environment in your lifecycle (e.g., development, staging, production). A Stage consumes Freight, executes custom verification tasks, and passes it along.</li><li><strong>Promotion:</strong> The actual action resource that takes a specific piece of Freight and applies it to a target Stage, changing the Git state or triggering an upgrade.</li></ol><h3>Eliminating the “Rebuild and Pray” Anti-Pattern</h3><p>In traditional CI/CD setups, moving code across environments often means compiling and building fresh container images at every gate, or maintaining separate, complex pipeline files for each environment. You build an image for dev, run tests, and then trigger a completely separate pipeline job that compiles the code <em>again</em> to tag it for staging or production. This introduces subtle differences in dependencies, compile-time environments, and configurations. It&#39;s an operational anti-pattern.</p><p>Kargo radically simplifies your pipeline complexity by establishing a clean separation of concerns:</p><ul><li><strong>CI builds it once:</strong> Your CI pipeline does one job — it builds, tests, and pushes a single immutable container image when code lands on your main branch.</li><li><strong>Kargo promotes it safely:</strong> Instead of writing custom runner logic or multi-stage pipelines to manage state transitions, Kargo captures that exact tested image as a distinct unit of <strong>Freight</strong>.</li><li><strong>Native GitOps Writing:</strong> When you click “Promote” (or automate it), Kargo handles the raw work of committing directly to your GitOps infrastructure repository. The exact same image artifact that passed validation in dev is seamlessly injected into staging and production manifests without ever rebuilding the source or needing access tokens inside your app runner.</li></ul><p>By offloading the promotion state logic to Kargo CRDs, your applications’ internal pipeline files drop from hundreds of lines of brittle bash code down to a single, straightforward container build step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C46dOC9XO5keeN_M.png" /><figcaption>kargo Image Updater pattern</figcaption></figure><h3>The Challenge: Boilerplate at Scale</h3><p>While Kargo provides incredible control over the lifecycle graph, defining these components manually via raw YAML for 30+ microservices quickly becomes tedious. Each service requires its own Kargo Project, a unique Warehouse tracking its image repository, several Stages tracking different folders or branches, and specialized PromotionMechanisms.</p><p>To eliminate this manual friction, I built an open-source Helm chart: <a href="https://github.com/MuhanedYahya/kargo-project-chart"><strong><em>kargo-project-chart</em></strong></a>. This chart acts as a declarative engine that abstracts Kargo&#39;s primitives into simple, structured configuration blocks.</p><p>Let’s look at how we can implement this pattern to bootstrap a complete multi-stage promotion pipeline out of the box.</p><h3>Automating Pipelines with kargo-project-chart</h3><p>By wrapping Kargo manifests inside a structured Helm architecture, we can define an entire application’s promotion graph in a single values.yaml file.</p><p>The structure organizes your Warehouses and Stages down into clean, repeatable patterns:</p><pre># ──────────────────────────────────────────────<br># Kargo Project<br># The project name becomes the Kargo namespace for all generated resources.<br># ──────────────────────────────────────────────<br>project: &quot;retail&quot;<br><br># ──────────────────────────────────────────────<br># Secret Store (External Secrets Operator)<br># ──────────────────────────────────────────────<br>secretStore:<br>  name: vault-backend<br>  kind: ClusterSecretStore<br><br># ──────────────────────────────────────────────<br># Credentials<br># ExternalSecrets pull from Vault and create K8s Secrets<br># that Kargo uses to authenticate with git and image registries.<br># ──────────────────────────────────────────────<br>credentials:<br>  git:<br>    vaultPath: &quot;platform/kargo/retail/git-credentials&quot;<br>    refreshInterval: &quot;1h&quot;<br><br>  registry:<br>    vaultPath: &quot;platform/kargo/retail/ghcr-credentials&quot;<br>    refreshInterval: &quot;1h&quot;<br><br>  webhook:<br>    enabled: true<br>    vaultPath: &quot;platform/kargo/retail/webhook-auth&quot;   # must contain a `secret` key<br>    refreshInterval: &quot;1h&quot;<br><br># ──────────────────────────────────────────────<br># Webhook Receivers<br># ──────────────────────────────────────────────<br>webhookReceivers:<br>  - name: dockerhub-receiver<br>    dockerhub:<br>      secretRef:<br>        name: kargo-webhook-auth<br><br># ──────────────────────────────────────────────<br># Git Repository<br># Required for prod stages that use PR flow (git-open-pr + git-wait-for-pr).<br># ──────────────────────────────────────────────<br>gitRepo:<br>  url: &quot;https://github.com/my-org/retail-gitops.git&quot;<br>  targetBranch: &quot;main&quot;<br>  provider: &quot;github&quot;<br><br># ──────────────────────────────────────────────<br># Values Path Template<br># Controls the `valuesPath` var the chart passes to every Stage&#39;s promotion task.<br># Supported tokens: {env}, {project}, {service}, {valuesDir}.<br>#   - valuesPathTemplate is used for dev/test and preprod/prod without tenant.valuesDir.<br>#   - tenantValuesPathTemplate is used when a preprod/prod tenant sets valuesDir.<br># Per-service literal override still wins: services[].stages.{env}.valuesPath.<br># ──────────────────────────────────────────────<br>valuesPathTemplate: &quot;envs/{env}/{project}/{service}/values.yaml&quot;<br>tenantValuesPathTemplate: &quot;envs/{valuesDir}/{service}/values.yaml&quot;<br><br># ──────────────────────────────────────────────<br># Pipeline Environments<br># Defines the promotion pipeline: dev → test → preprod → prod.<br># ──────────────────────────────────────────────<br>environments:<br>  dev:<br>    enabled: true<br>    autoPromotionEnabled: true # Automatically promote fresh images from the Warehouse<br>    promotionTask:<br>      name: gitops-direct-push<br>      kind: ClusterPromotionTask<br><br>  test:<br>    enabled: true<br>    autoPromotionEnabled: true # Automatically catch up when dev passes green<br>    promotionTask:<br>      name: gitops-direct-push<br>      kind: ClusterPromotionTask<br><br>  preprod:<br>    enabled: true<br>    autoPromotionEnabled: false # Requires manual gate/approval to promote to preprod<br>    promotionTask:<br>      name: gitops-direct-push<br>      kind: ClusterPromotionTask<br>    # tenants: one preprod Stage is generated per entry, all sourcing from the<br>    # nearest enabled upstream (test → dev → direct).<br>    tenants:<br>      - nameSuffix: preprod<br><br>  prod:<br>    enabled: true<br>    autoPromotionEnabled: false # Strict manual gate for production release<br>    promotionTask:<br>      name: gitops-pr-promote    # Switches to a strict Pull Request workflow for safety<br>      kind: ClusterPromotionTask<br>    # tenants: one prod Stage is generated per entry, sourcing from the<br>    # preprod tenant at the same index (prod[i] → preprod[i mod N]).<br>    tenants:<br>      - nameSuffix: prod<br><br># ──────────────────────────────────────────────<br># Services<br># Generates 1 Warehouse + 4 Stages (dev, test, preprod, prod) per service.<br># ──────────────────────────────────────────────<br>services:<br><br>  - name: web-storefront<br>    imageRef: ghcr.io/my-org/web-storefront<br>    allowTags: &#39;^[a-f0-9]{7,8}$&#39;<br>    discoveryLimit: 5<br>    imageSelectionStrategy: NewestBuild<br><br>  - name: checkout-backend<br>    imageRef: ghcr.io/my-org/checkout-backend<br>    allowTags: &#39;^[a-f0-9]{7,8}$&#39;<br>    discoveryLimit: 5<br>    imageSelectionStrategy: NewestBuild<br><br>  - name: inventory-processor<br>    imageRef: ghcr.io/my-org/inventory-processor<br>    allowTags: &#39;^[a-f0-9]{7,8}$&#39;<br>    discoveryLimit: 5<br>    imageSelectionStrategy: NewestBuild</pre><h4>Why This Pattern Wins</h4><ul><li><strong>Explicit Lineage:</strong> Instead of relying on brittle scripts to guess which image is running where, the staging tier explicitly declares that it only accepts Freight that has cleared the development stage. Kargo guarantees that code cannot bypass your verification quality gates.</li><li><strong>Declarative Git Manipulation:</strong> Rather than building custom Jenkins or GitHub Actions jobs with raw Git write permissions, Kargo natively understands how to update image values directly inside your target environment configuration files (valueFiles).</li><li><strong>Zero-Drift Execution:</strong> By packaging this configuration inside a Helm chart, you can treat your deployment pipelines exactly like your infrastructure — versioned, auditable, and easily managed via GitOps controllers like ArgoCD.</li></ul><h4>Final Thoughts</h4><p>Adopting Kargo shifts the operational mental model from <em>managing discrete Git commits</em> to <em>managing a continuous line of Freight</em>. By introducing a unified template architecture like kargo-project-chart, platform engineering teams can easily scale this capability out to hundreds of microservices, ensuring fast, safe, and entirely declarative rollouts.</p><p>If you want to dive deeper, you can find the complete open-source implementation and start bootstrapping your own declarative pipelines today:</p><ul><li>Explore the <a href="https://github.com/MuhanedYahya/kargo-project-chart"><strong>kargo-project-chart on GitHub</strong></a> to streamline your template architecture.</li><li>Check out the official <a href="https://docs.kargo.io/"><strong>Akuity Kargo Documentation</strong></a> to learn more about advanced promotion workflows.</li></ul><p>#GitOps #Kubernetes #DevOps #ArgoCD #Kargo</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54742178eed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Manually Generating Kubeconfigs: Meet KubeUser]]></title>
            <link>https://medium.com/@yahya.muhaned/stop-manually-generating-kubeconfigs-meet-kubeuser-2f3ca87b027a?source=rss-a5805f1335fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3ca87b027a</guid>
            <category><![CDATA[user-management]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[kubernetes-rbac]]></category>
            <category><![CDATA[kubeuser]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Muhaned Yahya]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 17:53:27 GMT</pubDate>
            <atom:updated>2026-05-09T12:01:56.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmg7xfEXMzJEF74sugZP6g.png" /></figure><p>If you manage a Kubernetes cluster, you know the specific pain of onboarding a new developer or service account. The “traditional” workflow usually looks something like this: generate a private key with openssl, create a Certificate Signing Request (CSR), submit it to the cluster, approve it manually, retrieve the certificate, and finally construct a kubeconfig file by hand.</p><p>It is error-prone, tedious, and frankly, it feels like it should have been automated years ago.</p><h4>Enter <strong>KubeUser</strong>.</h4><p><a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fgithub.com%2Fopenkube-hub%2FKubeUser">KubeUser</a> is a kubernetes-native operator that turns user management into a declarative code experience. No more manual certificate juggling — just apply a YAML file, and the operator handles the rest.</p><p>In this post, we’ll look at how KubeUser solves the X.509 management headache, how it handles security, and how you can install it in minutes.. <a href="https://github.com/openkube-hub/KubeUser">Github</a></p><h4>The Problem: Kubernetes Doesn’t Have a “User” Object</h4><p>Kubernetes has ServiceAccounts for bots, but for human users, it relies on external authentication strategies. While OIDC is great for large organizations, setting it up for smaller teams or specific automated processes is often overkill. Many teams fall back on X.509 client certificates, which brings us back to the manual &quot;CSR hell&quot; mentioned above.</p><p>The Solution:</p><p>KubeUser introduces a Custom Resource Definition (CRD) called User. It follows the standard Operator pattern:</p><p>1. <strong>You define the state:</strong> Create a User YAML specifying permissions and expiration.</p><p>2. <strong>The Controller reconciles:</strong> It automatically generates a private key, submits a CSR to the Kubernetes API, and creates the necessary RBAC (RoleBindings/ClusterRoleBindings).</p><p>3. <strong>The Output:</strong> It saves the resulting certificate and a ready-to-use kubeconfig into a Kubernetes Secret.</p><p>Crucially, KubeUser relies on a <strong>Strictly Explicit Authentication Model</strong>. You must explicitly define the auth type (currently x509), ensuring that security configuration is never ambiguous</p><h3>Hands-On: Installation and Workflow</h3><p>Let’s walk through a real-world scenario.</p><h4>1. Prerequisites &amp; Installation</h4><p>KubeUser requires <strong>cert-manager</strong> to handle webhook certificates.</p><pre># Install cert-manager<br>kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.19.2/cert-manager.yaml<br># Wait for cert-manager to be ready<br>kubectl wait --for=condition=ready pod -l app=cert-manager -n cert-manager --timeout=60s</pre><p>Once that is running, you can install KubeUser via Helm.</p><pre># Add the repository<br>helm repo add kubeuser https://openkube-hub.github.io/KubeUser<br># Extract the API server address from your current kubeconfig<br>export KUBERNETES_API_SERVER=$(kubectl config view --minify -o jsonpath=&#39;{.clusters[0].cluster.server}&#39;)</pre><pre># Install the operator (creates the &#39;kubeuser&#39; namespace automatically)<br>helm install kubeuser kubeuser/kubeuser --create-namespace -n kubeuser \<br>  --set env.KUBERNETES_API_SERVER=&quot;$KUBERNETES_API_SERVER&quot;</pre><pre># Verify installation<br>kubectl get pods -n kubeuser</pre><h4><strong>2. Creating a User (“Alice”)</strong></h4><p>In this scenario, we are onboarding a senior engineer, <strong>Alice</strong>, who needs a mix of namespace-specific permissions and cluster-wide access. He requires a long-lived certificate (1 year) that auto-renews 30 days before expiration.</p><pre>apiVersion: auth.openkube.io/v1alpha1<br>kind: User<br>metadata:<br>  name: alice<br>spec:<br>  auth:<br>    type: x509<br>    ttl: 8760h          # 1 Year (Max TTL)<br>    autoRenew: true<br>    renewBefore: &quot;720h&quot; # Renew 30 days (720 hours) before expiry<br>  roles:<br>    - namespace: &quot;development&quot;<br>      existingClusterRole: &quot;admin&quot;<br>    - namespace: &quot;staging&quot;<br>      existingRole: &quot;developer&quot;<br>  clusterRoles:<br>    - existingClusterRole: &quot;view&quot;<br>    - existingClusterRole: &quot;readonly-plus&quot;</pre><p>Important: Pre-Creating Custom Roles</p><p>KubeUser binds users to roles, but it does <strong>not</strong> create the role definitions themselves. You must ensure referenced roles exist before applying the User manifest.</p><p><strong><em>Future Update:</em></strong><em> A </em><strong><em>Predefined role templates library</em></strong><em> is currently on the roadmap and will be implemented soon. This feature will allow the operator to automatically provision standard role definitions, further reducing manual setup</em></p><p><strong>In Alice’s configuration:</strong></p><p>• <strong>Existing Roles (admin, view):</strong> These are built-in Kubernetes ClusterRoles. They already exist, so KubeUser will bind to them immediately.</p><p>• <strong>Manual Roles (developer, readonly-plus):</strong> These are <strong>custom roles</strong>. You must create these manually (via kubectl or GitOps) before applying <strong>Alice</strong>&#39;s config, otherwise the operator will report an error.</p><p><strong>Example of creating the missing manual roles:</strong></p><pre># Create the custom namespace Role<br>kubectl create role developer --verb=get,list,create,update --resource=pods,services -n staging<br><br># Create the custom ClusterRole<br>kubectl create clusterrole readonly-plus --verb=get,list,watch --resource=pods,nodes,events</pre><h4>3. Retrieving Credentials</h4><p>Once you apply the YAML above, KubeUser does the heavy lifting. You don’t need to run openssl. Just retrieve the generated secret:</p><pre># Extract the kubeconfig from the secret created by the operator<br>kubectl get secret alice-kubeconfig -n kubeuser -o jsonpath=&#39;{.data.config}&#39; | base64 -d &gt; alice.kubeconfig</pre><pre># Verify access<br>kubectl --kubeconfig alice.kubeconfig get pods -n development</pre><h4>4. Auditing</h4><pre>kubectl get users</pre><p>This output includes the user’s status, expiry time, and renewal time.</p><p>Auditing Bindings:</p><pre># Check bindings in the &#39;development&#39; namespace<br>kubectl get rolebindings -n development | grep alice</pre><pre># Check global bindings<br>kubectl get clusterrolebindings | grep alice</pre><h3>Security Features: “Shadow Secrets” and Safe Rotation</h3><p>KubeUser isn’t just a wrapper for openssl; it implements production-grade lifecycle management.</p><ul><li><strong>The “Shadow Secret” Pattern</strong></li></ul><p>Rotation causes downtime if not handled correctly. KubeUser uses a <strong>Shadow Secret strategy</strong>. When a certificate is due for renewal, the operator generates the new key and CSR in a temporary state. It only overwrites the live secret <em>after</em> the new certificate has been successfully verified by the API server. This ensures atomic updates and zero downtime.</p><ul><li><strong>The 33% Rule</strong></li></ul><p>Taking a page from cert-manager standards, KubeUser automatically triggers renewal when <strong>33% of the certificate&#39;s lifetime remains</strong>. If Alice has a 3-day certificate, KubeUser will attempt to rotate it after 48 hours, providing a massive safety buffer before expiration.</p><ul><li><strong>Guardrails</strong></li></ul><p>To prevent “Thundering Herd” loops where clients spam the API server requesting new keys, KubeUser’s validating webhooks enforce a <strong>minimum TTL of 24 hours</strong></p><h3>When to Use KubeUser</h3><p>KubeUser is best suited for environments where you need <strong>GitOps-driven access control</strong> without the overhead of managing an external Identity Provider (IdP) like Keycloak or Okta. It bridges the gap between simple ServiceAccounts and complex OIDC setups.</p><h3>Conclusion</h3><p>Kubernetes is moving toward a world where everything is managed as code, and user credentials shouldn’t be the exception. <strong>KubeUser</strong> bridges the gap between the complex needs of authentication and the simplicity of Kubernetes manifests.</p><p>You can check out the project, star the repo, or contribute at <a href="https://github.com/openkube-hub/KubeUser">https://github.com/openkube-hub/KubeUser</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3ca87b027a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Highly Available PostgreSQL Cluster with Patroni, etcd, and PgBouncer]]></title>
            <link>https://medium.com/@yahya.muhaned/building-a-highly-available-postgresql-cluster-with-patroni-etcd-and-pgbouncer-f8e363342bf4?source=rss-a5805f1335fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e363342bf4</guid>
            <category><![CDATA[pgbouncer]]></category>
            <category><![CDATA[patroni]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Muhaned Yahya]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 16:56:48 GMT</pubDate>
            <atom:updated>2025-09-20T18:26:45.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4m1inPGXf2_NKPwZoYfBg.png" /><figcaption>architecture diagram</figcaption></figure><p>Running PostgreSQL in production isn’t just about having a single server — it’s about <strong>high availability (HA)</strong>, <strong>automatic failover</strong>, and <strong>connection pooling</strong>. With the right setup, you can ensure your databases survive node failures without downtime.</p><p>In this guide, we’ll build a <strong>3-node PostgreSQL HA cluster</strong> using <strong>Patroni</strong>, <strong>etcd</strong>, and <strong>PgBouncer</strong>, combined with <strong>HAProxy + Keepalived</strong> for load balancing and a <strong>virtual IP</strong>.</p><h4>Architecture Overview</h4><pre>                       +------------------------+<br>                       |   Client Applications  |<br>                       | (Microservices, GUI)   |<br>                       +----------+-------------+<br>                                  |<br>                                  v<br>                       +----------------------+<br>                       |   Virtual IP (VIP)   |<br>                       |   192.168.50.100     |<br>                       +----------+-----------+<br>                                  |<br>              ---------------------------------------------<br>              |                                           |<br>   +----------+------------+                   +-----------+-----------+<br>   |   HAProxy + Keepalived|                   |  HAProxy + Keepalived|<br>   |       (haproxy1)      |                   |      (haproxy2)      |<br>   |   192.168.50.21       |                   |   192.168.50.22      |<br>   +----------+------------+                   +-----------+----------+<br>              \_______________________________________/<br>                              |<br>        ---------------------------------------------------<br>        |                    Patroni Nodes                |<br>        | (each running: PostgreSQL + PgBouncer + etcd)   |<br>        ---------------------------------------------------<br>             |                        |                       |<br>   +---------+---------+    +---------+---------+   +---------+---------+<br>   | patroni1           |    | patroni2           |   | patroni3          |<br>   | 192.168.50.11      |    | 192.168.50.12      |   | 192.168.50.13     |<br>   | PostgreSQL         |    | PostgreSQL         |   | PostgreSQL        |<br>   | PgBouncer          |    | PgBouncer          |   | PgBouncer         |<br>   | etcd               |    | etcd               |   | etcd              |<br>   +--------------------+    +--------------------+   +-------------------+</pre><p><strong>etcd:</strong> Distributed key-value store used by Patroni for consensus and leader election.</p><p><strong>Patroni:</strong> Orchestrates PostgreSQL, manages replication, failover, and recovery.</p><p><strong>PgBouncer:</strong> Connection pooler to reduce overhead from many client connections.</p><p><strong>HAProxy + Keepalived:</strong> Provides a VIP for clients, always pointing to the active PostgreSQL leader.</p><h3>🔧 Step 1. Preparing the Environment</h3><p>For this setup, I’m running on <strong>Ubuntu 22.04.5 LTS (Jammy Jellyfish).</strong></p><p>Update /etc/hosts for easier resolution:</p><pre>192.168.50.11  patroni1<br>192.168.50.12  patroni2<br>192.168.50.13  patroni3<br>192.168.50.21  haproxy1<br>192.168.50.22  haproxy2<br>192.168.50.100 pg-vip</pre><p>📂 Directory Layout and Tablespaces</p><p>I created dedicated directories for PostgreSQL data, WAL, logs, and optional tablespaces:</p><pre>sudo mkdir -p /pg/pgdata /pg/pgwal /pg/pglogs<br>sudo mkdir -p /tablespaces/TEST_TBS /tablespaces/TEST_TBS<br>sudo chown -R postgres:postgres /pg /tablespaces</pre><ul><li>/pg/pgdata → main PostgreSQL data directory</li><li>/pg/pgwal → separate storage for WAL files (recommended for performance and crash recovery)</li><li>/pg/pglogs → PostgreSQL logs</li><li>/tablespaces/… → optional directories for custom tablespaces<br><em>Tablespaces let you place different databases or schemas on different storage volumes.</em></li></ul><p><strong>⚠️ Important:</strong><br>The same directory structure (/pg/pgdata, /pg/pgwal, /pg/pglogs, and any /tablespaces/…) must exist on all Patroni nodes.</p><p>(<em>Optional</em> ) To create a tablespace in PostgreSQL, you’d run:</p><pre>CREATE TABLESPACE db1_tbs LOCATION &#39;/tablespaces/TEST_TBS&#39;;<br>CREATE DATABASE mydb TABLESPACE db1_tbs;</pre><p>Install required packages on all Patroni nodes:</p><p>source: <a href="https://www.postgresql.org/download/linux/ubuntu/">https://www.postgresql.org/download/linux/ubuntu/</a></p><pre># Import the repository signing key:<br>sudo apt install curl ca-certificates<br>sudo install -d /usr/share/postgresql-common/pgdg<br>sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc<br><br># Create the repository configuration file:<br>. /etc/os-release<br>sudo sh -c &quot;echo &#39;deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $VERSION_CODENAME-pgdg main&#39; &gt; /etc/apt/sources.list.d/pgdg.list&quot;<br><br># Update the package lists:<br>sudo apt update<br><br># Install the latest version of PostgreSQL:<br># If you want a specific version, use &#39;postgresql-17&#39; or similar instead of &#39;postgresql&#39;<br>sudo apt -y install postgresql-17</pre><p>install etcd pgbouncer patroni:</p><pre>sudo apt-get install postgresql-common patroni etcd python3-psycopg2 pgbouncer</pre><h3>🔧 Step 2. Configuring etcd</h3><p>On each etcd node, configure /etc/default/etcd:</p><p>Example for <strong>patroni1</strong>:</p><pre>ETCD_NAME=&quot;patroni1&quot;<br>ETCD_DATA_DIR=&quot;/var/lib/etcd&quot;<br>ETCD_LISTEN_PEER_URLS=&quot;http://192.168.50.11:2380&quot;<br>ETCD_LISTEN_CLIENT_URLS=&quot;http://192.168.50.11:2379,http://127.0.0.1:2379&quot;<br>ETCD_INITIAL_ADVERTISE_PEER_URLS=&quot;http://192.168.50.11:2380&quot;<br>ETCD_ADVERTISE_CLIENT_URLS=&quot;http://192.168.50.11:2379&quot;<br>ETCD_INITIAL_CLUSTER=&quot;patroni1=http://192.168.50.11:2380,patroni2=http://192.168.50.12:2380,patroni3=http://192.168.50.13:2380&quot;<br>ETCD_INITIAL_CLUSTER_STATE=&quot;new&quot;<br>ETCD_INITIAL_CLUSTER_TOKEN=&quot;pg-ha-etcd&quot;</pre><p>change etcd default config path:</p><pre>sudo mkdir -p /etc/systemd/system/etcd.service.d<br>sudo tee /etc/systemd/system/etcd.service.d/override.conf &gt;/dev/null &lt;&lt;&#39;EOF&#39;<br>[Service]<br>Environment=ETCD_DATA_DIR=/var/lib/etcd<br>EOF<br><br>sudo systemctl daemon-reload<br>sudo systemctl restart etcd<br>systemctl show etcd -p Environment | grep ETCD_DATA_DIR</pre><p>Repeat with node-specific IPs and names.</p><p>show etcd cluster health:</p><pre>ETCDCTL_API=3 etcdctl --endpoints=192.168.50.11:2379,192.168.50.12:2379,192.168.50.13:2379 endpoint health<br>etcdctl member list</pre><h3>🔧 Step 3. Configuring Patroni</h3><p>add patroni system service:</p><pre>cat &lt;&lt;&#39;EOF&#39; | sudo tee /etc/systemd/system/patroni.service<br>[Unit]<br>Description=Patroni PostgreSQL HA Cluster<br>After=network-online.target<br>Wants=network-online.target<br><br>[Service]<br>User=postgres<br>Group=postgres<br>Type=simple<br>ExecStart=/usr/bin/patroni /etc/patroni/patroni.yml<br>Restart=on-failure<br>LimitNOFILE=102400<br><br>[Install]<br>WantedBy=multi-user.target<br>EOF</pre><p>Each node has a Patroni config (/etc/patroni/patroni.yml). Example (for <strong>patroni1</strong>)</p><pre>scope: pg-ha<br>namespace: /service/<br>name: patroni1<br><br>restapi:<br>  listen: 0.0.0.0:8008<br>  connect_address: 192.168.50.11:8008<br><br>etcd:<br>  hosts: 192.168.50.11:2379,192.168.50.12:2379,192.168.50.13:2379<br><br>bootstrap:<br>  initdb:<br>    - encoding: UTF8<br>    - locale: en_US.UTF-8<br>    - data-checksums<br>    - waldir: /pg/pgwal/pg_wal<br>  dcs:<br>    ttl: 30<br>    loop_wait: 10<br>    retry_timeout: 10<br>    synchronous_mode: true<br>    synchronous_mode_strict: false<br>    synchronous_node_count: 1<br>    maximum_lag_on_failover: 1048576<br>    postgresql:<br>      use_pg_rewind: true<br>      parameters:<br>        shared_buffers: &#39;8GB&#39;<br>        effective_cache_size: &#39;16GB&#39;<br>        work_mem: &#39;32MB&#39;<br>        maintenance_work_mem: &#39;1GB&#39;<br>        wal_level: replica<br>        wal_compression: on<br>        wal_log_hints: on<br>        max_wal_senders: 10<br>        max_replication_slots: 10<br>        hot_standby: on<br>        hot_standby_feedback: on<br>        wal_keep_size: &#39;1024MB&#39;<br>        max_wal_size: &#39;8GB&#39;<br>        min_wal_size: &#39;1GB&#39;<br>        checkpoint_timeout: &#39;15min&#39;<br>        checkpoint_completion_target: 0.9<br>        fsync: on<br>        full_page_writes: on<br>        synchronous_commit: on<br>        archive_mode: on<br>        archive_command: &#39;pgbackrest --stanza=main archive-push %p&#39;<br>        logging_collector: on<br>        log_directory: &#39;/pg/pglogs&#39;<br>        log_filename: &#39;postgresql-%Y-%m-%d_%H%M%S.log&#39;<br>        log_truncate_on_rotation: on<br>        log_rotation_age: &#39;1d&#39;<br>        log_min_duration_statement: &#39;500ms&#39;<br><br>  users:<br>    replicator:<br>      password: &quot;ReplPass123&quot;<br>      options: [replication]<br>    admin:<br>      password: &quot;AdminPass123&quot;<br>      options: [createrole, createdb]<br><br>postgresql:<br>  listen: 0.0.0.0:5432<br>  connect_address: 192.168.50.11:5432<br>  data_dir: /pg/pgdata<br>  bin_dir: /usr/lib/postgresql/17/bin<br>  authentication:<br>    superuser:<br>      username: postgres<br>      password: &quot;SuperSecurePass123&quot;<br>    replication:<br>      username: replicator<br>      password: &quot;ReplPass123&quot;<br>  pg_hba:<br>    - host replication replicator 192.168.50.0/24 md5<br>    - host all all 0.0.0.0/0 md5<br><br>watchdog:<br>  mode: off</pre><p><strong>patroni2</strong> — /etc/patroni/patroni.yml</p><p>(same as above but name, connect_address, and IPs updated to 192.168.50.12)</p><p><strong>patroni3</strong> — /etc/patroni/patroni.yml</p><p>(same as above but name, connect_address, and IPs updated to 192.168.50.13)</p><p>Run Patroni as a systemd service:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable patroni<br>sudo systemctl start patroni<br>patronictl -c /etc/patroni/patroni.yml list<br>sudo patronictl -c /etc/patroni/config.yml show-config</pre><h3>🔧 Step 4. Setting up PgBouncer</h3><p>Each node runs PgBouncer at port <strong>6432</strong>:</p><p>/etc/pgbouncer/pgbouncer.ini</p><pre>[databases]<br>appdb = host=127.0.0.1 port=5432 dbname=appdb user=appuser pool_size=20 reserve_pool_size=5<br>* = host=10.157.8.23 port=5432 user=postgres pool_mode=session<br>[pgbouncer]<br>logfile = /var/log/postgresql/pgbouncer.log<br>pidfile = /var/run/postgresql/pgbouncer.pid<br>listen_addr = 0.0.0.0<br>listen_port = 6432<br>auth_type = plain<br>auth_file = /etc/pgbouncer/userlist.txt<br>admin_users = postgres<br>pool_mode = transaction<br>max_client_conn = 1000<br>max_db_connections = 100<br>reserve_pool_size = 5<br>stats_users = postgres</pre><p>/etc/pgbouncer/users.txt</p><pre>&quot;appdb&quot; &quot;myAppPassword&quot;<br>&quot;postgres&quot; &quot;myPostgresPassword&quot;</pre><p>Enable and start:</p><pre>sudo systemctl enable pgbouncer<br>sudo systemctl restart pgbouncer</pre><p>The /etc/pgbouncer/pgbouncer.ini and /etc/pgbouncer/userlist.txt files must be created and configured on <strong>each Patroni node</strong> (patroni1, patroni2, patroni3).</p><h3>🔎 Transaction vs Session Pooling</h3><p>Choosing the right <strong>pool mode</strong> is critical:</p><ul><li><strong>transaction mode</strong> (recommended for microservices):</li><li>Each query/transaction borrows a connection and releases it immediately.</li><li>Great for stateless, API-driven apps.</li><li>⚠️ GUI tools like <strong>DBeaver/pgAdmin</strong> may fail because they expect a stable session. <br>👉 That’s why I added a catch-all * rule with pool_mode=session, so I can still manage the cluster comfortably from GUI tools while keeping transaction mode as the default for microservices.</li><li><strong>session mode</strong> (recommended for interactive tools / long-lived sessions):</li><li>Client gets the same backend connection for the entire session.</li><li>Required for tools that keep temporary tables, prepared statements, or cursors open.</li><li>Less efficient for microservices.</li></ul><h3>🔐 Authentication Best Practices</h3><p><strong>Local PgBouncer (same host as Postgres)</strong> → auth_type = plain is acceptable since traffic never leaves the machine.</p><p><strong>Remote PgBouncer (dedicated pooler nodes)</strong> → Use md5 or scram-sha-256 for stronger security.</p><h3>🔧 Step 5. HAProxy + Keepalived</h3><p>install HAProxy and KeepAlived:</p><pre>sudo apt -y install haproxy keepalived<br># Enable Binding to VIP<br>echo &#39;net.ipv4.ip_nonlocal_bind = 1&#39; | sudo tee /etc/sysctl.d/60-nonlocal-bind.conf<br>sudo sysctl -p /etc/sysctl.d/60-nonlocal-bind.conf</pre><p>HAProxy forwards traffic to Patroni leader via PgBouncer:</p><p>/etc/haproxy/haproxy.cfg</p><pre>global<br>    daemon<br>    maxconn 5000<br>    log /dev/log local0<br><br>defaults<br>    mode tcp<br>    log global<br>    timeout connect 5s<br>    timeout client 30s<br>    timeout server 30s<br><br>frontend pg_write<br>    bind *:5432<br>    default_backend pgsql-write<br><br>backend pgsql-write<br>    balance roundrobin<br>    option httpchk GET /master<br>    http-check expect status 200<br>    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions<br>    server patroni1 192.168.50.11:6432 check port 8008<br>    server patroni2 192.168.50.12:6432 check port 8008<br>    server patroni3 192.168.50.13:6432 check port 8008<br><br>listen stats<br>    bind *:8404<br>    mode http<br>    stats enable<br>    stats uri /haproxy?stats<br>    stats refresh 10s</pre><pre>sudo haproxy -c -f /etc/haproxy/haproxy.cfg<br>sudo systemctl reload haproxy<br>sudo ss -lntp | grep &#39;:5432&#39;     # should show haproxy LISTEN</pre><p>repeat for haproxy1 and haproxy2.</p><p>HAProxy on each LB node is querying Patroni on all DB nodes (via the IPs and port 8008) to monitor their role. You can test this by visiting <a href="http://192.168.100.11:8008/master">http://HAPROXY_IP:8008/master</a> in a browser or with curl — the primary will return HTTP 200 and some JSON status, replicas return 503.</p><h3>🔧 Keepalived Configuration</h3><p>We’ll configure <strong>two HAProxy nodes</strong> (haproxy1 as MASTER, haproxy2 as BACKUP).</p><p>haproxy1 — /etc/keepalived/keepalived.conf</p><pre>global_defs {<br>  script_user root<br>  enable_script_security<br>}<br><br>vrrp_script chk_haproxy {<br>    script &quot;/usr/bin/systemctl is-active --quiet haproxy&quot;<br>    interval 2<br>    weight -5<br>}<br><br>vrrp_instance VI_PG {<br>    state MASTER<br>    interface eth0<br>    virtual_router_id 51<br>    priority 100<br>    advert_int 1<br>    authentication {<br>        auth_type PASS<br>        auth_pass MySecretPass<br>    }<br>    unicast_src_ip 192.168.50.21<br>    unicast_peer {<br>        192.168.50.22<br>    }<br>    virtual_ipaddress {<br>        192.168.50.100/32 dev eth0<br>    }<br>    track_script {<br>        chk_haproxy<br>    }<br>}</pre><p>haproxy2 — /etc/keepalived/keepalived.conf</p><pre>global_defs {<br>  script_user root<br>  enable_script_security<br>}<br><br>vrrp_script chk_haproxy {<br>    script &quot;/usr/bin/systemctl is-active --quiet haproxy&quot;<br>    interval 2<br>    weight -5<br>}<br><br>vrrp_instance VI_PG {<br>    state BACKUP<br>    interface eth0<br>    virtual_router_id 51<br>    priority 50<br>    advert_int 1<br>    authentication {<br>        auth_type PASS<br>        auth_pass MySecretPass<br>    }<br>    unicast_src_ip 192.168.50.22<br>    unicast_peer {<br>        192.168.50.21<br>    }<br>    virtual_ipaddress {<br>        192.168.50.100/32 dev eth0<br>    }<br>    track_script {<br>        chk_haproxy<br>    }<br>}</pre><pre>sudo systemctl restart keepalived<br>sudo journalctl -u keepalived -f</pre><p>✅ Testing the Cluster</p><p>Check Patroni status:</p><pre>patronictl -c /etc/patroni/patroni.yml list</pre><p>Connect via VIP:</p><pre>psql -h 192.168.50.100 -U postgres -d appdb</pre><p>Simulate failover by stopping Patroni on the leader and watching HAProxy switch:</p><pre>sudo systemctl stop patroni<br>curl http://PATRONI_NODE_IP:8008/master</pre><h4>📌 Conclusion</h4><ul><li>Patroni + etcd handles PostgreSQL replication and leader election.</li><li>PgBouncer provides lightweight connection pooling.</li><li>HAProxy + Keepalived ensures seamless client access through a single VIP.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e363342bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Native Routing and LoadBalancers with Cilium BGP in Kubernetes]]></title>
            <link>https://medium.com/@yahya.muhaned/native-routing-and-loadbalancers-with-cilium-bgp-in-kubernetes-16a952080982?source=rss-a5805f1335fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/16a952080982</guid>
            <category><![CDATA[cilium]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[on-premise]]></category>
            <dc:creator><![CDATA[Muhaned Yahya]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 11:53:35 GMT</pubDate>
            <atom:updated>2025-09-07T12:12:05.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32g-j9-g-vbc0tcwUtvdpQ.png" /></figure><p>This guide walks through setting up Cilium with the BGP control plane on an on-prem Kubernetes cluster, replacing kube-proxy and MetalLB with a cleaner, native routing approach.</p><h3>Why Cilium BGP?</h3><p>Traditional Kubernetes networking usually depends on:</p><ul><li><strong>kube-proxy</strong> → for service routing</li><li><strong>MetalLB</strong> → for advertising LoadBalancer services in on-prem environments</li></ul><p>This reduces moving parts, simplifies operations, and improves performance.</p><h3>🏗️ My Cluster Setup</h3><ul><li>Provisioned with <strong>Kubespray v2.27</strong></li><li><strong>Kubernetes v1.31.7</strong> with kube_proxy_remove: true</li><li>Pod subnet: 192.170.0.0/16</li><li>Service subnet: 172.17.0.0/16</li><li>3 master nodes + 5 worker nodes (on-prem)</li></ul><p>Cilium installation:</p><pre>cilium install --version 1.17.4 \<br>  --set kubeProxyReplacement=true \<br>  --set k8sServiceHost=172.17.0.1 \<br>  --set k8sServicePort=443 \<br>  --set ipam.mode=kubernetes \<br>  --set routingMode=native \<br>  --set ipv4NativeRoutingCIDR=192.170.0.0/16 \<br>  --set bgpControlPlane.enabled=true \<br>  --set k8s.requireIPv4PodCIDR=true \<br>  --set gatewayAPI.enabled=true</pre><h3>🔗 BGP Topology</h3><ul><li><strong>Masters</strong> → Advertise only <strong>Pod CIDRs</strong></li><li><strong>Workers</strong> → Advertise both <strong>Pod CIDRs</strong> and <strong>LoadBalancer Services</strong></li><li>Upstream router → 10.113.10.1, ASN 64513</li><li>Cluster ASN → 64515</li></ul><p>In my setup, the upstream router is a <strong>FortiGate firewall</strong> configured with BGP enabled.<br> 👉 Important: your upstream router <strong>must support BGP</strong> in order for this integration to work.</p><p>This way:</p><ul><li>Routing is distributed and scalable</li><li>LoadBalancer services are directly reachable in the network without MetalLB</li></ul><pre>                +-----------------------------+<br>                |  Upstream Router (ASN 64513)|<br>                |        10.113.10.1          |<br>                +---------------+-------------+<br>                                ^<br>                      BGP 64513 &lt;-&gt; 64515<br>                                |<br>               ---------------------------------------<br>               |                                     |<br>     +---------+---------+                 +---------+---------+<br>     |   Masters (x3)    |                 |   Workers (x5)    |<br>     | advertise=podcidr |                 | advertise=service |<br>     |  PodCIDR export   |                 |  PodCIDR export   |<br>     |                   |                 | LB Service export |<br>     +-------------------+                 +-------------------+</pre><h3>⚙️ Cilium BGP Configurations</h3><p>Masters: Advertise Pod CIDRs</p><pre>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPClusterConfig<br>metadata:<br>  name: test-bgp-cluster-config-masters<br>spec:<br>  nodeSelector:<br>    matchLabels:<br>      advertise: &quot;podcidr&quot;<br>  bgpInstances:<br>  - name: &quot;default&quot;<br>    localASN: 64515<br>    peers:<br>      - name: &quot;upstream-router&quot;<br>        peerAddress: &quot;10.113.10.1&quot;<br>        peerASN: 64513<br>        peerConfigRef:<br>          name: test-peer-config-masters<br>---<br>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPPeerConfig<br>metadata:<br>  name: test-peer-config-masters<br>spec:<br>  timers:<br>    holdTimeSeconds: 90<br>    keepAliveTimeSeconds: 30<br>  families:<br>    - afi: ipv4<br>      safi: unicast<br>      advertisements:<br>        matchLabels:<br>          advertise: &quot;podcidr&quot;<br>---<br>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPAdvertisement<br>metadata:<br>  name: test-bgp-podcidr-advertisement<br>  labels:<br>    advertise: &quot;podcidr&quot;<br>spec:<br>  advertisements:<br>    - advertisementType: &quot;PodCIDR&quot;</pre><p>Workers: Advertise Pod CIDRs + Services</p><pre>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPClusterConfig<br>metadata:<br>  name: test-bgp-cluster-config-workers<br>spec:<br>  nodeSelector:<br>    matchLabels:<br>      advertise: &quot;service&quot;<br>  bgpInstances:<br>  - name: &quot;default&quot;<br>    localASN: 64515<br>    peers:<br>      - name: &quot;upstream-router&quot;<br>        peerAddress: &quot;10.113.10.1&quot;<br>        peerASN: 64513<br>        peerConfigRef:<br>          name: test-peer-config-workers<br>---<br>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPPeerConfig<br>metadata:<br>  name: test-peer-config-workers<br>spec:<br>  timers:<br>    holdTimeSeconds: 90<br>    keepAliveTimeSeconds: 30<br>  families:<br>    - afi: ipv4<br>      safi: unicast<br>      advertisements:<br>        matchLabels:<br>          advertise: &quot;service&quot;<br>---<br>apiVersion: cilium.io/v2alpha1<br>kind: CiliumBGPAdvertisement<br>metadata:<br>  name: test-bgp-workers-advertisement<br>  labels:<br>    advertise: &quot;service&quot;<br>spec:<br>  advertisements:<br>    - advertisementType: &quot;PodCIDR&quot;<br>    - advertisementType: &quot;Service&quot;<br>      service:<br>        addresses:<br>          - LoadBalancerIP<br>      selector:<br>        matchExpressions:<br>          - { key: advertise, operator: In, values: [ service ] }<br>      attributes:<br>        communities:<br>          standard: [ &quot;64512&quot; ]</pre><h3>Verifying BGP Peers with Cilium CLI</h3><pre>cilium bgp peers</pre><p>Sample output:</p><pre>Peer Address     ASN    Session State  Uptime     Families<br>10.113.10.1      64513  established    2h10m      ipv4/unicast</pre><p>cilium bgp routes advertised</p><p>Example:</p><pre>Family          Prefix            NextHop<br>ipv4/unicast    192.170.1.0/24    0.0.0.0<br>ipv4/unicast    172.17.10.50/32   0.0.0.0</pre><h3>🏷️ Labels Matter</h3><p>For this setup to work:</p><ul><li>Nodes must have the right <strong>labels</strong> (advertise=podcidr or advertise=service)</li><li>LoadBalancer services must also carry the <strong>advertise label</strong> to be exported via BGP</li></ul><h3>✅ Lessons Learned</h3><ul><li><strong>ASN planning</strong> is important → avoid conflicts with upstream routers</li><li><strong>Labels are the key</strong> → no label, no advertisement</li><li>This approach <strong>removes MetalLB</strong> completely while giving me full BGP-powered routing</li></ul><h3>🎯 Conclusion</h3><p>By combining <strong>Cilium’s kube-proxy replacement, native routing, and BGP control plane</strong>, I simplified my networking stack:</p><ul><li>No kube-proxy</li><li>No MetalLB</li><li>Direct BGP route advertisements</li><li>Full visibility with Hubble</li></ul><p>If you want fewer moving parts with more control, I highly recommend trying <strong>Cilium BGP</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16a952080982" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>