Skip to content
ImagineWorld

Kubernetes Bootcamp

node_idnode-book_kubernetes-an-enterprise-guide_chapter-03-kubernetes-bootcamp
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleKubernetes Bootcamp
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The previous chapter introduced you to deploying Kubernetes clusters using KinD (Kubernetes in Docker), which is useful for creating a development cluster on a single machine using containers instead of virtual machines. This approach reduces the system resource requirements and simplifies the entire setup process. We covered the installation and configuration of KinD, creating clusters, including add-ons like Ingress controllers, Calico as the CNI, and using persistent storage.

We understand that many of you have experience with Kubernetes, whether it’s running clusters in production or experimenting with tools like kubeadm, minikube, or Docker Desktop. Our intention with this book is to go beyond the fundamentals of Kubernetes, which is why we didn’t want to reiterate all the basics. Instead, we’ve included this chapter as a bootcamp for those who are new to Kubernetes or have only had limited exposure to it.

In this chapter, we will explore the essential components of a Kubernetes cluster, including the control plane and worker nodes. We will provide detailed explanations of each Kubernetes resource and its respective use cases. If you have previous experience with Kubernetes and feel comfortable using kubectl, as well as an understanding of Kubernetes resources like DaemonSets, StatefulSets, and ReplicaSets, this chapter can serve as a helpful review before moving on to Chapter 4, where we will dive into Services, Load Balancing, ExternalDNS, Global Balancing, and K8GB.

Since this is a bootcamp chapter, we won’t get into every topic in detail. However, by the end of this chapter, you should have a solid understanding of the foundational concepts of Kubernetes, which will be crucial for comprehending the remaining chapters. Even if you already possess a strong background in Kubernetes, you may find this chapter valuable as a refresher before we get into more advanced topics. In this chapter, you will learn the following topics:

  • An overview of Kubernetes components
  • Exploring the control plane
  • Understanding the worker node components
  • Interacting with the API server
  • Introducing Kubernetes resources

By the end of this chapter, you will have a solid understanding of the most commonly used cluster resources. Understanding Kubernetes resources is important for both cluster operators and cluster administrators.

This chapter has no technical requirements.

If you want to execute commands while learning about the resources, you can use the KinD cluster that was deployed in the previous chapter.

Understanding the components of systems in an infrastructure is essential for delivering services effectively. In today’s wide landscape of installation options, many Kubernetes users may not have felt the need to fully comprehend the integration of different Kubernetes components.

Just a few years ago, establishing a Kubernetes cluster involved the manual installation and configuration of each component. This process presented a steep learning curve and often resulted in frustration. As a result, many individuals and organizations concluded that “Kubernetes is overly complex.” However, the benefit of manual installation was the in-depth understanding it provided regarding the interaction between each component. If any issues arose within the cluster after installation, you would have a clear understanding of where to investigate.

To understand how Kubernetes components work together, you must first understand the different components of a Kubernetes cluster.

The following diagram is from the http://Kubernetes.io site and shows a high-level overview of a Kubernetes cluster component:

Figure 5.1 – Kubernetes cluster components

Figure 3.1: Kubernetes cluster components

As you can see, the Kubernetes cluster is made up of several components. As we progress through the chapter, we’ll discuss these components and the role they play in a Kubernetes cluster.

The control plane, as its name suggests, has authority over every aspect of a cluster. In the absence of a functioning control plane, the cluster loses its ability to schedule workloads, create new deployments, and manage Kubernetes objects. Recognizing the criticality of the control plane, it is highly advisable to deploy with high availability (HA) support, deploying a minimum of three control plane nodes. Many production environments even utilize more than three control plane nodes, but the key principle is to have an odd number of nodes, which is required so we can maintain a highly available control plane if we lose a single etcd node.

Now, let’s delve into the importance of the control plane and its components, providing a comprehensive understanding of their pivotal role in a functioning cluster.

The first component to understand in a cluster is the kube-apiserver component. Since Kubernetes is application programming interface (API)-driven, every request that comes into a cluster goes through the API server. Let’s look at a simple get nodes request using an API endpoint, using the IP address for the control plane, which, in an enterprise, is usually fronted by a load balancer. In our example, our load balancer has an entry for the three control plane nodes on 10.240.100.100:

https://10.240.100.100:6443/api/v1/nodes?limit=500

If you attempt to make an API call without any credentials, you will receive a permission denied request. Using a pure API request directly is something that is very common when creating a pipeline for application deployment or even a Kubernetes add-on component. However, the most common method for users to interact with Kubernetes is the kubectl utility.

Every command that is issued using kubectl calls an API endpoint behind the scenes. In the preceding example, if we executed a kubectl get nodes command, an API request would be sent to the kube-apiserver process using the address 10.240.100.100 on port 6443.

The API call requested the /api/vi/nodes endpoint, which returned a list of the nodes in the cluster:

NAME STATUS ROLES AGE VERSION
home-k8s-control-plane Ready control-plane,master 45d v1.27.3
home-k8s-control-plane2 Ready control-plane,master 45d v1.27.3
home-k8s-control-plane3 Ready control-plane,master 45d v1.27.3
home-k8s-worker Ready worker 45d v1.27.3
home-k8s-worker2 Ready worker 45d v1.27.3
home-k8s-worker3 Ready worker 45d v1.27.3

In the absence of a functioning API server, all requests directed to your cluster will fail. Therefore, it becomes crucial to ensure the continuous operation and health of the kube-apiserver.

By running three or more control plane nodes, we minimize any potential impact that could be caused by the loss of a control plane node.

Remember, from the last chapter, that when running more than one control plane node, you need to have a load balancer in front of the cluster’s API server. The Kubernetes API server can be fronted by most standard solutions, including F5, HAProxy, and Seesaw.

Describing etcd as the foundation of your Kubernetes cluster would not be an overstatement. etcd functions as a robust and highly efficient distributed key-value database that Kubernetes relies on to store all cluster data. Every resource present within the cluster is associated with a specific key in the etcd database. If you can access the node or pod that hosts etcd, you will be able to use the etcdctl executable to explore all the keys stored within the database. The code snippet provided below offers an example extracted from a cluster based on KinD:

etcdctl-3.5.12 --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --key=/etc/kubernetes/pki/etcd/server.key --cert=/etc/kubernetes/pki/etcd/server.crt get / --prefix --keys-only

The output from the preceding command contains too much data to list it all in this chapter. A base KinD cluster will return approximately 314 entries.

All keys start with /registry/<resource>. For example, one of the keys that was returned is the ClusterRole for the cluster-admin key, as follows: /registry/clusterrolebindings/cluster-admin.

We can use the key name to retrieve the value using the etcdctl utility by slightly modifying our previous command, as follows:

etcdctl-3.5.12 --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --key=/etc/kubernetes/pki/etcd/server.key --cert=/etc/kubernetes/pki/etcd/server.crt get /registry/clusterrolebindings/cluster-admin

The output will contain characters that cannot be interpreted by your shell, but you will get an idea of the data stored in etcd. For the cluster-admin key, the output shows us the following:

/registry/clusterrolebindings/cluster-admin
k8s
2
rbac.authorization.k8s.io/v1ClusterRoleBinding▒
▒
cluster-admin"*$7b235e81-52de-4001-b354-994dad0279ee2▒▒▒▒Z,
rbac-defaultsb3otstrapping
+rbac.authorization.kubernetes.io/autoupdatetrue▒▒
kube-apiserverUpdaterbac.authorization.k8s.io/v▒▒▒▒FieldsV1:▒
▒{"f:metadata":{"f:annotations":{".":{},"f:rbac.authorization.kubernetes.io/autoupdate":{}},"f:labels":{".":{},"f:kubernetes.io/bootstrapping":{}}},"f:roleRef":{},"f:subjects":{}}B4
Grouprbac.authorization.k8s.iosystem:masters"7
rbac.authorization.k8s.io
cluster-admin" ClusterRole

We describe the entries in etcd to offer an understanding of how Kubernetes stores and utilizes data to manage cluster objects. While you’ve already observed the direct database output for the cluster-admin key, in typical scenarios, you would utilize the command kubectl get clusterrolebinding cluster-admin -o yaml to query the API server for the same data. Using kubectl, the command would yield the following information:

Figure 3.2: kubectl ClusterRoleBinding output

If you look at the output from the kubectl command and compare it with the output from the etcdctl query, you will see matching information. You will rarely have to interact with etcd directly; instead, you will execute kubectl commands, and the request will go to the API server, which then queries the etcd database for the resource’s information.

It’s worth noting that while etcd is by far the most used backend database for Kubernetes, it isn’t the only one. The k3s project, which was originally built to strip down Kubernetes for edge use cases, replaced etcd with relational databases. When we dive into vclusters, which use k3s, we’ll see that it uses SQLite instead of etcd.

As its name suggests, the kube-scheduler component oversees the allocation of pods to nodes. Its primary task is to consistently monitor pods that have yet to be assigned to any specific node. The scheduler then assesses the resource requirements of each pod to determine the most suitable placement. This assessment takes multiple factors into account, including the availability of node resources, constraints, selectors, and affinity/anti-affinity rules. Nodes that satisfy these requirements are considered feasible nodes. Finally, from the resulting list of compatible nodes, the scheduler chooses the most appropriate one for scheduling the pod.

The Kubernetes Controller Manager is a central control system in the Kubernetes control plane; it’s responsible for managing and coordinating other controllers that handle specific tasks for the cluster.

The Controller Manager contains multiple controllers, each dedicated to a specific function within the cluster. These controllers continuously monitor the cluster’s current state and adapt dynamically to maintain the desired configuration.

All of the controllers are contained in a single executable, reducing complexity and management. Some of the controllers included are shown in Table 3.1.

Each controller provides a unique function to a cluster, and each controller and its function is listed here:

ControllerResponsibilities
EndpointsMonitors new services and creates endpoints to the pods with matching labels
NamespaceMonitors actions for namespaces
NodeMonitors the status of nodes in the cluster, detecting node failures or additions, and taking appropriate actions to maintain the desired number of nodes
ReplicationMonitors the replicas for pods, taking action to either remove a pod or add a pod to get to the desired state
Service AccountsMonitors Service accounts

Table 3.1: Controllers and their functions

Each controller runs a non-terminating (never-ending) control loop. These control loops monitor the state of each resource, making any changes required to normalize the state of the resource. For example, if you needed to scale a deployment from one to three nodes, the replication controller would notice that the current state has one pod running, and the desired state is to have three pods running. To move the current state to the desired state, two additional pods would be requested by the replication controller.

This is one component that you may not have run into, depending on how your clusters are configured. Similar to the kube-controller-manager component, this controller contains four controllers in a single binary.

The cloud controller provides integrations specific to a particular cloud provider’s Kubernetes service, enabling the utilization of cloud-specific functionalities such as load balancers, persistent storage, auto-scaling groups, and other features.

Worker nodes, as implied by their name, have the duty of carrying out tasks within a Kubernetes cluster. In our previous conversation about the kube-scheduler element in the control plane, we emphasized that when a new pod requires scheduling, the kube-scheduler selects the suitable node for its execution. The kube-scheduler relies on data provided by the worker nodes to make this determination. This data is regularly updated to ensure a distribution of pods throughout the cluster, making the most of the cluster resources.

Each worker node has two main components, kubelet and kube-proxy.

You may hear a worker node referred to as a kubelet. The kubelet is an agent that runs on all worker nodes, and it is responsible for ensuring that containers are running and healthy on the node.

Contrary to the name, kube-proxy is not a proxy server at all (though it was in the original version of Kubernetes).

Depending on the CNI deployed in your cluster, you may or may not have a kube-proxy component on your nodes. CNIs like Cilium can be run with kube-proxy or in a kube-proxyless mode. In our KinD clusters, we have deployed Calico, which relies on the presence of kube-proxy.

When kube-proxy is deployed, its main purpose is to oversee network connectivity for pods and services in the cluster, providing network traffic routing to the destination pod(s).

Each node also needs a container runtime. A container runtime is responsible for running the containers. The first thing you might think of is Docker, and while Docker is a container runtime, it is not the only runtime option available. Over the last several years, other options have replaced Docker as the preferred container runtime for clusters.

The two most prominent Docker replacements are CRI-O and containerd. At the time of writing this chapter, KinD only offers official support for Docker and Red Hat’s Podman.

As we mentioned earlier, you interact with the API server using either direct API requests or the kubectl utility. We will focus on using kubectl for the majority of our interaction in this book, but we will call out using direct API calls wherever applicable.

kubectl is a single executable file that allows you to interact with the Kubernetes API using a command-line interface (CLI). It is available for most major operating systems and architectures, including Linux, Windows, and macOS.

Note: We have already installed kubectl using the KinD script that created our cluster in Chapter 2. Installation instructions for most operating systems are located on the Kubernetes site at https://kubernetes.io/docs/tasks/tools/install-kubectl/. Since we are using Linux as our operating system for the exercises in the book, we will cover installing kubectl on a Linux machine. Follow these steps:

  1. To download the latest version of kubectl, you can run a curl command that will download it, as follows:
    curl -LO https://storage.googleapis.com/kubernetes-release/release/\`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt\`/bin/linux/amd64/kubectl
  2. After downloading, you need to make the file executable by running the following command:
    chmod +x ./kubectl
  3. Finally, we will move the executable to our path, as follows:
    sudo mv ./kubectl /usr/local/bin/kubectl

You now have the latest kubectl utility on your system and can execute kubectl commands from any working directory.

Kubernetes is updated about every 4 months. This includes upgrades to the base Kubernetes cluster components and the kubectl utility. You may run into a version mismatch between a cluster and your kubectl command, requiring you to either upgrade or download your kubectl executable. You can always check the version of both by running a kubectl version command, which will output the version of both the API server and the kubectl client. The output from a version check is shown in the following code snippet – please note, your output may differ from our example output:

Client Version: v1.30.0-6+43a0480e94cee1
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0-6+43a0480e94cee1

As you can see from the output, the kubectl client is running version 1.30.0 and the cluster is running 1.30.0. A minor version difference in the two will not cause any issues. In fact, the official supported version difference is within one major version release. So, if your client is running version 1.29 and the cluster is running 1.30.0, you would be within the supported version difference. While this may be supported, it doesn’t mean that you won’t run into issues if you are trying to use any new commands or resources included in the higher version. In general, you should try to keep your cluster and client version in sync to avoid any issues.

Through the remainder of this chapter, we will discuss Kubernetes resources and how you interact with the API server to manage each one. But before diving into the different resources, we wanted to mention one commonly overlooked option of the kubectl utility: the verbose option.

When you execute a kubectl command, the only outputs you will see by default are any direct responses to your command. If you were to look at all pods in the kube-system namespace, you would receive a list of all pods. In most cases, this is the desired output, but what if you issued a get Pods request and received an error from the API server? How could you get more information about what might be causing the error?

By adding the verbose option to your kubectl command, you can get additional details about the API call itself and any replies from the API server. Often, the replies from the API server will contain additional information that may be useful to find the root cause of the issue.

The verbose option has multiple levels ranging from 0 to 9; the higher the number, the more output you will receive.

The following screenshot has been taken from the Kubernetes site, detailing each level and what the output will include:

Figure 5.5 – Verbosity description

Figure 3.3: Verbosity description

You can experiment with the levels by adding the -v or --v option to any kubectl command.

The CLI allows you to interact with Kubernetes in an imperative and declarative manner. Using an imperative command involves you telling Kubernetes what to do—for example, kubectl run nginx --image nginx. This tells the API server to create a new pod called nginx that runs an image called nginx. While imperative commands are useful for development and quick fixes or testing, you will use declarative commands more often in a production environment. In a declarative command, you tell Kubernetes what you want. To use declarative commands, you send a manifest to the API server, written in either JavaScript Object Notation (JSON) or YAML Ain’t Markup Language (YAML), which declares what you want Kubernetes to create.

kubectl includes commands and options that can provide general cluster information or information about a resource. The table below contains a cheat sheet of commands and what they are used for. We will use many of these commands in future chapters, so you will see them in action throughout the book:

Cluster Commands

api-resources

Lists supported API resources

api-versions

Lists supported API versions

cluster-info

Lists cluster information, including the API server and other cluster endpoints

Object Commands

get

Retrieves a list of all objects (i.e., pods, ingress, etc.)

describe

Provides details for the object

logs

Retrieve the logs for a pod

edit

Edits an object interactively

delete

Deletes an object

label

Labels an object

annotate

Annotates an object

run

Creates a pod

Table 3.2: Cluster and object commands

With an understanding of each Kubernetes component and how to interact with the API server using imperative commands, we can now move on to Kubernetes resources and how we use kubectl to manage them.

In this section, we will provide a substantial amount of information. However, as this is a bootcamp, we won’t go into exhaustive details about each resource. It’s worth noting that each resource could easily warrant its own dedicated chapter or even multiple chapters in a book. Since numerous books on basic Kubernetes already cover these resources extensively, we will focus on the essential aspects necessary for a basic understanding of each resource. As we progress through the subsequent chapters, we will supplement additional details about the resources as we expand our cluster using the exercises provided in the book.

Prior to delving into a comprehensive understanding of Kubernetes resources, let’s begin by introducing the concept of Kubernetes manifests.

The files that we will use to create Kubernetes resources are referred to as manifests. A manifest can be created using YAML or JSON—most manifests use YAML, and that is the format we will use throughout the book.

It’s important to note that while we are working with YAML files, kubectl will convert all YAML into JSON when interacting with your API server. All API calls are made with JSON, even if the manifests are written in YAML.

The content of a manifest will vary depending on the resource, or resources, that will be created. At a minimum, all manifests require a base configuration that includes apiVersion, the kind of resource, and metadata fields, as can be seen here:

apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: grafana
name: grafana
namespace: monitoring

The preceding manifest alone is not complete; we are only showing the beginning of a full Deployment manifest. As you can see in the file, we start with the three required fields that all manifests are required to have: the apiVersion, kind, and metadata fields.

You may also notice that there is a format for fields in the file. YAML is very format-specific, and if the format of any line is off by even a single space, you will receive an error when you try to deploy the manifest. This takes time to get used to, and even after creating manifests for a long time, formatting issues will still pop up from time to time.

When you want to add or delete something from a cluster, you are interacting with Kubernetes resources. This interaction is how you declare your desired state for the resource, which may be to create, delete, or scale a resource. Based on the desired state, the API server will make sure that the current state equals the desired state. For example, if you have a deployment that starts with a single replica, you can change the deployment resource from 1 to 3 replicas. When the API server sees that the current state is 1, it will scale the deployment out to 3 replicas by creating the additional 2 pods.

To retrieve a list of resources a cluster supports, you can use the kubectl api-resources command. The API server will reply with a list of all resources, including any valid short name, namespace support, and supported API group.

There are approximately 58 base resources included with a Kubernetes cluster, but it’s very common to have many more than 58 in a production cluster. Many add-on components, like Calico, will extend the Kubernetes API with new objects. As a cluster has different add-ons deployed in the cluster, don’t be surprised at 100+ resources in a list.

An abbreviated list of the most common resources is shown below:

NAMESHORT NAMESAPI VERSIONNAMESPACED
apiservicesapiregistration.k8s.io/v1FALSE
certificatesigningrequestsCsrcertificates.k8s.io/v1FALSE
clusterrolebindingsrbac.authorization.k8s.io/v1FALSE
clusterrolesrbac.authorization.k8s.io/v1FALSE
componentstatusesCsv1FALSE
configmapsCmv1TRUE
controllerrevisionsapps/v1TRUE
cronjobsCjbatch/v1TRUE
csidriversstorage.k8s.io/v1FALSE
csinodesstorage.k8s.io/v1FALSE
csistoragecapacitiesstorage.k8s.io/v1TRUE
customresourcedefinitionscrd,crdsapiextensions.k8s.io/v1FALSE
daemonsetsDsapps/v1TRUE
deploymentsDeployapps/v1TRUE
endpointsEpv1TRUE
endpointslicesdiscovery.k8s.io/v1TRUE
eventsEvv1TRUE
eventsEvevents.k8s.io/v1TRUE
flowschemasflowcontrol.apiserver.k8s.io/v1beta3FALSE
horizontalpodautoscalersHpaautoscaling/v2TRUE
ingressclassesnetworking.k8s.io/v1FALSE
ingressesIngnetworking.k8s.io/v1TRUE
jobsbatch/v1TRUE
limitrangesLimitsv1TRUE
localsubjectaccessreviewsauthorization.k8s.io/v1TRUE
mutatingwebhookconfigurationsadmissionregistration.k8s.io/v1FALSE
namespacesNsv1FALSE
networkpoliciesNetpolnetworking.k8s.io/v1TRUE
nodesNov1FALSE
persistentvolumeclaimsPvcv1TRUE
persistentvolumespvv1FALSE
poddisruptionbudgetspdbpolicy/v1TRUE
podspov1TRUE
podtemplatesv1TRUE
priorityclassespcscheduling.k8s.io/v1FALSE
prioritylevelconfigurationsflowcontrol.apiserver.k8s.io/v1beta3FALSE
profilesprojectcalico.org/v3FALSE
replicasetsrsapps/v1TRUE
replicationcontrollersrcv1TRUE
resourcequotasquotav1TRUE
rolebindingsrbac.authorization.k8s.io/v1TRUE
rolesrbac.authorization.k8s.io/v1TRUE
runtimeclassesnode.k8s.io/v1FALSE
secretsv1TRUE
selfsubjectaccessreviewsauthorization.k8s.io/v1FALSE
selfsubjectrulesreviewsauthorization.k8s.io/v1FALSE
serviceaccountssav1TRUE
servicessvcv1TRUE
statefulsetsstsapps/v1TRUE
storageclassesscstorage.k8s.io/v1FALSE
subjectaccessreviewsauthorization.k8s.io/v1FALSE
tokenreviewsauthentication.k8s.io/v1FALSE
validatingwebhookconfigurationsadmissionregistration.k8s.io/v1FALSE
volumeattachmentsstorage.k8s.io/v1FALSE

Table 3.3: Kubernetes API resources

As this chapter functions as a bootcamp, we will provide a short overview of the resources found in Table 3.3. To effectively comprehend the following chapters, it is important for you to possess a strong understanding of the objects and their respective functions.

Some resources will also be explained in greater detail in future chapters, including Ingress, RoleBindings, ClusterRoles, StorageClasses, and more.

Most resources in a cluster are run in a namespace, and to create/edit/read them, you should supply the -n <namespace> option to any kubectl command. To find a list of resources that accept a namespace option, you can reference the output from Table 3.3. If a resource can be referenced by a namespace, the NAMESPACED column will show TRUE. If the resource is only referenced by the cluster level, the NAMESPACED column will show FALSE.

Apiservices provide the primary entry point for communication and interaction between Kubernetes components and all external resources, such as users, applications, and other services. They provide a set of endpoints that allow users and applications to perform various operations, such as creating, updating, and deleting Kubernetes resources (i.e., pods, deployments, services, and namespaces).

Apiservices handle the authentication, authorization, and validation of requests, allowing only authorized users and applications to access or modify resources. They also handle resource versioning and other critical aspects of a Kubernetes cluster.

They can also extend Kubernetes functionality by developing custom controllers, operators, or other components that interact with the API Services to manage and automate various aspects of the cluster’s behavior. One example of this is our CNI, Calico, which adds 31 extra api-resources to a cluster.

A CertificateSigningRequest (CSR) allows you to request a certificate from a certificate authority. These are typically used to obtain trusted certificates for securing communication within a Kubernetes cluster.

A ClusterRole is a collection of permissions that enable interaction with the API of the cluster. It pairs an action, or verb, with an API group to define a specific permission. For example, if you intended to restrict a continuous integration/continuous delivery (CI/CD) pipeline’s ability to only patch Deployments for updating image tags, you could utilize a ClusterRole similar to the following:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: patch-deployment
rules:
- apiGroups: ["apps/v1"]
resources: ["deployments"]
verbs: ["get", "list", "patch"]

A ClusterRole can apply to APIs at both the cluster and namespace levels.

Once you have specified a ClusterRole, the next step is to create an association between the ClusterRole and a subject using a ClusterRoleBinding. This binding links the ClusterRole to a user, group, or service account, granting them the permissions defined within the ClusterRole.

We’ll explore ClusterRoleBinding in more detail in Chapter 7, RBAC Policies and Auditing.

The Kubernetes control plane is a crucial component for a cluster; it is essential for the operation of the cluster. ComponentStatus is an object that shows the health and status of different Kubernetes control plane components. It provides an indicator of the overall health of a component, providing information on whether it is operating correctly or has errors.

A ConfigMap is a resource that stores data in key-value pairs, enabling the separation of configuration from your application. ConfigMaps can hold various types of data, including literal values, files, or directories, allowing flexibility in managing your application’s configuration.

Here is an imperative example:

kubectl create configmap <name> <data>

The <data> option will vary based on the source of the ConfigMap. To use a file or a directory, you supply the --from-file option and either the path to a file or an entire directory, as shown here:

kubectl create configmap config-test --from-file=/apps/nginx-config/nginx.conf

This would create a new ConfigMap named config-test, with the nginx.conf key containing the content of the nginx.conf file as the value.

If you need to have more than one key added in a single ConfigMap, you put each file into a directory and create the ConfigMap using all of the files in the directory. For example, you have three files in a directory located at ~/config/myapp. The files each contain data and are called config1, config2, and config3. To create a ConfigMap that would add each file into a key, you need to supply the --from-file option and point to the directory, as follows:

kubectl create configmap config-test --from-file=/apps~/config/myapp

This would create a new ConfigMap with three key values called config1, config2, and config3. Each key will contain a value equal to the content of each file in the directory.

To quickly show a ConfigMap, using the example mentioned above, we can retrieve it using the get command, kubectl get configmaps config-test, resulting in the following output:

NAME DATA AGE
config-test 3 7s

The ConfigMap is comprised of three keys, indicated by the presence of the number 3 under the DATA column. For a more detailed examination, we can utilize the kubectl get command with the additional “ -o yaml ” option appended to the kubectl get configmaps config-test command. This will show the output of each key’s value represented in YAML format, as demonstrated below:

apiVersion: v1
data:
config1: |
First Configmap Value
config2: |
Yet Another Value from File2
config3: |
The last file - Config 3
kind: ConfigMap
metadata:
creationTimestamp: "2023-06-10T01:38:51Z"
name: config-test
namespace: default
resourceVersion: "6712"
uid: a744d772-3845-4631-930c-e5661d476717

By examining the output, it shows that each key within the ConfigMap corresponds to the filenames found in the directory— config1, config2, and config3. Each key retains the value obtained from the data within its respective file.

One limitation of ConfigMaps that you should keep in mind is that the data is easily accessible to anyone with permission to the resource. As you can see from the preceding output, a simple get command shows the data in cleartext.

Due to this design, you should never store sensitive information such as a password in a ConfigMap. Later in this section, we will cover a resource that was designed to store secret data information, called a Secret.

A ControllerRevision is like a snapshot of a particular version or update to a controller’s settings. It’s mainly used by specific controllers, such as the StatefulSet controller, to keep track of and manage changes made to their configurations as time goes on.

Whenever there are modifications or updates to the configuration of a resource managed by a controller, a new ControllerRevision is created. Each revision includes the desired setup of the controller and a revision number. These revisions are stored in the Kubernetes API server, allowing you to refer to or revert to them whenever necessary.

If you have used Linux cronjobs in the past, then you already know what a Kubernetes CronJob resource is. If you don’t have a Linux background, a cronjob is used to create a scheduled task. As another example, if you are a Windows person, it’s similar to Windows scheduled tasks.

An example manifest that creates a CronJob is shown in the following code snippet:

apiVersion: batch/v1
kind: CronJob
metadata:
name: hello-world
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello-world
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello World!
restartPolicy: OnFailure

The schedule format follows the standard cron format. From left to right, each * represents the following:

  • Minute (0–59)
  • Hour (0–23)
  • Day (1–31)
  • Month (1–12)
  • Day of the week (0–6) (Sunday = 0, Saturday = 6)

CronJob accept step values, which allow you to create a schedule that can execute every minute, every 2 minutes, or every hour.

Our example manifest will create a CronJob that runs an image called hello-world every minute and outputs Hello World! in the Pod log.

Kubernetes uses the CsiDriver resource to connect nodes to a storage system.

You can list all CSI drivers that are available on a cluster by executing the kubectl get csidriver command. In one of our lab clusters, we are using NetApp’s SolidFire for storage, so our cluster has the Trident CSI driver installed, as can be seen here:

NAME CREATED AT
csi.trident.netapp.io 2019-09-04T19:10:47Z

To avoid storing storage information in the node’s API resource, the CSINode resource was added to the API server to store information generated by the CSI drivers. The information that is stored includes mapping Kubernetes node names to CSI node names, CSI driver availability, and the volume topology.

CSIStorageCapacity is a component that stores information about the storage capacity for a given CSI, representing the available storage capacity for a given StorageClass. This information is used when K8s decides where to create new PersistentVolumes.

A CustomResourceDefinition (CRD) is a way for users to make their own custom resources in a Kubernetes cluster.

It outlines the structure, format, and behavior of the custom resource, including its API endpoints and supported operations. Once a CRD is made and added to the cluster, it becomes a built-in resource type that can be managed using regular Kubernetes tools and APIs.

A DaemonSet enables the deployment of a pod on each node in a cluster or on a specific set of nodes. It is commonly utilized to deploy essential components like logging, which are required on every node in the cluster. Once a DaemonSet is set up, it automatically creates a pod on each existing node.

Moreover, as new nodes are added to the cluster, the DaemonSet ensures that a pod is deployed on the newly joined nodes.

We mentioned earlier that you should never deploy a pod directly. One reason for this is that you cannot scale a pod or perform a rolling upgrade when a pod is created in this way. Deployments offer you many advantages, including a way to manage your upgrades declaratively and the ability to roll back to previous revisions. Creating a Deployment is actually a three-step process that is executed by the API server: a Deployment is created, which creates a ReplicaSet, which then creates the pod(s) for the application.

Even if you don’t plan to scale or perform rolling upgrades to the application, you should still use Deployments by default so that you can leverage the features at a future date.

An Endpoint maps a service to a pod or pods. This will make more sense when we explain the Service resource. For now, you only need to know that you can use the CLI to retrieve endpoints by using the kubectl get endpoints command. In a new KinD cluster, you will see a value for the Kubernetes API server in the default namespace, as illustrated in the following code snippet:

NAMESPACE NAME ENDPOINTS AGE
default Kubernetes 172.17.0.2:6443 22h

The output shows that the cluster has a service called kubernetes that has an endpoint at the Internet Protocol (IP) address 172.17.0.2 on port 6443. The IP that is returned in our example is the address to which our Docker control plane container has been assigned.

Later, you will see how looking at endpoints can be used to troubleshoot service and ingress issues.

Endpoints do not scale well—they store all endpoints in a single resource. When dealing with a smaller deployment that may have a handful of pods, this isn’t an issue. As clusters grow and applications scale, endpoint sizes also grow, and this will impact the performance of your control plane and cause additional network traffic as endpoints change.

EndPointSlices are designed to take on more significant and larger scenarios that require scalability and precise control over network endpoints. By default, each EndPointSlice can hold up to 100 endpoints, which can be increased by adding the --max-endpoints-per-slice option to the kube-controller-manager.

Imagine that you have a deployment of a Service in Kubernetes with a large number of pods. If one of those pods is deleted, Kubernetes will only update the specific slice that contains the information about that pod. When the updated slice is distributed across the cluster, it will only include details for a smaller subset of pods. By doing so, the cluster network remains efficient and avoids becoming overwhelmed with excessive data.

The Events resource will display any events for a namespace. To get a list of events for the kube-system namespace, you would use the kubectl get events -n kube-system command.

Kubernetes clusters have predefined settings that manage the handling of concurrent requests to the API server, ensuring that the traffic does not overload the server. However, you have the flexibility to customize and configure your own flow schema and priority levels for requests directed at the API server in your clusters. This allows you to define specific rules and preferences for how requests are handled and prioritized, tailoring the behavior of the API server to suit your specific requirements and workload.

For example, you have a namespace that has an important application deployed. You could create a FlowSchema with a high priority so the API server would handle requests for the namespace before other requests.

One of the biggest advantages of running a workload on a Kubernetes cluster is the ability to automatically scale your pods. While you can scale using the kubectl command or by editing a manifest’s replica count, these are not automated and require manual intervention.

Horizontal Pod Autoscalers (HPAs) provide the ability to scale an application based on a set of criteria. Using metrics such as CPU and memory usage, or your own custom metrics, you can set a rule to scale your pods out when you need more pods to maintain your service level.

After a cooldown period, Kubernetes will scale the application back to the minimum number of pods defined in the policy.

To quickly create an HPA for an NGINX Deployment, we can execute a kubectl command using the autoscale option, as follows:

kubectl autoscale deployment nginx --cpu-percent=50 --min=1 --max=5

You can also create a Kubernetes manifest to create your HPAs. Using the same options as those we did in the CLI, our manifest would look like this:

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: nginx-deployment
spec:
maxReplicas: 5
minReplicas: 1
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx-deployment
targetCPUUtilizationPercentage: 50

Both options will create an HPA that will scale nginx-deployment up to 5 replicas when the Deployment hits a CPU utilization of 50%. Once the Deployment usage falls below 50% and the cooldown period is reached (by default, 5 minutes), the replica count will be reduced to 1.

IngressClasses allow you to define and oversee various types of Ingress controllers. They offer the ability to personalize and adjust the behavior of these controllers according to specific needs, providing customizable routing of incoming traffic to services. IngressClasses allow you to manage and fine-tune Ingress controllers, ensuring that traffic is handled in a manner that aligns with your requirements.

The most important role an IngressClass has is to let you define multiple Ingress controllers in a single cluster. For instance, the Kubernetes Dashboard version 3 uses a specific IngressClass to make sure its Ingress objects are bound to an NGINX instance that doesn’t have a LoadBalancer, so it can’t be accessed from outside the cluster. You can also use this feature to connect Ingress controllers to different networks.

An Ingress resource is a tool that lets you create rules for incoming HTTP and HTTPS traffic to services using options like hostnames, paths, or request headers. It acts as a middleman between the external traffic and the services running in the cluster. By using Ingress, you can define how different types of traffic should be routed to specific services, giving you granular control over the flow of incoming requests.

We will discuss Ingress in depth in the next chapter, but a quick description of what Ingress provides is that it allows you to expose your application to the outside world using an assigned URL.

Jobs allow you to execute a specific number of executions of a pod or pods. Unlike a CronJob resource, these pods are not run on a set schedule, but rather they will execute once when they are created.

We will discuss the Quota resource later in this chapter, but a LimitRange is a configuration that allows you to establish and enforce specific boundaries and restrictions on resource allocations for pods and containers within a given namespace. By utilizing LimitRanges, you can define limits on resources, such as CPU, memory, and storage, ensuring that pods and containers operate efficiently and prevent any negative impact on the overall cluster environment.

LocalSubjectAccessReview is a feature that helps you check if a user or group in the cluster has the required permissions to perform a specific action on a local resource. It enables you to review access permissions directly within the cluster without relying on external API requests.

Using LocalSubjectAccessReview, you can specify the user or group identity along with the action and resource you want to evaluate. The Kubernetes API server will then verify the permissions against the local access control policies. It will respond with whether the requested action is allowed or denied.

MutatingWebhookConfiguration is used to create webhooks that can intercept and modify requests sent to the API server, providing a way to automatically modify the requested resources.

A MutatingWebhookConfiguration contains a set of rules that determine which requests should be intercepted and processed by a webhook. When a request matches the defined rules, the MutatingWebhookConfiguration triggers the corresponding webhooks, which can then modify the payload. Modifications can include adding, removing, or modifying fields and annotations in the resource being created or updated.

A Namespace is a resource to divide a cluster into logical units. Each Namespace allows granular management of resources, including permissions, quotas, and reporting.

The Namespace resource is used for namespace tasks, which are cluster-level operations. Using the namespace resource, you can execute commands including create, delete, edit, and get.

The syntax for the command is kubectl <verb> ns <namespace name>.

For example, to describe the kube-system namespace, we would execute a kubectl describe namespaces kube-system command.

This will return information for the namespace, including any labels, annotations, and assigned quotas, as illustrated in the following code snippet:

Name: kube-system
Labels: <none>
Annotations: <none>
Status: Active
No resource quota.
No LimitRange
resource.

In the preceding output, you can see that this namespace does not have any labels, annotations, or resource quotas assigned.

This section is only meant to introduce the concept of namespaces as a management unit in multi-tenant clusters. If you plan to run clusters with multiple tenants, you need to understand how namespaces can be used to secure a cluster.

NetworkPolicy resources let you define how network traffic, both ingress (incoming) and egress (outgoing), can flow through your cluster. They allow you to use Kubernetes native constructs to define which pods can talk to other Pods. If you’ve ever used security groups in Amazon Web Services (AWS) to lock down access between two groups of systems, it’s a similar concept. As an example, the following policy will allow traffic on port 443 to pods in the myns namespace from any namespace with the app.kubernetes.io/name: ingress-nginx label on it (which is the default label for the nginx-ingress namespace):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-from-ingress
namespace: myns
spec:
PodSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
app.kubernetes.io/name: ingress-nginx
ports:
- protocol: TCP
port: 443

A NetworkPolicy is another resource that you can use to secure a cluster. They should be used in all production clusters, but in a multi-tenant cluster, they should be considered a must-have to secure each namespace in the cluster.

The nodes resource is a cluster-level resource that is used to interact with the cluster’s nodes. This resource can be used with various actions including get, describe, label, and annotate.

To retrieve a list of all of the nodes in a cluster using kubectl, you need to execute a kubectl get nodes command. On a new KinD cluster running a simple one-node cluster, this would display as follows:

NAME STATUS ROLES AGE VERSION
kind-control-plane Ready master 22h v1.30.0

You can also use the nodes resource to get details of a single node using the describe command. To get a description of the KinD node listed previously, we can execute kubectl describe node kind-control-plane, which would return details on the node, including consumed resources, running pods, IP classless inter-domain routing (CIDR) ranges, and more.

A PVC is a namespaced resource that is used by a pod to consume persistent storage. A PVC uses a persistent volume (PV) to map the actual storage resource, which can be on any support storage system, including NFS and iSCSI.

As with most resources we have discussed, you can issue get, describe, and delete commands on a PVC resource. Since these are used by pods in the namespace, PVCs must be created in the same namespace as the pod(s) that will use the PVC.

PVs are used by PVCs to create a link between the PVC and the underlying storage system. Manually maintaining PVs is a messy, manual task, and it should be avoided. Instead, Kubernetes includes the ability to manage most common storage systems using the Container Storage Interface (CSI).

Most CSI solutions that are used in an Enterprise cluster provide auto-provisioning support, as we discussed in Chapter 2 when we introduced Rancher’s local provisioner. Solutions that support auto-provisioning remove the administrative overhead that is required to create PVs manually, taking care of the creation and mapping of the PVs to PVCs automatically.

A PodDisruptionBudget (PDB) is a resource that creates boundaries on the maximum number of unavailable pods at any given time. Its purpose is to prevent situations where multiple pods are terminated simultaneously, which could result in service disruptions or failures. By defining the minimum number of available pods, referred to as the "minAvailable" parameter, you can guarantee that a specific quantity of pods remains functional during maintenance or other disruptive occurrences.

The kube-scheduler in a cloud will use this information to figure out how to replace nodes during an upgrade. You need to be careful when using a PodDisruptionBudget because you could find a situation where an upgrade is halted.

The pod resource is used to interact with the pods that are running your container(s). Using the kubectl utility, you can use commands such as get, delete, and describe. For example, if you wanted to get a list of all pods in the kube-system namespace, you would execute a kubectl get Pods -n kube-system command that would return all pods in the namespace, as follows:

NAME READY STATUS RESTARTS AGE
calico-kube-controllers-c6c8dc655-vnrt7 1/1 Running 0 15m
calico-node-4d9px 1/1 Running 0 15m
calico-node-r4zsj 1/1 Running 0 15m
coredns-558bd4d5db-8mxzp 1/1 Running 0 15m
coredns-558bd4d5db-fxnkt 1/1 Running 0 15m
etcd-cluster01-control-plane 1/1 Running 0 15m
kube-apiserver-cluster01-control-plane 1/1 Running 0 15m
kube-controller-manager-cluster01-control-plane 1/1 Running 0 15m
kube-proxy-npxqd 1/1 Running 0 15m
kube-proxy-twn7s 1/1 Running 0 15m
kube-scheduler-cluster01-control-plane 1/1 Running 0 15m

While you can create a pod directly, you should avoid doing so unless you are using a pod for quick troubleshooting. pods that are created directly cannot use many of the features provided by Kubernetes, including scaling, automatic restarts, or rolling upgrades.

Instead of creating a pod directly, you should use a Deployment, StatefulSet, or, in some rare cases, ReplicaSet resource or replication controller.

PodTemplates provide a way to create templates or blueprints for creating pods. They function as reusable configurations that include the desired specifications and settings for pods. They include the metadata and specifications of a pod, including the name, labels, containers, volumes, and other attributes.

PodTemplates are commonly used in other Kubernetes objects such as ReplicaSets, Deployments, and StatefulSets. These resources rely on a PodTemplate to generate and manage a collection of pods with consistent configurations and behavior.

PriorityClasses provide a way to prioritize pods based on their importance. This allows the Kubernetes scheduler to make better decisions regarding resource allocation and pod scheduling in a cluster.

To define PriorityClasses, you create a new PriorityClass resource associated with numeric values that indicate the priority level. pods with higher priority values are given priority over lower values when it comes to resource allocation and scheduling.

Using PriorityClasses, you can guarantee that crucial workloads are given higher priority in terms of resource allocation and scheduling, providing the necessary resources to run smoothly.

PriorityLevelConfigurations are objects that help define priority levels for requests sent to the API server. They provide control over how API requests are processed and prioritized within a cluster. Using PriorityLevelConfigurations, you can establish multiple priority levels, assigned to specific attributes. These attributes include setting limits on the maximum number of queries per second (QPS) and concurrent requests for a particular priority level. This allows for more efficient resource management and allocation based on the importance of different API requests.

PriorityLevelConfigurations allow you to enforce policies that ensure critical requests always receive enough resources, providing flexibility in managing the processing and allocation of resources for API requests.

ReplicaSets can be used to create a pod or a set of pods (replicas). Similar to the ReplicationController resource, a ReplicaSet will maintain the set number of pods defined in the replica count. If there are too few pods, Kubernetes will make up the difference and create the missing pods. If there are too many pods for a ReplicaSet, Kubernetes will delete pods until the number is equal to the replica count set.

In general, you should avoid creating ReplicaSets directly. Instead, you should create a Deployment, which will create and manage a ReplicaSet.

Replication controllers will manage the number of running pods, keeping the desired replicas specified running at all times. If you create a replication controller and set the replica count to 5, the controller will always keep five pods of the application running.

Replication controllers have been replaced by the ReplicaSet resource, which we just discussed in its own section. While you can still use replication controllers, you should consider using a Deployment or a ReplicaSet.

It is becoming very common to share a Kubernetes cluster between multiple teams, referred to as a multi-tenant cluster. Since you will have multiple teams working in a single cluster, you should create quotas to limit the potential of a single tenant consuming all the resources in a cluster or on a node.

Limits can be set on most cluster resources, including the following:

  • Central processing unit (CPU)
  • Memory
  • PVCs
  • ConfigMaps
  • Deployments
  • Pods, and more

Setting a limit will stop any additional resources from being created once the limit is hit. If you set a limit of 10 pods for a namespace and a user creates a new Deployment that attempts to start 11 Pods, the eleventh pod will fail to start up and the user will receive an error.

A basic manifest file to create a quota for memory and CPU would look like this:

apiVersion: v1
kind: ResourceQuota
metadata:
name: base-memory-cpu
spec:
hard:
requests.cpu: "2"
requests.memory: 8Gi
limits.cpu: "4"
limits.memory: 16Gi

This will set a limit on the total amount of resources the namespace can use for CPU and memory requests and limits.

Many of the options you can set in a quota are self-explanatory, like pods, PVCs, services, etc. When you set a limit, it means that the set limit is the maximum allowed for that resource in the namespace. For example, if you set a limit on a pod to 5, when an attempt is made to create a sixth pod in that namespace, it will be denied.

Some quotas have more than one option that can be set: specifically, CPU and memory. In our example, both resources have set a request and a limit. Both values are very important to understand to ensure efficient use of your resources and to limit the potential availability of the application.

A request is essentially a reservation of that specific resource. When a pod is deployed, you should always set a request on your CPU and memory, and the value should be the minimum required to start your application. This value will be used by the scheduler to find a node that meets the request that has been set. If there are no nodes with the requested resource available, the pod will fail to be scheduled.

Now, since a request will reserve the resource, that means once all nodes in the cluster have 100% of requests assigned, any additional pod creations will be denied since the requests are at 100%. Even if your actual cluster CPU or memory utilization is at 10%, pods will fail to be scheduled since the request, or reservation, is at 100%. If requests are not carefully thought out, it will lead to wasted resources, and that will lead to an increased cost to run the platform.

Limits on CPU and memory set the maximum value that the pod will be able to utilize. This is different from a request since limits are not a reservation of the resource. However, limits still need to be carefully planned out from an application side. If you set the CPU limit too low, the application may experience performance issues, and if you set the memory limit too low, the pod will be terminated, impacting availability while it is restarted.

Once a quota has been created, you can view the usage using the kubectl describe command. In our example, we named the ResourceQuota as base-memory-cpu.

To view the usage, we will execute the kubectl get resourcequotas base-memory-cpu command, resulting in the following output:

Name: base-memory-cpu
Namespace: default
Resource Used Hard
-------- ---- ----
limits.cpu 0 4
limits.memory 0 16Gi
requests.cpu 0 2
requests.memory 0 8Gi

ResourceQuotas serve as a means to manage and control the allocation of resources within a cluster. They allow you to assign specific CPU and memory resources to individual namespaces, ensuring that each tenant has sufficient resources to run their applications effectively. Additionally, ResourceQuotas act as a safeguard, preventing a poorly optimized or resource-intensive application from adversely affecting the performance of other applications in the cluster.

The RoleBinding resource is how you associate a Role or ClusterRole with a subject and namespace. For instance, the following RoleBinding will allow the aws-codebuild user to apply the patch-openunison ClusterRole to the openunison namespace:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: patch-openunison
namespace: openunison
subjects:
- kind: User
name: aws-codebuild
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: patch-deployment
apiGroup: rbac.authorization.k8s.io

Even though this references a ClusterRole, it will only apply to the openunison namespace. If the aws-codebuild user tries to patch a Deployment in another namespace, the API server will stop it.

As with a ClusterRole, Roles combine API groups and actions to define a set of permissions that can be assigned to a subject. The difference between a ClusterRole and a Role is that a Role can only have resources defined at the namespace level and they apply only within a specific namespace.

RuntimeClasses are used to set up and customize different runtime environments for running containers. They provide the flexibility to choose and configure the container runtime that best suits your workloads. By using RuntimeClasses, you can fine-tune the container runtime according to your specific requirements.

Each RuntimeClass is linked to a specific container runtime, like Docker or Containerd. They include configurable parameters that define how the chosen container runtime behaves. These parameters include resource limits, security configurations, and environment variables.

Earlier, we described how to use a ConfigMap resource to store configuration information. We mentioned that ConfigMap should never be used to store any type of sensitive data. This is the job of a Secret.

Secrets are stored as Base64-encoded strings, which aren’t a form of encryption. So, why separate Secrets from ConfigMap? Providing a separate resource type offers an easier way to maintain access controls and the ability to inject sensitive information using an external secret management system.

Secrets can be created using a file, directory, or from a literal string. As an example, we have a MySQL image we want to execute, and we would like to pass the password to the pod using a Secret. On our workstation, we have a file called dbpwd in our current working directory that has our password in it. Using the kubectl command, we can create a Secret by executing kubectl create secret generic mysql-admin --from-file=./dbpwd.

This would create a new Secret called mysql-admin in the current namespace, with the content of the dbpwd file. Using kubectl, we can get the output of the Secret by running the kubectl get secret mysql-admin -o yaml command, which would output the following:

apiVersion: v1
data:
dbpwd: c3VwZXJzZWNyZXQtcGFzc3dvcmQK
kind: Secret
metadata:
creationTimestamp: "2020-03-24T18:39:31Z"
name: mysql-admin
namespace: default
resourceVersion: "464059"
uid: 69220ebd-c9fe-4688-829b-242ffc9e94fc
type: Opaque

Looking at the preceding output, you can see that the data section contains the name of our file and then a Base64-encoded value, which was created from the content of the file.

If we copy the Base64 value from the Secret and pipe it out to the base64 utility, we can easily decode the password, as follows:

echo c3VwZXJzZWNyZXQtcGFzc3dvcmQK | base64 -d
supersecret-password

When using the echo command to Base64-encode strings, add the -n flag to avoid adding an additional \n. Instead of echo 'test' | base64, use echo -n 'test' | base64.

Everything is stored in etcd but we are concerned that someone may be able to hack into the etcd node and steal a copy of the etcd database. Once someone has a copy of the database, they could easily use the etcdctl utility to look through the content to retrieve all of our Base64-encoded Secrets. Luckily, Kubernetes added a feature to encrypt Secrets when they are written to a database.

Enabling this feature can be fairly complex for many users, and while it sounds like a good idea, it does present some potential issues that you should consider before implementing it. If you would like to read the steps on encrypting your Secrets at rest, you can view these on the Kubernetes site at https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/.

Another option to secure Secrets is to use a third-party secrets management tool such as HashiCorp’s Vault or CyberArk’s Conjur. We’ll cover integration with secret management tools in Chapter 9, Managing Secrets in Kubernetes.

SelfSubjectAccessReviews objects enable users or entities to check their own permissions for performing specific actions on resources in their namespace.

To use SelfSubjectAccessReviews, users provide their username along with the desired action and resource to check. The cluster evaluates the permissions of the provided user against the access control policies in the namespace, and the API server responds with whether the requested action is allowed or denied.

SelfSubjectAccessReviews and the next resource, SelfSubjectRulesReviews, may look very similar, but they serve different functions. The main point to keep in mind for SelfSubjectAccessReviews is that they assess individual access permissions for specific actions on resources.

SelfSubjectRulesReviews objects are used to determine the set of rules that a user or entity has permissions for within a namespace, providing the ability to investigate the access control rules for their own actions and resources.

To use a SelfSubjectRulesReview, you provide your identity, and the API server assesses the permissions associated with the identity in a namespace.

SelfSubjectRulesReviews offer a more comprehensive view over SelfSubjectAccessReviews, providing a deeper understanding of the entire set of rules that govern a user’s permissions within a namespace.

Kubernetes uses ServiceAccounts to enable access controls for workloads. When you create a Deployment, you may need to access other services or Kubernetes resources.

Since Kubernetes is a secure system, each resource or service your application tries to access will evaluate role-based access control (RBAC) rules to accept or deny the request.

Creating a service account using a manifest is a straightforward process, requiring only a few lines in the manifest. The following code snippet shows a service account manifest to create a service account for a Grafana Deployment:

apiVersion: v1
kind: ServiceAccount
metadata:
name: grafana
namespace: monitoring

You combine the service account with role bindings and Roles to allow access to the required services or objects.

We’ll cover how to use ServiceAccounts in depth in Chapter 6, Integrating Enterprise Authentication into Your Cluster.

When you create a pod, it will receive an IP address from the CIDR range that was assigned when the cluster was created. In most clusters, the assigned IPs are only addressable within the cluster itself, referred to as “ island mode.” Since pods are ephemeral, the assigned IP address will likely change during an application’s life cycle, which becomes problematic when any service or application needs to connect to the pod. To address this, we can create a Kubernetes service, which will also receive an IP address, but since services aren’t deleted during an application’s life cycle, the address will remain the same.

A service will dynamically maintain a list of pods to target based on labels that match the service selector, creating a list of endpoints for the service.

A service stores information about how to expose the application, including which pods are running the application and the network ports to reach them.

Each service has a network type that is assigned when they are created, and they include the following:

  • ClusterIP: A network type that is only accessible inside the cluster itself. This type can still be used for external requests using an Ingress controller, which will be discussed in a later chapter. The ClusterIP type is the default type that will be used if no type is specified when you create a service.
  • NodePort: A network type that exposes the service to a random port between ports 30000 and 32767. This port becomes accessible by targeting any worker node in a cluster on the assigned NodePort. Once created, each node in the cluster will receive the port information, and incoming requests will be routed via kube-proxy.
  • LoadBalancer: This type requires an add-on to use inside a cluster. If you are running Kubernetes on a public cloud provider, this type will create an external load balancer that will assign an IP address to your service. Most on-premises Kubernetes installations do not include support for the LoadBalancer type, but some offerings such as Google’s Anthos do offer support for it. In a later chapter, we will explain how to add an open-source project called MetalLB to a Kubernetes cluster to provide support for the LoadBalancer type.
  • ExternalName: This type is different from the other three. Unlike the other three options, this type will not assign an IP address to the service. Instead, this is used to map the internal Kubernetes Domain Name System (DNS) name to an external service.

