K3s Homelab for Edge Computing Experiments
local graph
Chapter 5 — K3s Homelab for Edge Computing Experiments
Section titled “Chapter 5 — K3s Homelab for Edge Computing Experiments”At this point, we have explored essential topics to create your own edge computing cluster. The previous chapters covered how to configure and install a K3s cluster. Building small and big solutions at home involves experimenting. In this chapter, we are going to start building a simple but real cluster, using the knowledge acquired in the previous chapters. We will refer to this environment as the K3s homelab. Once this cluster is created, we are going to deploy a simple application. We will use this as a quickstart method of using Kubernetes with your cluster. In the last part of this chapter, we are going to use the Kubernetes dashboard as a simple UI to manage Kubernetes clusters.
In this chapter, we’re going to cover the following main topics:
- Installing a multi-node K3s cluster on your local network
- Deploying your first application with
kubectl - Deploying a simple NGINX server using YAML files
- Adding persistence to your applications
- Deploying a Kubernetes dashboard
Technical requirements
Section titled “Technical requirements”For this chapter, you need the following hardware to create your K3s homelab for your edge computing applications or experiments:
- Two or more Raspberry Pi 4 B models with a minimum of 4 GB RAM and a 32 GB microSD card with Ubuntu version 20.04 or later. The SanDisk Extreme microSDHC 32 GB UHS-1 A1 V30 or similar is recommended as the microSD card.
- Ethernet cables to connect your Raspberries.
- An Ethernet internet connection for the Raspberries with Dynamic Host Configuration Protocol (DHCP) activated.
- One switch to connect your Raspberry to your local network.
With this hardware, we are ready to start building our K3s homelab. So, let’s get started.
For more detail and code snippets, check out this resource on GitHub: https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch5
Installing a multi-node K3s cluster on your local network
Section titled “Installing a multi-node K3s cluster on your local network”To start creating this homelab, let’s understand the network topology that we are going to use. Each component in the following diagram is used in the homelab:

