<?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 Luca Camphuisen on Medium]]></title>
        <description><![CDATA[Stories by Luca Camphuisen on Medium]]></description>
        <link>https://medium.com/@camphul?source=rss-ceae985ea960------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*51zeafe9ksiiOuuzGc9DqQ.jpeg</url>
            <title>Stories by Luca Camphuisen on Medium</title>
            <link>https://medium.com/@camphul?source=rss-ceae985ea960------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:54:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@camphul/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[CloudNative-PG in the homelab with Longhorn]]></title>
            <link>https://medium.com/@camphul/cloudnative-pg-in-the-homelab-with-longhorn-b08c40b85384?source=rss-ceae985ea960------2</link>
            <guid isPermaLink="false">https://medium.com/p/b08c40b85384</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Luca Camphuisen]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 07:00:55 GMT</pubDate>
            <atom:updated>2024-07-02T20:38:00.437Z</atom:updated>
            <content:encoded><![CDATA[<p>In my first blog on Medium I will showcase my solution on running cloud-native PostgreSQL on Kubernetes (K3s) with Longhorn storage.</p><p><strong>Update as of July 2nd 2024: </strong>I have added the “<em>Drain nodes with CloudNative-PG volumes</em>” section due to issues I discovered when upgrading from Ubuntu 22.04 to 24.04.</p><p>As a software engineer who is into both Kubernetes and homelabs, one of the challenges is managing stateful data. A popular phrase in the ecosystem is:</p><blockquote>Cattle, not pets</blockquote><p>I believe that this is true to some extent but somewhere you still need to persist your data. I have thought about using separate VMs for databases but I really wanted the capabilities that Kubernetes brings and disliked the overhead that VMs bring. When I first began my Kubernetes journey I was just using a Helm chart for PostgreSQL and only had a single pod/replica (a pet, following our previous analogy), I quickly found out just deploying a PostgreSQL chart with Longhorn storage will break your database in no time. Upgrading the PostgreSQL versions also was not fun and caused downtime (not too important in a homelab but still not nice).</p><p>I then decided to try out CloudNative-PG. CloudNative-PG is a Kubernetes operator that can manage the lifecycle of your database. You create a “<em>Cluster</em>” resource in yaml and then the operator will manage the database for you. It is also able to perform periodic backups and is able to restore from various kinds of backed up data when configured correctly.</p><h3>Ubuntu &amp; Longhorn</h3><p>My homelab Kubernetes cluster currently runs on Ubuntu server 22.04 VMs (upgrading to 24.04 but am also looking into <a href="https://www.talos.dev/">Talos</a> 👀). I am using K3s and only have NVMe storage. Even before using CloudNative-PG I had experienced some issues with Longhorn. I had various volume mounting errors and did not have a smooth experience.</p><p>I managed to resolve these issues by creating a <em>/etc/multipath.conf</em> configuration file on the Kubernetes nodes as described in the related <a href="https://longhorn.io/kb/troubleshooting-volume-with-multipath/">Longhorn troubleshooting page</a>. <br>Grasping/explaining multipath is pretty difficult and I do not want to explain it in this blog. I would recommend reading <a href="https://en.wikipedia.org/wiki/Linux_DM_Multipath">the Wikipedia page</a> for a quick summary.</p><p>Create <em>/etc/multipath.conf</em> and write the following contents:</p><pre>blacklist {<br>    devnode &quot;^sd[a-z0-9]+&quot;<br>}</pre><p>Then restart the <em>multipathd</em> service and Longhorn should not have these mounting issues anymore.</p><p>To handle node failures, the draining of nodes, and database replica failover I have also changed some default Longhorn configurations. I have installed Longhorn as Helm chart using ArgoCD GitOps. These are some of the values I have configured:</p><pre>defaultSettings:<br>  orphanAutoDeletion: false<br>  autoDeletePodWhenVolumeDetachedUnexpectedly: true<br>  nodeDownPodDeletionPolicy: delete-both-statefulset-and-deployment-pod<br>  nodeDrainPolicy: always-allow</pre><p>These options can also be configured within the Longhorn web UI settings page. The “<em>nodeDrainPolicy</em>” field is described in the “<em>Drain nodes with CloudNative-PG volumes</em>” section. It is required to drain nodes that have the last/only replica of a Longhorn volume. You could set it to the default value and only use <em>“always-allow”</em> when having to drain nodes.</p><h3>Custom Longhorn storage class</h3><p>Since CloudNative-PG uses application-level replication, we do not want to also replicate the data in Longhorn. If we have 3 database replicas, that would mean we have 9 copies of the data when using the default 3 replicas in Longhorn. We would really like a single copy of the data per database replica.</p><p>Another thing that broke my databases when I first began using CloudNative-PG was the scheduling of the pods in the cluster. Kubernetes would schedule a database pod on a node, Longhorn would try to mount the volume to the pod, but the pod would be stuck on initialising because it could not mount. This was caused by the default volume binding mode. The <em>Immediate</em> volume binding mode does not take the pod scheduling requirements into consideration. One of the scheduling requirements we would like is that the pod is placed on the same node as where the volume resides.</p><p>Within the Longhorn web UI I also added an “<em>nvme</em>” <a href="https://longhorn.io/docs/latest/nodes-and-volumes/nodes/storage-tags/">storage tag</a> to the disks which makes it possible to select which storage medium we want for our applications. Go to the “<em>Node</em>” page at the top menu, select a node and click “<em>Edit node and disks</em>” on the right side (dropdown menu) and apply your relevant tags:</p><figure><img alt="The longhorn menu where you add disk tags" src="https://cdn-images-1.medium.com/max/449/1*XTc9ElyKa9Utw_5BV3pozw.png" /><figcaption>Part of the “Edit Node and Disks” menu where you manage disk tags.</figcaption></figure><p>After adding the tags to each disk I came up with the following storage class:</p><pre>kind: StorageClass<br>apiVersion: storage.k8s.io/v1<br>metadata:<br>  name: longhorn-postgres-replica-storage<br>  annotations:<br>    storageclass.kubernetes.io/is-default-class: &quot;false&quot;<br>provisioner: driver.longhorn.io<br>allowVolumeExpansion: true<br># WaitForFirstConsumer mode will delay the binding and provisioning of a PersistentVolume until a Pod using the PersistentVolumeClaim is created.<br>volumeBindingMode: WaitForFirstConsumer<br>reclaimPolicy: Delete<br>parameters:<br>  numberOfReplicas: &quot;1&quot;<br>  staleReplicaTimeout: &quot;1440&quot; # 1 day<br>  fsType: &quot;ext4&quot;<br>  diskSelector: &quot;nvme&quot;<br>  dataLocality: &quot;strict-local&quot;<br>  recurringJobSelector: &#39;[<br>      {<br>        &quot;name&quot;:&quot;postgres-replica-storage&quot;,<br>        &quot;isGroup&quot;:true<br>      }<br>    ]&#39;</pre><p>In this storage class we specify that we want NVMe storage (if you have lower bandwidth/iops requirements you could for example choose HDD), we only want one replica of the data, the pod must be scheduled on the same node as where the volume resides, we change the binding mode to <em>WaitForFirstConsumer</em>, and I added a job selector. This selector can be used to create a backup job within Longhorn (backup all volumes with <em>X</em> selector). I do not personally use the Longhorn backup feature for my PostgreSQL since I backup using the CloudNative-PG backup CRD’s, but I can imagine that it could be useful. Have a look at all available <a href="https://longhorn.io/docs/latest/references/storage-class-parameters/">Longhorn storage class parameters</a> for more information.</p><p>When having multiple types of storage, it may be useful to create a second storage class for the WAL (write ahead log) data. I only have NVMe storage in my cluster (all the same speed) so I just use the same storage class for both WAL and DB data.</p><h3>Creating your database</h3><p>I am currently running databases for various services in my cluster. <br>A couple of examples are: Keycloak, Harbor, Gitea, my own projects. Most of these are created from a backup I did since I tend to sometimes nuke my services by having a wrongly indented yaml file (need to improve my GitHub Actions and Argo CD integration 😬). I will provide an example database resource together with the periodic backup:</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: Cluster<br>metadata:<br>  name: iam-db<br>  labels:<br>    app.kubernetes.io/component: database<br>    app.kubernetes.io/version: 16.3-bullseye<br>spec:<br>  instances: 3<br>  description: &quot;Keycloak DB&quot;<br>  imageName: &quot;ghcr.io/cloudnative-pg/postgresql:16.3-bullseye&quot;<br><br>  primaryUpdateStrategy: unsupervised<br><br>  bootstrap:<br>    initdb:<br>      database: iam<br>      owner: iam<br>      secret:<br>        name: db-credentials<br><br>  # configure storage types used<br>  storage:<br>    storageClass: longhorn-postgres-replica-storage<br>    size: 2Gi<br>  walStorage:<br>    storageClass: longhorn-postgres-replica-storage<br>    size: 2Gi<br><br>  # prometheus<br>  monitoring:<br>    enablePodMonitor: true<br><br>  # see https://cloudnative-pg.io/documentation/1.22/kubernetes_upgrade/<br>  nodeMaintenanceWindow:<br>    reusePVC: false # rebuild from other replica instead<br><br>  backup:<br>    retentionPolicy: &quot;60d&quot;<br>    barmanObjectStore:<br>      destinationPath: s3://databases/iam-db<br>      endpointURL: https://your-s3-minio-or-aws-url<br>      s3Credentials:<br>        accessKeyId:<br>          name: barman-credentials<br>          key: access-key-id<br>        secretAccessKey:<br>          name: barman-credentials<br>          key: secret-access-key<br>      wal:<br>        compression: gzip # this saves a lot of storage<br>      data:<br>        compression: gzip<br>        jobs: 2</pre><p>The above yaml is not perfect but works great in a homelab environment. I have been running my Keycloak database this way and have not had any big issues so far (8+ months of PostgreSQL upgrading, usage, node failures). I will not explain everything in the yaml so please <a href="https://cloudnative-pg.io/docs/">read the CloudNative-PG docs</a>. They are very extensive and they also have a great <a href="https://join.slack.com/t/cloudnativepg/shared_invite/zt-2ij5hagfo-B04EQ9DUlGFzD6GEHDqE0g">community on slack</a>.</p><p>The “<em>db-credentials</em>” and “<em>barman-credentials</em>” values reference Kubernetes secrets. Do ensure that “<em>db-credentials</em>” is of type “<em>kubernetes.io/basic-auth</em>” instead of being a generic secret.</p><p>I have also been experimenting with certificate-based auth. Instead of using the CloudNative-PG Krew plugin to manage certificates I have integrated <a href="https://cert-manager.io/">cert-manager</a> to manage the certificate lifecycles (since I only apply changes using Argo CD / easier to do using cert-manager). Please let me know if you would like a post about configuring PostgreSQL/CloudNative-PG with certificates and connecting to the database in Spring Boot and/or with IntelliJ 😄</p><h3>Periodic backups</h3><p>Creating scheduled backups is very easy with CloudNative-PG. Just create a “<em>ScheduledBackup”</em> resource like this:</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: ScheduledBackup<br>metadata:<br>  name: db-scheduled-backup<br>  labels:<br>    app.kubernetes.io/component: database-backup<br>spec:<br>  schedule: &quot;0 0 23/12 * * *&quot; # At 0 minutes past the hour, every 12 hours, starting at 11:00 PM<br>  backupOwnerReference: none<br>  immediate: false<br>  cluster:<br>    name: &quot;iam-db&quot; # Your Cluster resource name<br></pre><p>The <em>backupOwnerReference</em> sets the owner of each backup that is made. <br>You can also set it to “<em>self”</em> or “<em>cluster”. </em>Please reference the <a href="https://cloudnative-pg.io/documentation/1.23/backup/#scheduled-backups">documentation on backups</a> for more information.</p><h3>Backup recovery</h3><p>Recovering a database from a backup is fairly easy. You need to create a new “<em>Cluster”</em> resource and instead of bootstrapping a new DB from scratch, you bootstrap from a database backup resource:</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: Cluster<br>metadata:<br>  name: iam-db<br>  labels:<br>    app.kubernetes.io/component: database<br>    app.kubernetes.io/version: 16.3-bullseye<br>spec:<br>  instances: 3<br>  description: &quot;Keycloak DB&quot;<br>  imageName: &quot;ghcr.io/cloudnative-pg/postgresql:16.3-bullseye&quot;<br><br>  primaryUpdateStrategy: unsupervised<br><br>  bootstrap:<br>    recovery:<br>      owner: keycloak<br>      secret:<br>        name: db-credentials<br>      database: keycloak<br>      backup:<br>        name: your-backup-resource-name<br><br>  # configure storage types used<br>  storage:<br>    storageClass: longhorn-postgres-replica-storage<br>    size: 2Gi<br>  walStorage:<br>    storageClass: longhorn-postgres-replica-storage<br>    size: 2Gi<br><br>  # prometheus<br>  monitoring:<br>    enablePodMonitor: true<br><br>  # see https://cloudnative-pg.io/documentation/1.22/kubernetes_upgrade/<br>  nodeMaintenanceWindow:<br>    reusePVC: false # rebuild from other replica instead<br><br>  backup:<br>    retentionPolicy: &quot;60d&quot;<br>    barmanObjectStore:<br>      destinationPath: s3://databases/iam-db<br>      endpointURL: https://your-s3-minio-or-aws-url<br>      s3Credentials:<br>        accessKeyId:<br>          name: barman-credentials<br>          key: access-key-id<br>        secretAccessKey:<br>          name: barman-credentials<br>          key: secret-access-key<br>      wal:<br>        compression: gzip<br>      data:<br>        compression: gzip<br>        jobs: 2</pre><h3>Drain nodes with CloudNative-PG volumes</h3><p>When upgrading my Kubernetes host VMs from Ubuntu server 22.04 to 24.04 I experienced several issues related to Longhorn and CloudNative-PG.<br>My usual host OS upgrade process consists of draining a node, then applying the upgrades, rebooting the node, and finally uncordoning the node.</p><p>When attempting the upgrade to Ubuntu server 24.04 I first experienced some common issues related to <em>PodDisruptionBudget</em> configurations not allowing the node to drain (not related to CloudNative-PG). <br>After fixing those issues, the nodes still would not drain correctly. This was caused by Longhorn not allowing a node to drain if it contains the only replica left of a volume.</p><p>The <em>StorageClass</em> that we use for our CloudNative-PG databases only has one replica configured per volume which means Longhorn prevents the node from draining. To solve this you can (temporarily) configure the “<em>Node Drain Policy</em>” in Longhorn to “<em>always-allow</em>”. Go to the Longhorn web UI and navigate to the settings page.<br>If you use GitOps you could also set the “<em>defaultSettings</em>.<em>nodeDrainPolicy</em>” to “<em>always-allow</em>” (when installing using Helm).</p><p>We can now successfully drain a node even when it contains a CloudNative-PG volume. Before draining though there is one step left: we need to put the CloudNative-PG “<em>Cluster</em>” resources into node maintenance mode. Edit your “<em>Cluster</em>” resource as follows:</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: Cluster<br>metadata:<br>  name: iam-db<br>  labels:<br>    app.kubernetes.io/component: database<br>    app.kubernetes.io/version: 16.3-bullseye<br>spec:<br>...<br>  nodeMaintenanceWindow:<br>    inProgress: true # add this field<br>...</pre><p>Apply the changes and now CloudNative-PG will failover by creating a new DB replica together with a new PVC.<br>To then drain a node I have used the following command:</p><pre>kubectl drain &lt;NODE-NAME&gt; --ignore-daemonsets --delete-emptydir-data --grace-period=360</pre><p>You may also verify if all pods are evicted from the node. Only pods controlled by DaemonSets should still be running:</p><pre>kubectl get pods --all-namespaces --field-selector spec.nodeName=&lt;NODE-NAME&gt;</pre><h3>Thank you!</h3><p>Thanks for reading my first blog on Medium! Feel free to connect with me on <a href="https://www.linkedin.com/in/luca-camphuisen/">LinkedIn</a>. Special shoutout to <a href="https://www.linkedin.com/in/mbianchidev/">Matteo Bianchi</a> for providing feedback on my first post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b08c40b85384" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>