Step 10: Deploying an application
- An infrastructure only makes sense if it supports applications that are adopted by those who use it.
- Identifying the necessary objects and creating the manifests.
- Deploying WordPress as a sample application.
- End of Cookbook V1; next steps: authentication, monitoring, backup.
Legacy version of the Kubernetes cookbook
This article is part of the first version of the cookbook (VMware and PhotonOS). A new version, on XCP-ng and Rocky Linux, is being published: this step has not yet been released; the roadmap is presented in the Step 00 - Architecture and components. The article remains online for reference.
Introduction
This article concludes this section of the site dedicated to the CookBook Kubernetes Onprem.
Designing and implementing an execution infrastructure only makes sense if it is intended to support applications that are desired by the business users.
The infrastructure must also meet the needs of developers. Proposing the architecture that seems technically the most elegant has no value if it is not adopted by those who will use it to deploy their assets.
That's why it was important to finish this tutorial on Kubernetes by implementing an application that can take advantage of everything presented previously.
As an example, the content management system (CMS) WordPress will be used. Unlike microservices applications, this is more of a "classic" software package, but it is widely used and implemented in many ecosystems and companies.
The goal is also to demonstrate that Kubernetes is not limited to specific software architectures, but can very well host all types of applications.
To better understand the following content, it is recommended that you have read the previous articles in order of their publication, at least the first part, which introduces the implemented Kubernetes environment and the main principles associated with it.
What target for the cluster, and what architectural choices should be made?
Using Terraform/OpenTofu to deploy the VMs.
Using Ansible to prepare the servers and install dependencies.
Templating the configuration files and copying them to the target environment.
Installing HAProxy as a front end and performing various preparations.
Deploying K8S, the Cilium CNI, setting up aliases and taints.
Deploying the vSphere CPI/CSI for persistent storage.
Using Traefik to expose applications externally.
Deploying CertManager to automate the certificate lifecycle.
I also strongly encourage you to familiarize yourself with the various definitions provided on this site, particularly the definitions of Kubernetes, a Pod, a Namespace, a Deployment, and a Service.
Implementing an application in K8S primarily involves manipulating objects that interact with each other to ensure the execution of the application and its accessibility to users.
Before starting the example, it is advisable to have a basic understanding of the concepts involved. The minimalist logic involves using a Namespace, within which a Deployment will manage the lifecycle of a Pod. The containers hosted in this Pod can be exposed using a Service. The ability of a Deployment to manage the Pod, and the ability of the Service to expose the Pod, will depend on a set of labels that will allow the objects to be associated with each other.
Click the image to enlarge.
Preparations
To deploy an application using Kubernetes, it is first useful to analyze the different components that make it up, so that we can then associate the Kubernetes objects that we will need to create.
In the case of WordPress, we are dealing with a fairly standard configuration for an application based on a database and a web front-end.
We quickly come to the conclusion that we will need to deploy two main components:
- A database engine: Since WordPress is compatible with several solutions, I decided to use MariaDB in version 10.5 (an older but functional version). In a containerized form, it will require high-performance persistent storage that is accessible only by one container at a time. It is not intended to be exposed outside the cluster.
- A front-end: Based on the official WordPress image, I chose version 6.6.1. The image includes a web server Apache. This part of the application also requires persistent storage, but for hosting only flat files. It is possible to imagine multiple instances of the front-end sharing this storage.
These two components will need to communicate with each other, and the front-end must be able to access its database using connection credentials.
The front-end must be accessible from the outside, and over a secure protocol HTTPS (Hyper Text Transfer Protocol Secure).
This decomposition is nothing exceptional, but it allows us to project ourselves in terms of Kubernetes objects.
Identifying the objects
For reasons of isolation and potential segmentation of administration and resources, the first Kubernetes object to use is a namespace.
This will allow us to establish an execution scope for the application.
Within this namespace, we will deploy our two components.
We will therefore have a deployment dedicated to the database, which will be responsible for managing a pod hosting the MariaDB image.
The second deployment will be dedicated to the web part and will be responsible for the lifecycle of the pods hosting the WordPress front-end instances.
The pod associated with the database will need block-type persistent storage and will therefore use a PersistentVolumeClaim (pvc), which in turn will refer to a PersistentVolume (pv).
The pods associated with the front-end will also need shared storage, which will be based on a NFS (Network File System) filesystem, but still using a PersistentVolumeClaim (pvc), and a PersistentVolume (pv).
If you are a little confused about storage, feel free to read this article from the cookbook, which details the principle of PVs and PVCs.
The database pod must be exposed within the namespace to be accessible by the front-end pods.
The front-end pods must be exposed outside the cluster, with a certificate associated with their URL.
Finally, the front-end pods will access the database pod by providing credentials that need to be stored in a Secret.
The simplest thing is to summarize everything in a diagram:
Click the image to enlarge.
Creating the objects
Now that we know what we need, we can start writing our YAML files, based on the naming conventions decided during the definition of our k8s cluster.
Namespace: 01-ns-demoapp-default-dmz.yml
The namespace can be described in the file 01-ns-demoapp-default-dmz.yml.
---
apiVersion: v1
kind: Namespace
metadata:
name: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
Very few details need to be specified in the file other than the name of the namespace (here, dev-demoapp-dmz). Don't forget the labels to clearly identify the object.
Secret: 02-secret-demoapp-bdd-dmz.yml
Next, we have the Secret. This is intended to store three confidential pieces of information.
- The root password for MariaDB.
- The database user's password.
- The database user's login name.
Indeed, we will not simply use the default root account; we will create a dedicated user.
Just because we are using containers doesn't mean we should forget about best practices.We keep our labels and can describe everything in a file 02-secret-demoapp-bdd-dmz.yml.
---
apiVersion: v1
kind: Secret
metadata:
name: secret-demoapp-bdd-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
type: Opaque
data:
mariadb-root-password: mot_de_passe_en_base64
mariadb-user-password: mot_de_passe_en_base64
mariadb-user: user_en_base64
A very important point to note about Secrets. In the end, only their name is secret... indeed, a Secret stores its information in base64 (this is the format in which you will need to enter them in the YAML). They are absolutely not encrypted.
This means that any user with access to the cluster and permission to read the contents of a Secret can retrieve the original passwords. Therefore, while using Secrets is a good security practice, you can subsequently use third-party tools like Vault to host your Secrets in a truly secure manner. However, that is not the purpose of this article; at a minimum, always ensure that objects of type Secret can only be manipulated by clearly identified and limited users.
PersistentVolumeClaim: 03-pvc-demoapp-bdd-dmz.yml
Next, we address the pvc dedicated to the database. This will allow us to provision a volume on demand within the StorageClass (sc) prd-sc-vmfs-default-na, corresponding to our CSI (Container Storage Interface) vSphere driver.
Feel free to read this article to fully understand this point.
Here is the content of the file 03-pvc-demoapp-bdd-dmz.yml:
---
kind: "PersistentVolumeClaim"
apiVersion: "v1"
metadata:
name: pvc-demoapp-bdd-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
spec:
accessModes:
- "ReadWriteOnce"
resources:
requests:
storage: "10Gi"
storageClassName: prd-sc-vmfs-default-na
In terms of information, we have the access mode ReadWriteOnce. Indeed, the MariaDB engine will not accept working on a filesystem that can be accessed simultaneously by other resources.
We are using a classic database instance model where it accesses its data through a local filesystem. However, in this case, this local filesystem will actually be a VMDK (vSphere volume) mapped to the node that will execute the pod MariaDB.
The VMDK will follow the pod if it needs to be executed on another node, for example, in case of an incident... but at time T, only one MariaDB pod will be authorized to access the volume.
(Note that this example relies on the CSI (Container Storage Interface) vSphere and therefore on a VMware storage technology (hence the VMDK). However, the logic remains applicable to any other CSI driver and third-party storage solution.)
The provisioned volume will have a size of 10Gi.
Deployment: 04-deploy-demoapp-bdd-dmz.yml
We can now address the deployment object for our database.
Here is the content of the file 04-deploy-demoapp-bdd-dmz.yml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy-demoapp-bdd-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
spec:
replicas: 1
selector:
matchLabels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
template:
metadata:
labels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
spec:
nodeSelector:
network: dmz
tolerations:
- key: "node-role.kubernetes.io/worker-dmz"
operator: "Exists"
effect: "NoSchedule"
containers:
- name: mariadb
image: mariadb:10.5
ports:
- containerPort: 3306
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1"
env:
- name: MARIADB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: secret-demoapp-bdd-dmz
key: mariadb-root-password
- name: MARIADB_DATABASE
value: wordpressdb
- name: MARIADB_USER
valueFrom:
secretKeyRef:
name: secret-demoapp-bdd-dmz
key: mariadb-user
- name: MARIADB_PASSWORD
valueFrom:
secretKeyRef:
name: secret-demoapp-bdd-dmz
key: mariadb-user-password
volumeMounts:
- name: mariadb-storage
mountPath: /var/lib/mysql
livenessProbe:
exec:
command:
- /bin/sh
- -c
- mysqladmin ping -u root -p$MARIADB_ROOT_PASSWORD
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- /bin/sh
- -c
- mysql -u root -p$MARIADB_ROOT_PASSWORD -e "SELECT 1"
initialDelaySeconds: 5
periodSeconds: 10
volumes:
- name: mariadb-storage
persistentVolumeClaim:
claimName: pvc-demoapp-bdd-dmz
In terms of specifications, we will be working with a replica count of 1, because in our model, we cannot have multiple instances of the database engine.
We are using our usual labels, except that they appear repeatedly. It is very important to understand this.
First, there are the labels associated with the Deployment object itself. Then, within the spec section, in the selector subsection, you'll find the labels that allow the deployment to associate with the pods it manages.
Finally, these labels are found in the template section and will be applied to the pod that is executed. If the labels at the template level of the pod are not consistent with the labels in the selector section of the Deployment, then it will not work (refer to the first diagram in the article).
Continuing within the template section, you'll find all the characteristics of our Pod. Specifically, it will only host a single container based on the mariadb:10.5 image.
It is also very important to fix the version of the images used. Using a tag like latest is a very bad idea, because you no longer control the potential versions of the applications associated with it. If the latest tag is updated on the Docker registry, you risk an unwanted upgrade of your database.
Another good practice is to use resource options.
This allows you to define the needs of your container based on two principles:
- Requests: These are the minimum resources required for your container to start. In the example, I specify a minimum of 512 MiB (mebibytes) of memory and 500 milliCPU, which is 0.5 vCPU (1 CPU = 1 CPU core on the host machine). This unit is somewhat arbitrary, but it ensures that the container starts with the minimum resources needed to function correctly. Be aware that this also means that if these resources are not available in the cluster, then Kubernetes will never execute the pod.
- Limits: These are the maximum resources allowed to be consumed by the container. In this example, it's 1 GiB (gibibyte) of memory and 1 vCPU. If, for some reason, the memory exceeds this limit, then Kubernetes will "kill" the container to restart it. However, there will be no interruption for the CPU, because in any case, the container will never be able to use more than one vCPU.
It is very important to implement a policy regarding resources.
This will allow you to establish a QoS (Quality of Service) that can have three settings:
- Guaranteed: Your resources set as request are equal to your resources set as limits. In this way, you guarantee the execution of your applications with the same level of resources, and the cluster will ensure that it always has sufficient availability (up to the maximum possible). However, you may waste resources. If your containers do not consume what you have declared, because you have fixed them, especially at the request level, the cluster considers this as a mandatory reservation that cannot be changed.
- Burstable: Your request values are less than your limits. In this way, you allow your pods to exceed what they are supposed to consume, up to a certain limit. This allows you to optimize resource usage further by reducing the cluster's ability to guarantee everything you need.
- BestEffort: You do not set anything; there are no request values and no limits. This is not recommended because your cluster, without any instructions, will simply do its best, with the risk that everything interferes with each other.
Click the image to enlarge.
The worst thing is to set nothing (Best Effort). It should be remembered that a Kubernetes infrastructure is designed to run a large number of applications. You need to maintain control over your consumption; otherwise, some containers may penalize others.
The env section allows you to specify all the environment variables that can be passed to the container. Simply refer to the documentation for the MariaDB image, which provides the names to use.
The subtlety is that while some variables are set directly in the deployment, such as the database name via MARIADB_DATABASE, others, which are more critical, point to our Secret created previously.
Even though a secret does not encrypt its content, using it allows you to create a deployment file that contains no passwords or sensitive data. It can therefore be freely shared. The person who writes it does not need to know the database credentials.
We continue with the volumeMounts section. The goal is to associate a volume (whose reference is mentioned later in the file) with the mount point inside the container, which is /var/lib/mysql here.
What follows is very interesting and very important. It involves defining the probes used to allow Kubernetes to know the status of the container.
There are two types of probes.
- livenessProbe: This probe determines whether the container is healthy or not. There may be cases where the process associated with the container is still running, but it is nevertheless faulty and does not respond correctly... in this case, Kubernetes keeps a container that no longer responds to the requested service alive. Using a probe of type livenessProbe allows K8S to execute a command inside the container, and based on the output, make the decision to restart the container (and therefore the pod). In this case, we are performing a ping mysql command, 30 seconds after the container starts, and then executed every 10 seconds.
- readinessProbe: This probe determines whether the container is ready to accept requests. It is possible to be in a situation where the container has started, it responds to its livenessProbe, but it is not yet ready to process requests. This is often the case with Java applications, for example, which require a certain amount of time and specific conditions before they can handle processing. In this case, we are making a request to the database. If the request succeeds, then Kubernetes will route traffic to the pod; if it does not succeed, the pod will be put in a notready state, and requests will be queued.
To summarize our example, we continuously ensure that the mariadb engine is running. If it is, the container remains alive, and we ensure that the engine can respond to requests.
Click the image to enlarge.
The use of probes is extremely important. Not using them exposes you to having phantom containers running that do not fulfill their role.
Finally, we define the volume. This directly references our pvc. The deployment will therefore use the pvc, which in turn will provision the pv within our sc. This volume will be named mariadb-storage and will then be mounted at the path /var/lib/mysql of the container. In essence, it's the VMDK provisioned by the vSphere CSI driver that will be mapped.
It's time to pause for a moment before continuing. This deployment is much more complex than the one presented in the definition. This is an important point to understand, because a Kubernetes object does not necessarily impose all the properties that can be associated with it.
Only a few minimum attributes are required... which doesn't mean you should settle for the basics. The use of probes and resources is, for example, very important to integrate.
Service: 05-service-demoapp-bdd-dmz.yml
The database needs to be accessible to the front-end, so we need to expose it via a service.
This is described in the file 05-service-demoapp-bdd-dmz.yml:
apiVersion: v1
kind: Service
metadata:
name: service-demoapp-bdd-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: bdd
spec:
type: ClusterIP
ports:
- port: 3306
targetPort: 3306
selector:
environment: dev
network: dmz
application: demoapp
tiers: bdd
In this file, the most important part is the label, within the selector section. As with the deployment, these labels must match those defined at the level of the pod.
This allows the service to redirect traffic arriving on port 3306 to port 3306 of the pod.
The MariaDB part is now complete.
We can move on to the front-end.
PersistentVolume: 06-pv-demoapp-front-dmz.yml
We start by creating a PersistentVolume (pv). Unlike the database, we are not using a StorageClass (sc), so we will not be able to have automatic volume creation.
Here is the content of the file 06-pv-demoapp-front-dmz.yml:
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteMany
nfs:
server: 192.168.10.152
path: /Volume1/nfsshare/kub.coolcorp.priv/namespaces/dev-demoapp-dmz/wordpress
In this file, we specify the characteristics of our pv. Specifically, it allows access from multiple pods with the ReadWriteMany option and a capacity of 10GB.
Since we are not using a sc, we directly indicate that this pv uses an NFS (Network File System) server, specifying the IP address of the server and the associated export. This, of course, implies that you have this type of storage available and configured.
In terms of NFS access, the export must be authorized to be accessible to all nodes in the cluster that may run the WordPress pods.
Click the image to enlarge.
(Update 06/16/2024) Please note that in this example, I am manipulating a persistent volume directly without using a standard CSI driver. While this is still possible at the time of writing this article, it will not be allowed in future versions of Kubernetes. A CSI driver will be required. For more information on how to map an NFS volume in this way, please refer to this article dedicated to the subject.
Currently, I am keeping this legacy method in this part of the cookbook because there are still many examples of this type, but I encourage you to switch to a persistent volume based on a CSI as soon as possible.
PersistentVolumeClaim: 07-pvc-demoapp-front-dmz.yml
We are switching directly using the persistent volume claim, which will logically reference the volume that we just declared.
Here is the content of the file 07-pvc-demoapp-front-dmz.yml:
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 10Gi
volumeName: pv-demoapp-front-dmz
Feel free to visit this page for more information on how storage works in Kubernetes.
Deployment: 08-deploy-demoapp-front-dmz.yml
Now it's time for the Deployment associated with the front end.
Here is the content of the file 08-deploy-demoapp-front-dmz.yml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
replicas: 2
selector:
matchLabels:
environment: dev
network: dmz
application: demoapp
tiers: front
template:
metadata:
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
nodeSelector:
network: dmz
tolerations:
- key: "node-role.kubernetes.io/worker-dmz"
operator: "Exists"
effect: "NoSchedule"
containers:
- name: wordpress
image: wordpress:6.6.1
ports:
- containerPort: 80
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
env:
- name: WORDPRESS_DB_HOST
value: service-demoapp-bdd-dmz
- name: WORDPRESS_DB_NAME
value: wordpressdb
- name: WORDPRESS_DB_PASSWORD
valueFrom:
secretKeyRef:
name: secret-demoapp-bdd-dmz
key: mariadb-user-password
- name: WORDPRESS_DB_USER
valueFrom:
secretKeyRef:
name: secret-demoapp-bdd-dmz
key: mariadb-user
volumeMounts:
- name: wordpress-storage
mountPath: /var/www/html
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 10
volumes:
- name: wordpress-storage
persistentVolumeClaim:
claimName: pvc-demoapp-front-dmz
I will not present it in as much detail as the one used for the database.
We see the same principles here, with the continued importance of labels, especially between those used in the selector section and those used in the template section.
Unlike the database, we allow two replicas. This means that two pods will be constantly running. Given the use of a shared file system via our NFS volume, this is not a problem.
A point I did not address in the previous deployment is that we are also using the concepts of node selector and toleration here.
This is directly related to the use of a single Kubernetes cluster to host assets intended for both internal and web exposure. Feel free to review the cluster presentation and this article to understand the principle of taint/toleration.
In the case of the selector, we are instructing Kubernetes to run the pods on nodes with the label network: dmz.
Adding the toleration allows Kubernetes to override the taint that is set on our DMZ nodes.
This provides a double assurance to avoid having a pod run in the DMZ when it is not intended to be exposed in that zone.
In our example, it is assumed and desired to use the DMZ, so we place these options in the deployment.
We also have an env section to provide the WordPress containers (version 6.6.1) with the elements they need, including access to the database. We are of course using the same Secret as for the database since it contains the same information.
Again, you only need to review the image documentation on Docker Hub to get a description of the role of each variable.
Resources are set both in admission and limits, for the same reasons as for the database.
livenessProbe and readinessProbe probes are used. This could be optimized here, because the tests performed are the same... which is not very useful... but I wasn't more inspired...
Of course, we have our pvc at the end of the file, which will associate the pv NFS with a volume wordpress-storage, which in turn will be mounted in the /var/www/html directory of each container.
Note the difference with the database. The way volumes are mapped is the same, but the purpose is different. Here, it's an NFS share that will be mapped to each container.
Service: 09-service-demoapp-front-dmz.yml
The frontends must of course be exposed, hence the use of a service.
Here is the content of the file 09-service-demoapp-front-dmz.yml:
---
apiVersion: v1
kind: Service
metadata:
name: service-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
type: ClusterIP
ports:
- port: 80
targetPort: 80
selector:
environment: dev
network: dmz
application: demoapp
tiers: front
There's nothing special to declare here, except for the usual importance of labels. In our case, port 80 will be used on the service side to then forward to port 80 of each pod that meets the label selection criteria.
Issuer: 10-issuer-demoapp-front-dmz.yml
This is not finished, because while the database is only intended to be exposed internally within the cluster, this is not the case for the frontend.
Therefore, we need to address the HTTPS exposure part.
To do this, we will first need to generate a certificate. We will therefore rely on an object of type Issuer provided by CertManager. We are reusing all the logic explained in this article when we implemented CertManager.
As explained in the dedicated article, we create an Issuer that is responsible for requesting Let's Encrypt and requesting a certificate via the ACME protocol.
Here is the content of the file 10-issuer-demoapp-front-dmz.yml:
---
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
name: issuer-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
acme:
email: [email protected]
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: sec-issuer-demoapp
solvers:
- http01:
ingress:
class: traefik-dmz
podTemplate:
metadata:
labels:
network: dmz
spec:
nodeSelector:
network: dmz
tolerations:
- key: "node-role.kubernetes.io/worker-dmz"
operator: "Exists"
effect: "NoSchedule"
ingressTemplate:
metadata:
labels:
network: dmz
Certificate/Ingress: 11-ing-demoapp-front-dmz.yml
We can now proceed with the file 11-ing-demoapp-front-dmz.yml, which will contain both the certificate definition and the ingress configuration.
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: cert-demoapp-front
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
spec:
commonName: demoapp.myprivatelab.tech
secretName: sec-certificate-demoapp
dnsNames:
- demoapp.myprivatelab.tech
issuerRef:
kind: Issuer
name: issuer-demoapp-front-dmz
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ing-demoapp-front-dmz
namespace: dev-demoapp-dmz
labels:
environment: dev
network: dmz
application: demoapp
tiers: front
annotations:
traefik.ingress.kubernetes.io/router.entrypoints: web,websecure
ingressClassName: traefik-dmz
traefik.ingress.kubernetes.io/router.tls: "true"
spec:
ingressClassName: traefik-dmz
tls:
- hosts:
- demoapp.myprivatelab.tech
secretName: sec-certificate-demoapp
rules:
- host: demoapp.myprivatelab.tech
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: service-demoapp-front-dmz
port:
number: 80
For the certificate, we are using the Issuer. The certificate obtained with its private key will be stored in the secret sec-certificate-demoapp.
The chosen URL is demoapp.myprivatelab.tech. For the challenge to succeed and for the certificate to be issued by Let's Encrypt, the DNS entry must be operational. It is necessary that the resolution works before submitting the certificate request. Once again, feel free to read this section of the cookbook to fully understand the process.
We finish with the Ingress. This will be controlled by the IngressController Traefik deployed in the DMZ. That's why we use the annotations section. We are following the same logic as explained here.
We apply the TLS configuration by associating the secret that contains the certificate information.
We also ensure that all requests for the URL are redirected to port 80 of the service service-demoapp-front-dmz.
Now we have everything, and we have all the YAML files needed to create all the objects required for our test application.
NetworkPolicy: 12-netpol-demoapp-default-dmz.yml
However, we can still mention one last file, which is optional but highly recommended.
This is the file 12-netpol-demoapp-default-dmz.yml, which will allow us to establish a NetworkPolicy:
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: netpol-demoapp-default-dmz
namespace: dev-demoapp-dmz
spec:
podSelector:
matchLabels:
application: demoapp
tiers: bdd
ingress:
- from:
- podSelector:
matchLabels:
application: demoapp
tiers: front
ports:
- protocol: TCP
port: 3306
policyTypes:
- Ingress
A NetworkPolicy, which has been mentioned very little so far, is a native Kubernetes object that allows you to implement network filtering rules, similar to a firewall, but in a slightly different way.
Support for NetworkPolicy depends on the chosen CNI driver. In our case, Cilium supports it, and even better, it can use an improved version, but which is no longer part of the default API.
I will stick to a basic NetworkPolicy.
The idea is not to go into detail; this article is already long enough. But to summarize briefly, a NetworkPolicy allows you to define rules for incoming traffic (Ingress) or outgoing traffic (Egress) of one or more pods.
You can use labels, and various filtering criteria are possible up to level 3 (filtering by IP address and port).
However, be aware that as soon as at least one rule is specified in the Ingress and/or Egress, all traffic not explicitly allowed by that rule is implicitly denied.
In our example, I kept it basic.
I simply want to ensure that the database can only be accessed by pods with labels associated with my WordPress frontends.Therefore, I am only using an Ingress section on the database pod (filtering incoming traffic to the mariadb pod).
Only traffic originating from the frontend pods and destined for port 3306 is allowed.
Thus, no other pods that do not meet the label criteria of the NetworkPolicy will be able to access the database.
The use of NetworkPolicy is important because, by default in Kubernetes, everyone can communicate with everyone else, even if you are in different namespaces.
It quickly becomes important to filter all this… but it's important to be careful.
This is not a firewall either. Too many network policies or overly complex network policies can lead to incidents.Always make sure you fully understand what implementing a network policy entails.I know that Cilium brings many improvements in this area, and it is becoming possible to go up to level 7, the application layer, to create rules.
But in this case, we switch to the API specific to Cilium.
I am not yet knowledgeable enough about this topic, but perhaps a dedicated article can be written later.
Launching the application
Now, all that remains is to launch our application.
We could have created a single YAML file to declare all our objects, but I do not recommend this practice. It can quickly become unreadable, and separating the files by object has always seemed interesting to me.
Especially since with Kubernetes, you only need to apply the command kubectl apply -f, specifying the folder containing the YAML files for all the files to be considered.
Click the image to enlarge.
(I had previously run the command once before taking the screenshot, which is why in the image, the return of the objects appears as unchanged, except for the netpol, which was not yet deployed. You can recall the command as many times as you like. K8S will only apply changes if it detects a difference between what is already in place and what is described in your files.)
Note that in my case, I number my files, but in reality, Kubernetes doesn't care about that at all. As long as it finds all the necessary YAML files in the folder and there are no inconsistencies, it will process them all.
The magic happens quickly; it only takes a few minutes to download the images, and then our WordPress site is available at its URL, with its certificate.
Click the image to enlarge.
If we list the pods in the namespace using the command kubectl get pod -n dev-demoapp-dmz -o wide
Click the image to enlarge.
We can see a database pod and two front-end pods, all running on nodes in the DMZ.
Note that, without me having to specify it, K8S automatically distributed the two front-end pods across different nodes. You should know that it is possible to enforce this behavior by adding an affinity section in the Deployments. Several rules are possible, but I won't cover them here. Without your instructions, K8S will always try to distribute resources as efficiently as possible, but it can be a good practice to also manage this aspect.
If we look at which node the database is running on, in VMware, we can see the 10 GB VMDK mapped to the VM.
Click the image to enlarge.
On the NFS share, we find the files directly.
Click the image to enlarge.
By connecting to the Traefik dashboard, we can see our Ingress and the routing rule that points to our service.
Click the image to enlarge.
Conclusion
This cookbook is finally complete. I have tried to thoroughly describe the entire process of setting up a Kubernetes cluster and running an application. I have attempted to stay as close as possible to production conditions, using industrialization and automation tools such as Terraform and Ansible in the construction of the cluster.
Each article also aimed to gradually introduce the various principles that can be found within Kubernetes, with a focus on networking and storage.
I emphasize the importance of designing your architecture and logic in accordance with those who will operate/use the cluster. It is important to be rigorous and methodical, understanding what you are doing and, above all, why you are doing it.
Leveraging namespaces, establishing a naming policy, outlining your architecture, and defining mandatory labels are activities that should not be overlooked. Whether you find yourself on a vanilla cluster like this one or a hosted cluster, the difficulty of Kubernetes lies not so much in deploying servers as in properly utilizing the ecosystem associated with it.
I hope this cookbook will be useful to some, and of course, I am open to criticism and would be delighted to receive feedback on the subject.
I am far from having all the answers, and it is quite possible that I may have been mistaken in certain explanations or that there are better ways to do things.Of course, with ChatGPT around, it is becoming increasingly easy to achieve a result by using prompts. I myself regularly use AI in my work.
But without my experience and numerous trials, I would never have been able to complete the writing of this cookbook.
Kubernetes is learned through iteration and continuous improvement. Don't hesitate to test, evaluate, and start over… anyway, it will never be perfect. Kubernetes evolves so quickly that your knowledge is constantly being revised… without necessarily having to question everything.
There are now many other things to explore, such as authentication within the cluster, monitoring, backup of the configuration and persistent volumes, as well as adding new CSI drivers.
I invite you to continue with the upgrade procedure, which is described in a first theoretical part and then in a second practical part.
You can also extend the cluster with other worker nodes. An example is available at this URL.