Figure 5.1 – Homelab architecture
Here is a small explanation of each component in the figure:
- Lan: This is the local network that you are going to use. In our example, the network is defined as
192.168.0.0/24. - Switch: A switch is also a network connecting device that connects various devices in the same network.
- Router: A router connects devices across multiple networks. Typically, home routers are hybrid devices that give local computers access to the internet. It also has small switch capabilities to connect local computers, using wireless or Ethernet ports for your wired devices.
- Public Interface: This is the interface of your router that has a public IP.
- Gateway: This is an IP address that is used as the gateway in your private network.
- DNS: This is the DNS IP address that your router is going to assign to your devices automatically – in this case,
8.8.8.8and1.1.1.1. - Master: This is the master node of your K3s cluster.
- Agent: This is the agent node that acts as a worker in your K3s cluster.
- Client: This is your local machine or laptop where you are going to access the cluster using the
kubectlcommand.
Now – a small explanation about how these pieces interact with each other. All your machines will use the 192.168.0.0/24 network; in this case, let’s think that your client will use the 192.168.0.2 IP. Using the config files or parameters to install your cluster, you can choose an IP range inside the previous network for your nodes. In this case, the master is using the 192.168.0.11 IP and your agents are using the 192.168.0.12 and 192.168.0.13 IP addresses. Remember that your configuration has set static IP private addresses to your nodes to prevent errors in your nodes if the IP address changes. We assume that the nodes are using IP addresses starting from 192.168.0.11 to 192.168.0.13. We are going to use the 192.168.0.240 to 192.168.0.250 IP address range for load balancers. This is just a simple example of how to organize your IPs for your cluster.
We are assuming that your router is in the 192.168.0.0/24 network. As we mentioned, home routers have some switch capabilities to auto-assign dynamic IP addresses using a DHCP service configured inside the router, but this isn’t healthy for your nodes. That’s the main reason for using static IPs for your nodes. We are assuming some public IP to use as an example. We are assuming that we are going to use the 8.8.8.8 and 1.1.1.1 DNS servers.
Important Note
All these IP ranges can change, depending on your internet provider or the router device that you are using. We set these values to provide an example of how to organize the network for your cluster.
To create your homelab, we have to complete the following tasks:
- Install Ubuntu image on your Raspberry device.
- Configure your device to run the K3s installer.
- Configure the K3s master node.
- Configure the K3s agent nodes.
- Install MetalLB as the load balancing service.
- Install Longhorn as the default storage class.
- Configure
kubectlin an external client to access the cluster. - Deploy your first application using
kubectland YAML files. - Install and configure Lens to manage your cluster.
So, let’s now quickly recap the concepts, starting with how to install Ubuntu on your device.
Installing an Ubuntu image on your Raspberry device
Section titled “Installing an Ubuntu image on your Raspberry device”In this section, we are going to install an Ubuntu image on a Raspberry device. You can skip this section or refer to previous chapters for more information. As a quick summary, you can follow the next steps to install Ubuntu on a Raspberry device:
- Open Raspberry Pi Imager.
- Click on the CHOOSE OS button to choose the Ubuntu Server 20.04 64-bit for ARM64 operating system, which is located in the Other general purpose OS | Ubuntu menu.
- Then, insert your microSD card (you may have to buy an adapter to read microSD cards); your device appears when you select the CHOOSE STORAGE button.
- Click on the WRITE button.
- Accept to write the device; then, Raspberry Pi Imager will ask you for your username and password in order to continue writing to the microSD card.
- Wait until the writing and verifying process finishes.
- Extract your microSD card.
- Insert the microSD card into your Raspberry Pi and turn it on.
- Repeat these steps for each Raspberry Pi device that will be part of your cluster.
Now, let’s move to configure the network settings and the container support for your device.
Configuring your Raspberry Pi to run the K3s installer
Section titled “Configuring your Raspberry Pi to run the K3s installer”In this section, we are going to configure the network settings, including your static IP address, DNS, hostname, and hosts files, finalizing with activating the support of the cgroups necessary to use containerd. Now, follow the next steps to perform the final setup before installing K3s in your nodes; remember that you can customize all these configurations to fit your own network:
- Turn on your device.
- When Ubuntu asks you for your username and password, enter the username and
ubuntuas the password this is the default password for the first login. - Now, Ubuntu will ask you to change the default password; let’s use
k3s123-as our password. - Now, let’s configure the network; by default, Ubuntu uses
cloud-initto configure the network. Let’s deactivate this by creating the99-disable-network-config.cfgfile with the following commands and content:$ sudo nano /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
Here is an example of the content:
network: {config: disabled}- If you execute
ifconfig, you will see that your device iseth0, but it can be namedes3or something similar, so let’s modify the50-cloud-initfile with the following command:$ sudo nano /etc/netplan/50-cloud-init.yaml - Then, modify the content of the file; it has to look something like this:
network:version: 2renderer: networkdethernets:eth0:dhcp4: noaddresses:- 192.168.0.11/24gateway4: 192.168.0.1nameservers:addresses: [8.8.8.8, 1.1.1.1]
- Now, apply the configuration and reboot your device to see whether your IP address is set when the Operating System (OS) starts. To do this, execute the following command:
$ sudo netplan apply
- Now, configure the kernel parameters for the boot by editing the
/boot/firmware/cmdline.txtfile with the following command and content:$ sudo nano /boot/firmware/cmdline.txt
Add this content to the end of the line:
cgroup_memory=1 cgroup_enable=memory- Edit
/etc/hostnameusing themastername for your master node. Usenode01andnode02for the hostnames of your agent nodes; let’s edit the file usingnano:$ sudo nano /etc/hostname
Here is an example of the content:
master- Edit the
/etc/hostsfile, adding the hostname; at a minimum, you need to have a line like this:$ sudo nano /etc/hosts
Here is an example of the content:
127.0.0.1 localhost masterImportant Note
You can also use master.local instead of master to follow Internet Engineering Task Force (IETF) naming conventions for local networks. This may also help with zero-configuration multicast DNS (mDNS) setups. For more information, you can check out this link: http://www.zeroconf.org.
Now, reboot your device:
$ sudo rebootThis configuration is required to prepare your device to configure a K3s master or agent nodes. You can also follow IETF recommendations for local network design. In the next section, you will see how to install K3s for your master nodes.
Configuring the K3s master node
Section titled “Configuring the K3s master node”This section explains how to install your master node for your K3s cluster; for this, you have to follow these steps:
- Turn on your device and log in with your
ubuntuuser. - Run the following commands to install your master node using
MASTER_IPas192.168.0.11, as shown in Figure 5.1, for your K3s cluster:$ MASTER_IP=<YOUR_PRIVATE_IP>$ curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--write-kubeconfig-mode 644 --no-deploy traefik --disable traefik --tls-san "$MASTER_IP" --node-external-ip "$MASTER_IP" --disable servicelb" sh -s -
Now, we have installed the master node. This will be the node with the 192.168.0.11 IP address. Now, let’s go ahead and add agent nodes to the cluster in the next section.
Configuring the K3s agent nodes
Section titled “Configuring the K3s agent nodes”This section explains how to complete our initial cluster diagram by repeating this section twice to complete the configuration of two agent nodes. Agent nodes will use the 192.168.0.12 and 192.168.0.13 IP addresses. Complete the following steps to configure each agent node:
- Log in to your master node:
$ ssh ubuntu@<MASTER_IP>
We are going to extract the servicer node token to connect the agent nodes. In this case, the master node will be 192.168.0.11.
- Extract and copy the token to join your agent nodes in the cluster, running the following command:
$ sudo cat /var/lib/rancher/k3s/server/node-token
- Log out from your master node. Now, you have the token to join additional nodes to the cluster.
For each agent node to join the cluster, follow the next steps (the easy way):
- Log in to your agent node that you want to add to the cluster. In this case,
AGENT_IPwill be192.168.0.12or192.168.0.13:$ ssh ubuntu@<AGENT_IP> - Set an environment variable with the token that your master generated:
$ export TOKEN=<YOUR_MASTER_TOKEN>
- Register your node with the following command; in this case,
MASTER_IPwill be192.168.0.11:$ curl -sfL https://get.k3s.io | sh -s - agent --server https://MASTER_IP:6443 --token ${TOKEN}
Exit from your agent node:
$ exitNow, we have configured our agent nodes. Let’s install MetalLB to start using load balancers for our applications.
Installing MetalLB as the load balancing service
Section titled “Installing MetalLB as the load balancing service”MetalLB is a bare metal load balancer that can help when using the load balancing service of a regular Kubernetes cluster, with the capabilities of networking designed for bare metal, such as IP address assignment. So, let’s get started by installing MetalLB by following these steps:
- Create a MetalLB namespace (
metallb-system) with the official manifests, executing the following lines:$ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/namespace.yaml - Before running the command to install MetalLB, you have to create a
ConfigMapresource calledmetallb-configinside themetallb-systemnamespace. Let’s call this fileconfig.yaml, with the following content:apiVersion: v1kind: ConfigMapmetadata:namespace: metallb-systemname: configdata:config: |address-pools:- name: defaultprotocol: layer2addresses:- 192.168.0.240-192.168.0.250 - Now, create
ConfigMap, executing the following command:$ kubectl apply -f config.yaml - Install MetalLB with the official manifests by executing the following lines:
$ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/metallb.yaml
Now, you have installed MetalLB. You are ready to install services that use load balancers. These load balancers are commonly found in a lot of Kubernetes software. Now, it is time to add Longhorn for our storage.
Installing Longhorn with ReadWriteMany mode
Section titled “Installing Longhorn with ReadWriteMany mode”K3s includes basic storage support. Sometimes, this storage can cause errors when you are installing software. To prevent this, you will need another storage driver instead of the default one that comes with K3s. In this case, you can use Longhorn. With Longhorn, you can install Kubernetes software that looks for regular storage drivers. So, let’s install Longhorn in the following steps:
- Log in to your virtual machine (VM) or device:
$ ssh ubuntu@NODE_IP
- If you want to install ReadWriteMany Persistent Volume (PVC) mode, you have to install
nfs-commonon each VM with Ubuntu installed in your cluster. To do this, execute the following command:$ sudo apt install -y nfs-common - Apply the official Longhorn manifests, as follows:
$ kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/v1.1.2/deploy/longhorn.yaml
Now, you have Longhorn installed and running. Let’s move on to learn how to configure kubectl on your personal computer to manage your K3s.
Extracting the K3s kubeconfig file to access your cluster
Section titled “Extracting the K3s kubeconfig file to access your cluster”Now, it’s time to configure the kubeconfig file to access your K3s cluster from your computer, using the kubectl command. To configure the connection of your new K3s cluster from the outside, follow these steps:
- Install
kubectl, following the instructions of the official documentation of Kubernetes (https://kubernetes.io/docs); in this case, we are going to use the instructions for Macintosh:$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl"$ chmod +x ./kubectl$ sudo mv ./kubectl /usr/local/bin/kubectl$ sudo chown root: /usr/local/bin/kubectl
Or you can install kubectl using brew on macOS, using the next command:
$ brew install kubectlFor other custom installations, such as kubectl for Apple’s new silicon processors, Linux, or Windows, visit the Kubernetes official documentation: https://kubernetes.io/docs/tasks/tools/install-kubectl-macos.
- From the master node, copy the content inside
/etc/rancher/k3s/k3s.yamlto your local~/.kube/configfile. - Change the permissions of the file with the next command:
$ chmod 0400 ~/.kube/config
- Change part of the server value from
127.0.0.1to theMASTER_IPaddress of your master node; in this case, it will be192.168.0.11:server: https://127.0.0.1:6443
This changes to the following:
server: https://MASTER_IP:6443Important Note
Remember to install kubectl before you copy the Rancher kubeconfig file onto your computer. Remember that the content of the k3s.yaml file has to be stored inside ~/.kube/config and needs the 0400 permissions. To check how to install the kubectl command, go to https://kubernetes.io/docs/tasks/tools/install-kubectl-macos.
Now, we are ready to use the cluster. In the next section, we are going to deploy a basic application with kubectl and YAML files, using MetalLB and Longhorn. So, let’s start deploying applications, using kubectl in the next section.
Deploying your first application with kubectl
Section titled “Deploying your first application with kubectl”This section covers the basics of Kubernetes. We are going to deploy an application using kubectl first. But before that, let me give you a quick introduction about how Kubernetes works with its basic objects.
Basic Kubernetes objects
Section titled “Basic Kubernetes objects”Kubernetes works with objects that provide different functionalities for your application using containers. The goal of Kubernetes is to orchestrate your containers. Kubernetes uses two ways to create objects. One is using imperative commands – in the case of Kubernetes, the kubectl command. The other is using declarative files, where the state of an object is defined, and Kubernetes ensures that this state stays as it was defined throughout its lifetime:

Figure 5.2 – Kubernetes objects
This diagram represents how some of the basic objects interact with each other to deploy and manage an application. So, let’s explain each of these objects:
- Pod contains one or more containers, where your application lives; all the containers inside a Pod share the same network, memory, and CPU.
- ReplicaSet controls the number of pods to be the same.
- Deployment is an advanced kind of ReplicaSet object that not only controls the number of Pods and versions but also the changes of the Pods, providing a way to perform rollbacks.
- Service is a way to expose your services. There are different types. NodePort opens a random port on all the nodes, ClusterIP creates a DNS that you can use to communicate with your Pod or deploy with other Pods or deployments, and LoadBalancer creates an exclusive endpoint to publish your app to the outside.
- Persistent Volume Claim is the object in charge of requesting persistent storage and creating stateful deployments.
- Storage Class is the object that defines how you are going to request storage for an application.
With these pretty basic concepts, let’s move on to the practical aspects to understand how each component works. In the next section, we are going to deploy a simple NGINX server using kubectl.
Deploying a simple NGINX server with pods using kubectl
Section titled “Deploying a simple NGINX server with pods using kubectl”In this section, we are going to deploy an NGINX server, step by step, using kubectl. To do this, follow these steps:
- Create a pod with the
nginximage:$ kubectl run myserver --image=nginx --restart=Never - Create a
LoadBalancertype of service for this Pod to expose and access the NGINX pod:$ kubectl expose pod/myserver --port=8001 --target-port=80 –type=LoadBalancer - Assign the IP address to your load balancer with the following command:
$ IP_SERVICE=$(kubectl get svc mywebserver --output jsonpath='{.status.loadBalancer.ingress[0].ip}')
- Access the next URL using your browser or the following command:
$ curl IP_SERVICE:8001
Now, you have an NGINX service up and running. So, let’s move to deploy a Redis database that you can access to store data in the next section.
Deploying a Redis NoSQL database with pods
Section titled “Deploying a Redis NoSQL database with pods”Now, we are going to deploy a Redis NoSQL key-value database that you can access to store some data. We chose Redis as a basic example as it is quick and easy to use. So, let’s deploy Redis using the following commands:
- Create a pod with a
redisimage:$ kubectl run myredis --image=redis --restart=Never - Create a
ClusterIPservice that you can use to connect to Redis using the name of the service:$ kubectl expose pod myredis --port=6379 --type=ClusterIP - Let’s create an
ubuntuclient with the next command:$ kubectl run client -it --rm --image=ubuntu:18.04 -- bash - Now, you are inside the client, so let’s install the Redis client to get connected to the Redis pods with the following command:
root@client# apt-get update;apt-get install -y redis-tools
- Store the variable with the value
1and get the value from the client, using the following commands:root@client# redis-cli -h myredis set a 1root@client# redis-cli –h myredis get a
The last command returns the value of the a variable, which is 1.
- Write
exitand then press Enter to exit the client. The client will be automatically deleted because of the--rmparameter. - Now, let’s expose Redis, using
NodePortas an example of how to expose a pod using the IPs of your nodes:$ kubectl expose pod myredis --name=myredis-nodeport --port=6379 --type=NodePort
Now, you can access your Redis database using the IP of the host where Redis was deployed.
You have finished installing a simple database – in this case, Redis. Now, let’s explore the deployment objects and storage in the next section.
Deploying and scaling an NGINX server with deployments
Section titled “Deploying and scaling an NGINX server with deployments”One of the advantages of using deployments is that you manage the changes of your deployment if the version or the configuration changes. Let’s deploy a simple NGINX server, scale the deployment, change the image, and then perform a rollback to see the power of deployments. Deploy the NGINX server by following these steps:
- Create a deployment with two replicas using the
nginximage:$ kubectl create deployment mywebserver --image=nginx --replicas=2 - Create a
LoadBalancerservice to expose your deployment:$ kubectl expose deployment mywebserver --port=8002 --target-port=80 --type=LoadBalancer - Create the IP for
mywebserver:$ IP_SERVICE=$(kubectl get svc mywebserver --output jsonpath='{.status.loadBalancer.ingress[0].ip}') - Access the web server using
curl:$ curl $IP_SERVICE:8002 - Scale
mywebserverwith0replicas:$ kubectl scale deploy/mywebserver --replicas=0 - Try to access
mywebserveragain:$ curl $IP_SERVICE:8002 - Scale
mywebserverwith two replicas and wait until the deployment is ready; you can check this with the following:$ kubectl scale deploy/mywebserver --replicas=2$ kubectl rollout status deploy/mywebserver - Try to access
mywebserveragain:$ curl $IP_SERVICE:8002 - Let’s change the
nginxversion of the deployment with the wrong version:$ kubectl set image deployment/mywebserver nginx=nginx:1.16.1.x - Check the changes in the description of the object:
$ kubectl describe deployment mywebserver | grep -i image
- Check the current pod status for the
mywebserverdeployment:$ kubectl get pods
You will see some pods from mywebserver with errors.
- Let’s roll back to the previous version:
$ kubectl rollout undo deploy/mywebserver
- Check the current pod status for the
mywebserverdeployment:$ kubectl get pods
You will see that the pods with errors have disappeared because you returned to the previous image that the deployment was using – in this case, the correct image name.
Now, you have deployed your application using the deployment object. Let’s do something similar using YAML files and add some persistence. To do this, let’s move on to the next section.
Deploying a simple NGINX server using YAML files
Section titled “Deploying a simple NGINX server using YAML files”At this point, our examples don’t store data and the objects are created using imperative commands. To use declarative files, you can use the kubectl command to generate the files. Remember to deploy your application, using pods or deployments – just choose one of these options. To start, let’s create an NGINX pod using YAML files.
Deploying an NGINX server using a Pod
Section titled “Deploying an NGINX server using a Pod”Now, let’s create an NGINX pod using YAML files. To do this, follow these steps:
- If you want to use pods, you can use the next YAML file. To generate the file, use the following command:
$ kubectl run nginx --image=nginx --dry-run –o yaml > nginx-pod.yaml
The nginx-pod.yaml file will look like this:
apiVersion: v1kind: Podmetadata: name: nginx labels: name: nginxspec: containers: - name: nginx image: nginx ports: - containerPort: 80- Apply the generated file using the following command:
$ kubectl create -f nginx-pod.yaml
Let’s move on to create an NGINX deployment in the next section.
Deploying an NGINX server using deployment
Section titled “Deploying an NGINX server using deployment”So, let’s get started creating an NGINX server using deployment with YAML files. To do this, follow these steps:
- Generate the YAML file for deployment using the following command:
$ kubectl create deployment nginx --image=nginx --replicas=2 --dry-run –o yaml > nginx-deployment.yaml
The file nginx-deployment.yaml will look like this:
apiVersion: apps/v1kind: Deploymentmetadata: labels: app: nginx name: nginxspec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx name: nginx- Apply the generated file using the following command:
$ kubectl create -f nginx-deployment.yaml
Now that we have learned how to create a pod and deployment in Kubernetes, let’s move on to the next section to expose these objects using services with YAML files.
Exposing your pods using the ClusterIP service and YAML files
Section titled “Exposing your pods using the ClusterIP service and YAML files”To communicate your pod or deployment with other applications, you may need a DNS record. The ClusterIP service type creates a DNS A record for your pod or deployment. Using this DNS, other objects in your cluster can access your application. So, let’s create a ClusterIP service for your application, following these steps:
- To expose your application using YAML files, generate the YAML file for the
ClusterIPservice type:$ kubectl expose pod/nginx --type=ClusterIP --port=80 --target-port=8001 --dry-run –o yaml > nginx-clusterip.yaml
The nginx-service.yaml file will look like this:
apiVersion: v1kind: Servicemetadata: creationTimestamp: null labels: app: nginx name: nginxspec: ports: - port: 80 protocol: TCP targetPort: 8001 selector: app: nginx type: ClusterIP- Apply the generated file using the following command:
$ kubectl create -f nginx-pod.yaml
Now that you have learned how to create a ClusterIP service using YAML files, let’s move on to creating a NodePort service for your application in the next section.
Exposing your pods using the NodePort service and YAML files
Section titled “Exposing your pods using the NodePort service and YAML files”To create a NodePort service for a previously created pod, follow these steps:
- For
NodePort, use the following command:kubectl expose pod/nginx --type=NodePort --port=80 --target-port=8001 --dry-run -o yaml > nginx-nodeport.yaml
The nginx-nodeport.yaml file will look like this:
apiVersion: v1kind: Servicemetadata: labels: app: nginx name: nginxspec: ports: - port: 80 protocol: TCP targetPort: 8001 selector: app: nginx type: NodePort- Apply the generated file using the next command:
kubectl create -f nginx-pod.yaml
Now that you have learned how to create a NodePort service for your application in a pod, it’s time to learn how to use LoadBalancer services in the next section.
Exposing your pods using a LoadBalancer service and YAML files
Section titled “Exposing your pods using a LoadBalancer service and YAML files”To create a LoadBalancer service to expose your application inside a pod, follow these steps:
- For
LoadBalancer, use the next command:$ kubectl expose pod/nginx --type=LoadBalancer --port=80 -target-port=8001 --dry-run -o yaml > nginx-lb.yaml
The generated nginx-lb.yaml file will look like this:
apiVersion: v1kind: Servicemetadata: labels: app: nginx name: nginxspec: ports: - port: 80 protocol: TCP targetPort: 8001 selector: app: nginx type: LoadBalancer- Apply the generated file using the next command:
$ kubectl create -f nginx-pod.yaml
You have learned how to create a LoadBalancer service. With this, we have covered all the basic services in Kubernetes. Now, we are ready to learn how to create stateful applications. Let’s move on to the next section to add persistence to your applications.
Adding persistence to your applications
Section titled “Adding persistence to your applications”Now, it is time to add storage to your applications; we are going to use the storage classes installed with Longhorn to provide persistence to your applications. In this section, we are going to explore two examples using persistent volumes. In this part of the book, we are going to discuss the persistent volumes and the process of creating storage for a Pod. But first, we need a persistent volume claim definition to provision this storage.
Creating an NGINX pod with a storage volume
Section titled “Creating an NGINX pod with a storage volume”To create your NGINX application using a storage volume that uses the Longhorn storage class, follow these steps:
- Create
pvc.yaml:apiVersion: v1kind: PersistentVolumeClaimmetadata:name: longhorn-volv-pvcspec:accessModes:- ReadWriteManystorageClassName: longhornresources:requests:storage: 2Gi - Apply the
pvc.yamlYAML file:$ kubectl create -f pvc.yaml
Now, it’s time to create a pod using this PVC that uses the Longhorn storage class. To do this, follow these steps:
- Create and apply the
pod.yamlfile to create a pod using the previously created PVC:apiVersion: v1kind: Podmetadata:name: volume-testnamespace: defaultspec:containers:- name: volume-testimage: nginx:stable-alpineimagePullPolicy: IfNotPresentvolumeMounts:- name: volvmountPath: /dataports:- containerPort: 80volumes:- name: volvpersistentVolumeClaim:claimName: longhorn-volv-pvc
This example has created a pod using a persistent volume, with the Longhorn storage class. Let’s continue with a second example that shows a database using a storage volume.
Creating the database using a persistent volume
Section titled “Creating the database using a persistent volume”Now, is time to use a persistent volume for a database; in this example, you are going to learn how to create a Redis database with a persistent volume. So, let’s get started with the following steps:
- Create the
redis.yamlfile to create a pod that uses the previouslonghorn-volv-pvcPVC:apiVersion: v1kind: Podmetadata:name: redisspec:containers:- name: redisimage: redisvolumeMounts:- name: redis-storagemountPath: /data/redisvolumes:- name: redis-storagepersistentVolumeClaim:claimName: longhorn-volv-pvc - Apply the
pod.yamlYAML file to create the pod:$ kubectl create -f pod.yaml - Check and Apply the
pod.yamlYAML file to create the pod:$ kubectl create -f pod.yaml - Apply the
pod.yamlYAML file to create the pod:$ kubectl create -f pod.yaml
Troubleshooting Your Deployments
Remember that you can use the kubectl logs command to troubleshoot your deployments. For more information, you can check the next link: https://kubernetes.io/docs/tasks/debug-application-cluster/debug-running-pod/.
Now, your Redis database is running and using a persistent volume to prevent the loss of data. In the last section, we are going to explore how to install a simple Kubernetes dashboard to manage your cluster using a UI.
Deploying a Kubernetes dashboard
Section titled “Deploying a Kubernetes dashboard”Now, it’s time to install a Kubernetes dashboard. The next steps are based on the official K3s documentation. To start installing the dashboard, follow these steps:
- Install the dashboard using the following commands:
$ GITHUB_URL=https://github.com/kubernetes/dashboard/releases$ VERSION_KUBE_DASHBOARD=$(curl -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o /dev/null | sed -e 's|.*/||')$ sudo k3s kubectl create -f https://raw.githubusercontent.com/kubernetes/dashboard/${VERSION_KUBE_DASHBOARD}/aio/deploy/recommended.yaml
This is going to install the dashboard, but you need to configure how to access this dashboard.
- Create the
dashboard-admin-user.yamlfile to create a service account that provides access to your dashboard. The content of this file will be as follows:apiVersion: v1kind: ServiceAccountmetadata:name: admin-usernamespace: kubernetes-dashboard - Now create the file
dashboard-admin-user-role.yaml. The content of this file will be the next:apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:name: admin-userroleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: cluster-adminsubjects:- kind: ServiceAccountname: admin-usernamespace: kubernetes-dashboard - Now, apply the YAML files with the following command:
$ kubectl create -f dashboard-admin-user.yml -f dashboard-admin-user-role.yml
- Get the token inside the service account that will be used to access the dashboard:
$ kubectl -n kubernetes-dashboard describe secret admin-user-token | grep '^token'
Copy the token content only.
- Use
kubectl proxyto expose the Kubernetes API in your localhost, using the following command:$ sudo kubectl proxy - Access your browser with the following URL:
http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/
Sign in with the admin user bearer token that you got. Choose the Token option and enter the token. You will see a screen like this:

Figure 5.3 – Kubernetes Dashboard sign-in screen
After clicking on the Sign In button, you will see the dashboard. Explore the different menus to see the state of your objects, or click on the plus icon at the lower-right corner to create objects using the YAML files:

Figure 5.4 – Kubernetes Dashboard showing CPU and memory usage
We have now completed all the necessary concepts, giving you a quick introduction to how to use basic objects in Kubernetes with K3s.
Summary
Section titled “Summary”In this chapter, we learned how to set up a K3s cluster with Raspberry Pi devices for our homelab. We also covered how to use basic Kubernetes objects to deploy an application. We deployed sample applications in an imperative way using the kubectl command. We also deployed sample applications using YAML files too. At the end of the chapter, we covered how to install a Kubernetes dashboard to manage your cluster. In the next chapter, we are going to continue adding more pieces to this deployment; we are going to use ingress controllers to deploy applications at the edge.
Questions
Section titled “Questions”Here are a few questions to validate your new knowledge:
- What are the basic Kubernetes objects that I need to create an application?
- How can I install a K3s cluster for my homelab?
- How can I use
kubectlto create my applications? - How can I use YAML files to create my applications?
- How can I use persistent volumes?
- How can I troubleshoot my applications?
Further reading
Section titled “Further reading”You can refer to the following references for more information on the topics covered in this chapter:
- K3s installation options to add custom parameters to your config files: https://rancher.com/docs/k3s/latest/en/installation/install-options
- Longhorn official page: https://longhorn.io
- MetalLB official page: https://metallb.universe.tf
- Official Kubernetes documentation: https://kubernetes.io/docs
- Kubernetes Dashboard installation guide: https://rancher.com/docs/k3s/latest/en/installation/kube-dashboard
- Kubernetes Dashboard installation using Helm: https://artifacthub.io/packages/helm/k8s-dashboard/kubernetes-dashboard