As an example, we have deployed a pod running Nginx on port 80. We want to create a service that will allow this pod to receive incoming requests on port 80 from within the cluster. The code for this can be seen in the following snippet:

apiVersion: v1
kind: Service
metadata:
labels:
app: nginx-web-frontend
name: nginx-web
spec:
ports:
- name: http
port: 80
targetPort: 80
selector:
app: nginx-web

In our manifest, we create a label with a value of app and assign a value of nginx-web-frontend. We have called the service itself nginx-web and we exposed the service on port 80, targeting the pod port of 80. The last two lines of the manifest are used to assign the pods that the service will forward to, also known as Endpoints. In this manifest, any pod that has the label of app with a value of nginx-web in the namespace will be added as an endpoint to the service. Finally, you may have noticed that we didn’t specify a service type in our manifest. Since we didn’t specify the type, it will be created as the default service type of ClusterIP.

StatefulSets offer some unique features when creating pods. They provide features that none of the other pod creation methods offer, including the following:

  • Known pod names
  • Ordered Deployment and scaling
  • Ordered updates
  • Persistent storage creation

The best way to understand the advantages of a StatefulSet is to review an example manifest from the Kubernetes site, shown in the following screenshot:

Figure 5.9 – StatefulSet manifest example

Figure 3.4: StatefulSet manifest example

Now, we can look at the resources that the StatefulSet created.

The manifest specifies that there should be three replicas of a pod named nginx. When we get a list of pods, you will see that three pods were created using the nginx name, with an additional dash and an incrementing number. This is what we meant in the overview when we mentioned that Pods will be created with known names, as illustrated in the following code snippet:

NAME READY STATUS RESTARTS AGE
web-0 1/1 Running 0 4m6s
web-1 1/1 Running 0 4m2s
web-2 1/1 Running 0 3m52s

The pods are also created in order— web-0 must be fully deployed before web-1 is created, and then, finally, web-2.

Finally, for this example, we also added a PVC to each pod using the VolumeClaimTemplate in the manifest. If you look at the output of the kubectl get pvc command, you will see that three PVCs were created with the names we expected (note that we removed the VOLUME column due to space), as illustrated in the following code snippet:

NAME STATUS CAPACITY ACCESS MODES STORAGECLASS AGE
www-web-0 Bound 1Gi RWO nfs 13m
www-web-1 Bound 1Gi RWO nfs 13m
www-web-2 Bound 1Gi RWO nfs 12m

In the VolumeClaimTemplate section of the manifest, you will see that we assigned the name www to the PVC claim. When you assign a volume in a StatefulSet, the PVC name will combine the name used in the claim template, combined with the name of the pod. Using this naming, you can see why Kubernetes assigned the PVC names www-web-0, www-web-1, and www-web-2.

Storage classes are used to define a storage endpoint. Each storage class can be assigned labels and policies, allowing a developer to select the best storage location for their persistent data. You may create a storage class for a backend system that has all Non-Volatile Memory Express (NVMe) drives, assigning it the name fast, while assigning a different class to a NetApp Network File System (NFS) volume running standard drives, using the name standard.

When a PVC is requested, the user can assign a StorageClass that they wish to use. When the API server receives the request, it finds the matching name and uses the StorageClass configuration to create the volume on the storage system using a provisioner.

At a very high level, a StorageClass manifest does not require a lot of information. Here is an example of a storage class using a provisioner from the Kubernetes incubator project to provide NFS auto-provisioned volumes, named nfs:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: nfs
provisioner: nfs

Storage classes allow you to offer multiple storage solutions to your users. You may create a class for cheaper, slower storage while offering a second class that supports high throughput for high data requirements. By providing a different class to each offering, you allow developers to select the best choice for their application.

SubjectAccessReviews are used to check if an entity has permission to perform a specific action on a resource. They allow users to request access reviews and get information about their privileges. By providing an identity, desired action, and resource, the API server determines if the action is allowed or denied. This helps users verify their permissions to a resource, which can help to identify access issues to a Kubernetes resource.

For example, Scott wants to verify his ability to create pods in a namespace called sales. To do this, Scott creates a SubjectAccessReview in the sales namespace, including his username, the create action, and the target resource, pods.

The API server verifies whether he has permission to create pods in the sales namespace and sends a response back. The response from the API server includes whether the requested action is permitted or denied.

Knowing if an entity has permission to execute an action on a resource helps to minimize frustrations when a deployment fails due to permissions.

TokenReviews are API objects used to authenticate and verify the legitimacy of an authentication token linked to a user or entity in the cluster. If the token is valid, the API server retrieves the details about the associated user or entity.

When users submit an authentication token to the Kubernetes API server, it validates the token against the internal authentication system. It verifies that the token is legitimate and determines the user or entity associated with it.

The API server provides information about the token’s validity and the user or entity, including the username, user identifier (UID), and group membership.

ValidatingWebhookConfiguration is a collection of rules that determine what admission requests are intercepted and handled by a webhook. Each rule contains the specific resources and operations that the webhook should handle.

It provides a way to enforce specific policies or rules by applying validation logic to admission requests. Many add-ons to Kubernetes provide a ValidatingWebhookConfiguration – one of the most common is the NGINX ingress controller.

You can view all of the ValidatingWebhookConfigurations in your cluster by executing kubectl get validatingwebhookconfigurations. For the KinD clusters we have deployed, you will have a single entry for NGINX ingress admissions:

NAME WEBHOOKS AGE ingress-nginx-admission 1 3d10h

VolumeAttachments create connections between external storage volumes and nodes in a cluster. They control the association of persistent volumes with specific nodes, enabling the nodes to access and utilize the storage resources.

In this chapter, you were provided with a fast-paced Kubernetes bootcamp, where you were exposed to a wealth of technical information. Remember that as you get deeper into the world of Kubernetes, everything will become more manageable and easier to grasp. It’s important to note that many of the resources discussed in this chapter will be further explored and explained in subsequent chapters, providing you with a deeper understanding.

You gained insights into each Kubernetes component and their interdependencies, which form the cluster. Armed with this knowledge, you now possess the necessary skills to investigate and identify the root causes of errors or issues within a cluster. We explored the control plane, which encompasses api-server, kube-scheduler, etcd, and controller managers. Additionally, you familiarized yourself with Kubernetes nodes that run the kubelet and kube-proxy components, along with a container runtime.

We also delved into the practical use of the kubectl utility, which will be your primary tool for interacting with a cluster. You learned about several essential commands, such as commands for accessing logs and providing descriptive information, which you will utilize on a daily basis.

In the next chapter, we will create a development Kubernetes cluster that we will use as the base cluster for the remaining chapters. Throughout the remainder of the book, we will reference many of the resources that were presented in this chapter, helping to explain them by using them in real-world examples.

  1. A Kubernetes control plane does not include which of the following components?
    1. api-server 2. kube-scheduler 3. etcd 4. Ingress controller

Answer: d

  1. What is the name of the component that keeps all of the cluster information?
    1. api-server 2. Master controller 3. kubelet 4. etcd

Answer: d

  1. Which component is responsible for selecting the node that will run a workload?
    1. kubelet 2. api-server 3. kube-scheduler 4. Pod-scheduler

Answer: c

  1. Which option would you add to a kubectl command to see additional output from a command?
    1. Verbose 2. -v 3. –verbose 4. -log

Answer: b

  1. Which service type creates a randomly generated port, allowing incoming traffic to any worker node on the assigned port to access the service?
    1. LoadBalancer 2. ClusterIP 3. None—it’s the default for all services 4. NodePort

Answer: d

  1. If you need to deploy an application on a Kubernetes cluster that requires known pod names and a controlled startup of each pod, which object would you create?
    1. StatefulSet 2. Deployment 3. ReplicaSet 4. ReplicationController

Answer: a

Join the book’s Discord workspace for a monthly Ask Me Anything session with the authors: