Skip to content
ImagineWorld

K3s Homelab for Edge Computing Experiments

node_idnode-book_edge-computing-systems-with-kubernetes_chapter-05-k3s-homelab-for-edge-computing-experiments
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleK3s Homelab for Edge Computing Experiments
governed_byCORPUS
constitutional_citationCONSTITUTION
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

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.8 and 1.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 kubectl command.

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:

  1. Install Ubuntu image on your Raspberry device.
  2. Configure your device to run the K3s installer.
  3. Configure the K3s master node.
  4. Configure the K3s agent nodes.
  5. Install MetalLB as the load balancing service.
  6. Install Longhorn as the default storage class.
  7. Configure kubectl in an external client to access the cluster.
  8. Deploy your first application using kubectl and YAML files.
  9. 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:

  1. Open Raspberry Pi Imager.
  2. 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.
  3. 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.
  4. Click on the WRITE button.
  5. 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.
  6. Wait until the writing and verifying process finishes.
  7. Extract your microSD card.
  8. Insert the microSD card into your Raspberry Pi and turn it on.
  9. 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:

  1. Turn on your device.
  2. When Ubuntu asks you for your username and password, enter the username and ubuntu as the password this is the default password for the first login.
  3. Now, Ubuntu will ask you to change the default password; let’s use k3s123- as our password.
  4. Now, let’s configure the network; by default, Ubuntu uses cloud-init to configure the network. Let’s deactivate this by creating the 99-disable-network-config.cfg file 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}
  1. If you execute ifconfig, you will see that your device is eth0, but it can be named es3 or something similar, so let’s modify the 50-cloud-init file with the following command:
    $ sudo nano /etc/netplan/50-cloud-init.yaml
  2. Then, modify the content of the file; it has to look something like this:
    network:
    version: 2
    renderer: networkd
    ethernets:
    eth0:
    dhcp4: no
    addresses:
    - 192.168.0.11/24
    gateway4: 192.168.0.1
    nameservers:
    addresses: [8.8.8.8, 1.1.1.1]
  3. 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
  4. Now, configure the kernel parameters for the boot by editing the /boot/firmware/cmdline.txt file 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
  1. Edit /etc/hostname using the master name for your master node. Use node01 and node02 for the hostnames of your agent nodes; let’s edit the file using nano:
    $ sudo nano /etc/hostname

Here is an example of the content:

master
  1. Edit the /etc/hosts file, 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 master

Important 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 reboot

This 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.

This section explains how to install your master node for your K3s cluster; for this, you have to follow these steps:

  1. Turn on your device and log in with your ubuntu user.
  2. Run the following commands to install your master node using MASTER_IP as 192.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.

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:

  1. 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.

  1. 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
  2. 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):

  1. Log in to your agent node that you want to add to the cluster. In this case, AGENT_IP will be 192.168.0.12 or 192.168.0.13:
    $ ssh ubuntu@<AGENT_IP>
  2. Set an environment variable with the token that your master generated:
    $ export TOKEN=<YOUR_MASTER_TOKEN>
  3. Register your node with the following command; in this case, MASTER_IP will be 192.168.0.11:
    $ curl -sfL https://get.k3s.io | sh -s - agent --server https://MASTER_IP:6443 --token ${TOKEN}

Exit from your agent node:

$ exit

Now, 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:

  1. 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
  2. Before running the command to install MetalLB, you have to create a ConfigMap resource called metallb-config inside the metallb-system namespace. Let’s call this file config.yaml, with the following content:
    apiVersion: v1
    kind: ConfigMap
    metadata:
    namespace: metallb-system
    name: config
    data:
    config: |
    address-pools:
    - name: default
    protocol: layer2
    addresses:
    - 192.168.0.240-192.168.0.250
  3. Now, create ConfigMap, executing the following command:
    $ kubectl apply -f config.yaml
  4. 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:

  1. Log in to your virtual machine (VM) or device:
    $ ssh ubuntu@NODE_IP
  2. If you want to install ReadWriteMany Persistent Volume (PVC) mode, you have to install nfs-common on each VM with Ubuntu installed in your cluster. To do this, execute the following command:
    $ sudo apt install -y nfs-common
  3. 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:

  1. 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 kubectl

For 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.

  1. From the master node, copy the content inside /etc/rancher/k3s/k3s.yaml to your local ~/.kube/config file.
  2. Change the permissions of the file with the next command:
    $ chmod 0400 ~/.kube/config
  3. Change part of the server value from 127.0.0.1 to the MASTER_IP address of your master node; in this case, it will be 192.168.0.11:
    server: https://127.0.0.1:6443

This changes to the following:

server: https://MASTER_IP:6443

Important 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.

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:

  1. Create a pod with the nginx image:
    $ kubectl run myserver --image=nginx --restart=Never
  2. Create a LoadBalancer type of service for this Pod to expose and access the NGINX pod:
    $ kubectl expose pod/myserver --port=8001 --target-port=80 –type=LoadBalancer
  3. 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}')
  4. 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:

  1. Create a pod with a redis image:
    $ kubectl run myredis --image=redis --restart=Never
  2. Create a ClusterIP service that you can use to connect to Redis using the name of the service:
    $ kubectl expose pod myredis --port=6379 --type=ClusterIP
  3. Let’s create an ubuntu client with the next command:
    $ kubectl run client -it --rm --image=ubuntu:18.04 -- bash
  4. 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
  5. Store the variable with the value 1 and get the value from the client, using the following commands:
    root@client# redis-cli -h myredis set a 1
    root@client# redis-cli –h myredis get a

The last command returns the value of the a variable, which is 1.

  1. Write exit and then press Enter to exit the client. The client will be automatically deleted because of the --rm parameter.
  2. Now, let’s expose Redis, using NodePort as 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:

  1. Create a deployment with two replicas using the nginx image:
    $ kubectl create deployment mywebserver --image=nginx --replicas=2
  2. Create a LoadBalancer service to expose your deployment:
    $ kubectl expose deployment mywebserver --port=8002 --target-port=80 --type=LoadBalancer
  3. Create the IP for mywebserver:
    $ IP_SERVICE=$(kubectl get svc mywebserver --output jsonpath='{.status.loadBalancer.ingress[0].ip}')
  4. Access the web server using curl:
    $ curl $IP_SERVICE:8002
  5. Scale mywebserver with 0 replicas:
    $ kubectl scale deploy/mywebserver --replicas=0
  6. Try to access mywebserver again:
    $ curl $IP_SERVICE:8002
  7. Scale mywebserver with 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
  8. Try to access mywebserver again:
    $ curl $IP_SERVICE:8002
  9. Let’s change the nginx version of the deployment with the wrong version:
    $ kubectl set image deployment/mywebserver nginx=nginx:1.16.1.x
  10. Check the changes in the description of the object:
    $ kubectl describe deployment mywebserver | grep -i image
  11. Check the current pod status for the mywebserver deployment:
    $ kubectl get pods

You will see some pods from mywebserver with errors.

  1. Let’s roll back to the previous version:
    $ kubectl rollout undo deploy/mywebserver
  2. Check the current pod status for the mywebserver deployment:
    $ 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.

Now, let’s create an NGINX pod using YAML files. To do this, follow these steps:

  1. 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: v1
kind: Pod
metadata:
name: nginx
labels:
name: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
  1. 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:

  1. 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/v1
kind: Deployment
metadata:
labels:
app: nginx
name: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: nginx
name: nginx
  1. 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:

  1. To expose your application using YAML files, generate the YAML file for the ClusterIP service 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: v1
kind: Service
metadata:
creationTimestamp: null
labels:
app: nginx
name: nginx
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8001
selector:
app: nginx
type: ClusterIP
  1. 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:

  1. 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: v1
kind: Service
metadata:
labels:
app: nginx
name: nginx
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8001
selector:
app: nginx
type: NodePort
  1. 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:

  1. 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: v1
kind: Service
metadata:
labels:
app: nginx
name: nginx
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8001
selector:
app: nginx
type: LoadBalancer
  1. 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.

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:

  1. Create pvc.yaml:
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: longhorn-volv-pvc
    spec:
    accessModes:
    - ReadWriteMany
    storageClassName: longhorn
    resources:
    requests:
    storage: 2Gi
  2. Apply the pvc.yaml YAML 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:

  1. Create and apply the pod.yaml file to create a pod using the previously created PVC:
    apiVersion: v1
    kind: Pod
    metadata:
    name: volume-test
    namespace: default
    spec:
    containers:
    - name: volume-test
    image: nginx:stable-alpine
    imagePullPolicy: IfNotPresent
    volumeMounts:
    - name: volv
    mountPath: /data
    ports:
    - containerPort: 80
    volumes:
    - name: volv
    persistentVolumeClaim:
    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:

  1. Create the redis.yaml file to create a pod that uses the previous longhorn-volv-pvc PVC:
    apiVersion: v1
    kind: Pod
    metadata:
    name: redis
    spec:
    containers:
    - name: redis
    image: redis
    volumeMounts:
    - name: redis-storage
    mountPath: /data/redis
    volumes:
    - name: redis-storage
    persistentVolumeClaim:
    claimName: longhorn-volv-pvc
  2. Apply the pod.yaml YAML file to create the pod:
    $ kubectl create -f pod.yaml
  3. Check and Apply the pod.yaml YAML file to create the pod:
    $ kubectl create -f pod.yaml
  4. Apply the pod.yaml YAML 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.

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:

  1. 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.

  1. Create the dashboard-admin-user.yaml file to create a service account that provides access to your dashboard. The content of this file will be as follows:
    apiVersion: v1
    kind: ServiceAccount
    metadata:
    name: admin-user
    namespace: kubernetes-dashboard
  2. Now create the file dashboard-admin-user-role.yaml. The content of this file will be the next:
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
    name: admin-user
    roleRef:
    apiGroup: rbac.authorization.k8s.io
    kind: ClusterRole
    name: cluster-admin
    subjects:
    - kind: ServiceAccount
    name: admin-user
    namespace: kubernetes-dashboard
  3. Now, apply the YAML files with the following command:
    $ kubectl create -f dashboard-admin-user.yml -f dashboard-admin-user-role.yml
  4. 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.

  1. Use kubectl proxy to expose the Kubernetes API in your localhost, using the following command:
    $ sudo kubectl proxy
  2. 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.

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.

Here are a few questions to validate your new knowledge:

  1. What are the basic Kubernetes objects that I need to create an application?
  2. How can I install a K3s cluster for my homelab?
  3. How can I use kubectl to create my applications?
  4. How can I use YAML files to create my applications?
  5. How can I use persistent volumes?
  6. How can I troubleshoot my applications?

You can refer to the following references for more information on the topics covered in this chapter: