Skip to content
ImagineWorld

Orchestrating Containers with Kubernetes

node_idnode-book_becoming-kcna-certified_chapter-05-orchestrating-containers-with-kubernetes
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleOrchestrating Containers with Kubernetes
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Orchestrating Containers with Kubernetes

Section titled “Chapter 5 — Orchestrating Containers with Kubernetes”

In this and the following few chapters, we will cover the most important and perhaps the hardest part of the KCNA certification – Kubernetes Fundamentals. It makes up almost half (46%) of the total exam questions, so it’s crucial to understand all the details. We’ll take it one step at a time, and we’ll also get practical experience with Kubernetes that will help you to memorize everything you need to pass the exam.

In this chapter, we’ll learn about the features and the basics of the K8s architecture, its API, components, and the smallest deployable unit called a Pod. We will install and run Kubernetes locally with the help of the minikube project to support us along the way.

The topics we’re going to cover are as follows:

  • Kubernetes architecture
  • Kubernetes API
  • K8s – the Swiss Army knife of container orchestration
  • Installing and exploring Kubernetes with minikube

Let’s get started!

As you already know, Kubernetes is used to orchestrate fleets of containers that run on multiple servers that make up a Kubernetes cluster. Those servers are often called nodes, and nodes can be virtual machines running on-premises, in the cloud, or bare-metal servers. You can even combine different nodes in one Kubernetes cluster (for example, several nodes represented by VMs plus a few others as bare-metal servers).

There are two distinguished node types in Kubernetes:

  • Control plane nodes (sometimes also called master nodes)
  • Worker nodes

It is the worker nodes where the containerized applications run, and it is the control plane nodes where the K8s cluster management components run. We can see this in more detail in Figure 5*.1.*

Figure 5.1 – Kubernetes components

Control plane nodes run several specialized K8s services and make global decisions about the Kubernetes cluster, such as scheduling containerized applications. Control plane nodes are also responsible for managing worker nodes in the cluster.

The following five services run on control plane nodes:

  • API server (kube-apiserver): The core service that exposes the Kubernetes HTTP API for internal and external cluster communication. All operations within the cluster are performed through an API server – for example, when you query the state of the cluster or a particular application or start a new container.
  • Cluster data store (etcd): A place where all information about the Kubernetes cluster state and configuration is kept. etcd is an open source, distributed key-value store used for this purpose and it is the only stateful component.
  • Scheduler (kube-scheduler): A component that picks where, and on which worker node, the application containers will run in the cluster. The factors that can affect scheduling decisions include individual application requirements, load on the nodes, hardware or policy constraints, and more.
  • Controller manager (kube-controller-manager): A component that runs various controller processes, such as Node, Job, or Deployment controllers. Those controllers watch the current state of respective resources in the cluster and take action if the current state differs from the desired state.
  • An optional Cloud controller manager (cloud-controller-manager): A component that lets you integrate the Kubernetes cluster with a cloud provider by running controller processes specific to your provider. For example, it allows you to create load balancers for containerized applications or determine if a worker node cloud instance has been deleted. Cloud controller manager is a component that you do not need when K8s is running on-premises.

Let’s move on to the components of worker nodes:

  • Kubelet: An agent that ensures that containers assigned to the node are running and healthy. Kubelet also reports the status to the API server.
  • Proxy (kube-proxy): This is a network proxy that helps to implement Kubernetes Service functionality. Proxy maintains network rules on nodes to allow container communication from inside or outside of your K8s cluster.
  • Container runtime: This is a piece of software that’s responsible for basic container operations. Thanks to CRI, Kubernetes can use different container runtimes. One of the most popular runtimes today is containerd.

Note

Kubelet does not manage containers that were not created via the Kubernetes API. For example, containers created by other means on the worker nodes won’t be known to Kubernetes.

Today, the worker node components also run on the control plane nodes. That’s right – on the Kubernetes control plane, you’ll have not just the scheduler, kube-apiserver, etcd, and kube-controller-manager, but also kubelet, kube-proxy, and a runtime. This means that worker components are run on all Kubernetes nodes in the cluster.

Why is that? The reason is that control plane components are deployed in containers themselves and therefore can be managed by Kubernetes with so-called static pods. Alternatively, control plane components can be started and managed with systemd, but this approach is becoming less popular today.

What is a pod?

A pod is the smallest deployable unit that can be created in Kubernetes. A pod is a group of one or multiple containers that share storage, network, and a specification of how to run containers within the pod.

You can think of a pod as a Kubernetes wrapper for containers, and you’ll always deal with pods when deploying any application in a K8s cluster. Even if you need to run a small simple application consisting of only one container, you’ll need to define a pod with that single container. In other words, it is not possible to run containers on Kubernetes without a pod wrapper.

It is also rather common to have two or more containers in one pod where the second or third container in the pod acts as a helper to the main container. This happens when multiple containers need to work together and share resources. Such helper containers are called sidecars. In the previous chapter, we learned about the Service Mesh, which utilizes sidecars to deploy a proxy together with the application containers. Another example where you might run multiple containers in one pod is to collect monitoring metrics from the application running in the main container. A sidecar container may also be used for log aggregation – for example, a sidecar container might collect and ship logs for long-term storage from the main application in the same pod, as shown in Figure 5*.2*:

Figure 5.2 – Pod example with two containers

Note

Containers of one pod are always co-located and co-scheduled on the same node.

Other than the sidecar, there is yet another type called Init Containers. They are handy for running setup scripts and initialization utilities that are needed for the containerized application.

initContainers

These are containers that are executed in order before the other containers in the pod are started. Until all initContainers have finished, no other containers are going to start and initContainers will run every time a pod starts.

Besides allowing you to run co-located and individual containers on Kubernetes, pods have more features, including the following:

  • Shared storage: All the containers in a pod can access shared volumes, allowing containers to share data.
  • Shared networking: All the containers in a Pod share the network namespace with an IP address and network ports. Containers don’t have individual IP addresses, but the pod does, and containers in one pod can communicate with each other simply via localhost. Also, because of shared networking, two containers in one pod cannot listen on the same network port.
  • Shared memory: Containers in a pod can use standard Linux inter-process communication such as SystemV semaphores or POSIX shared memory.

Now, we’ve already mentioned Kubernetes clusters many times, meaning that we need at least two nodes. Technically, you could run Kubernetes on a single node while combining both the control plane and worker node functionality at the same time. However, you should never do this for production environments. This is only acceptable for learning or development purposes.

In real-life scenarios, we would run at least three control plane nodes with several worker nodes. The nodes should be spread across multiple failure domains (typically called availability zones by cloud providers) that might be represented by individual data centers interconnected with high bandwidth networks. In the case of an outage of a single server or an availability zone, such a Kubernetes cluster will remain operational.

Having just one control plane node in the cluster is not sufficient for production environments because, in the case of an outage, you won’t able to query the state of your cluster and applications, start new pods with containers, or make any changes. Also, you don’t want to lose your etcd data store, which keeps all the information about your cluster.

Therefore, like with many clustered systems, the best practice is to run an odd number of control plane nodes; for example, three or five. Having an odd number helps to prevent split-brain scenarios where, in the event of a network failure, two parts of the cluster won’t be able to establish a majority (for example, four nodes split into two parts can lead to inconsistencies or an inoperable state).

Note

This practice does not apply to worker nodes, and it is fine to run two, four, seven, or even 200 worker nodes in a cluster.

I know this is a lot to digest, but when we get our hands on Kubernetes and deploy our first few pods, things will become much clearer and easier. Later in this chapter, we will have a closer look at the pod specification, but for now, let’s learn more about the Kubernetes API and how we can use it.

As we learned previously, the Kubernetes API server is the main gateway for all cluster operations. When we want to know the state of the cluster, the number of nodes or pods or other resources, and their state, we need to use the Kubernetes API. The same is valid for all operations, such as creating new pods or making changes in the specifications of other resources. In a nutshell, the API server is the brain of K8s.

There are multiple ways to interact with the Kubernetes API:

  • Kubectl: A command-line interface tool available for all common platforms, including Linux, Windows, and macOS. Operators very often use kubectl to interact with K8s clusters and manage or debug applications running in Kubernetes.
  • dashboard (kube-dashboard): A popular web-based graphical user interface. It allows you to view, create, and modify resources, as well as troubleshoot applications running in K8s. dashboard, however, does not support all functionality that kubectl does.
  • Client libraries: Available in many programming languages, including Golang, Java, Python, JavaScript, and more. They allow you to write software that uses the Kubernetes API and helps handle common tasks such as authentication.
  • HTTP REST calls: Using any common HTTP client such as curl or wget, you can directly access the Kubernetes API. This is not a very commonly used method but it can be helpful sometimes.

This list is not exhaustive, and today, you can find many other tools (Lens, Octant) developed by third parties that allow you to use the Kubernetes API. However, they are outside the scope of this book and the KCNA exam. To successfully pass the exam, you only need to have experience with kubectl.

In the previous chapters, we mentioned that the Kubernetes API is declarative.

Declarative API

A declarative API means you declare the desired state of your Kubernetes resources and Kubernetes controllers, constantly ensuring that the current state of Kubernetes objects (for example, the number of pods for a certain app) is in sync with the declared desired state.

Thus, the Kubernetes API is different from an imperative approach where you instruct the server on what to do. After you have defined the desired state via the API, Kubernetes, using its kube-controller-manager, will instruct the controllers running in infinite control loops to check the resource state to be the same as the desired state and reconcile if not. For example, we have instructed K8s to run our application with three replicas and one of the replicas eventually crashed. Kubernetes will automatically detect that only two replicas are running and will spawn one new pod with our application:

Figure 5.3 – Kubernetes control loops

Note

The infinite control loops of controller managers are sometimes also called reconciliation loops.

Because Kubernetes is developed at high velocity, its APIs are constantly evolving. New API resources can be added frequently, and old resources or fields are removed over several release cycles following Kubernetes’s depreciation policy. To make it easier to make such changes, K8s supports multiple API versions and API grouping and maintains compatibility with existing API clients for an extended period. For example, there can be two API versions for the same resource: v1 and v1beta1. You may have first created a resource using its v1beta1 version, but you’ll still be able to make changes to this resource using either the v1 or v1beta1 API version for a few releases.

Each new feature of Kubernetes follows a defined life cycle and the respective API evolves from alpha to beta to the generally available state over several K8s releases, as shown in Figure 5*.4*:

Figure 5.4 – Kubernetes feature life cycle

It’s worth mentioning that the alpha features of Kubernetes are usually disabled. However, you can enable them by setting so-called feature gates. Beta and stable Kubernetes features are enabled by default.

The implementation of new and major changes to existing features in Kubernetes typically starts with Kubernetes Enhancement Proposal (KEP). Those are detailed specification documents that outline the motivation, goals, and design of the changes. You can find existing KEPs in Kubernetes GitHub repositories (https://github.com/kubernetes/enhancements/tree/master/keps).

Because Kubernetes is a complex project with many components, it has multiple operational areas, including storage, networking, scaling, and more. Those areas are typically covered by Kubernetes Special Interest Groups (SIGs). SIGs are smaller communities of developers that focus on particular parts of K8s. Since K8s is an open source project, anybody can become a part of SIG to fix issues, review code, and make enhancement proposals.

Last, but not least, the Kubernetes API is highly extensible in one of two ways:

  • With Custom Resource Definitions (CRDs): A method that does not require any programming
  • With aggregation layers: A method that requires programming but allows you to have more control over the API behavior

Both methods allow you to add extra functionality to Kubernetes, beyond what is offered by the standard Kubernetes APIs. You don’t need to know many details for the scope of the KCNA exam, but as you gain more hands-on experience, you’ll see that the extensible API is a very powerful feature of Kubernetes that allows us to add unique features without the need to know or modify existing K8s source code.

Now that we’ve learned about the Kubernetes API, let’s understand more about the features of Kubernetes that made it the number one orchestrator of containers.

K8s – the Swiss Army knife of container orchestration

Section titled “K8s – the Swiss Army knife of container orchestration”

We’ve mentioned a few times that Kubernetes is great for running cloud-native applications that consist of many microservices packaged in containers. But why exactly?

Kubernetes offers many features that enormously simplify the operation of large container fleets. We already know that it is possible to automatically scale the number of containers with Kubernetes or restart failing containers. What about the other features Kubernetes has to offer?

  • Automated rollouts and rollbacks: Allows you to deploy new versions and changes of your application (or its configuration) in a controlled way, monitoring the application’s health status and ensuring it is always running. K8s also allows you to roll back to the previous versions of the application, its image, or its configuration if something goes wrong.
  • Service discovery and load balancing: Allows different microservices in a cluster to easily find each other. In a set of pods representing the same microservice, each pod will have an IP address, but the set will have a single DNS name, allowing simple service discovery and load distribution.
  • Secret and configuration management: Allows you to handle microservice configuration and secrets without the need to rebuild container images or expose sensitive credentials – for example, when a service needs to access a database or has many configuration parameters that change.
  • Self-healing: Allows you to automatically restart containers that fail for any reason, automatically reschedule containers to another node if a worker node stops responding, restart containers that fail predefined health checks, and route requests to containers when only the applications inside are fully started and ready to serve.
  • Horizontal scaling: Allows you to scale a containerized application up or down by adding or reducing the number of pods running the application. This can be done manually or automatically, for example, based on CPU usage.
  • Batch execution: Allows you to schedule the execution of containers and flexibly manage batch processing or CI workloads.
  • Automatic bin packing: Allows you to automatically determine the best worker node to start the container based on requested resources, current cluster utilization, or other requirements. It also allows you to define workload priorities to handle different critical and non-critical applications.
  • Storage orchestration: Allows you to integrate and manage storage systems of your choice. Kubernetes can automatically provision and mount storage volumes when a pod is spawned and re-mount volumes to different nodes as needed.

This is a long list and yet not 100% complete. In the previous section, we saw that it is possible to extend the Kubernetes API to add new features. Today, Kubernetes has a rich ecosystem with numerous projects that extend Kubernetes and even allow you to manage other workloads besides containers. That’s right – Kubernetes can be used to orchestrate not just containers. There are several projects we should mention:

  • KubeVirt: A project that’s used to provision and manage virtual machines with Kubernetes alongside containers. This is used for cases when a workload cannot be easily containerized or for an ongoing process of application containerization where some applications still run in VMs.
  • Kubeless: A serverless computing framework that runs on top of Kubernetes. It adds FaaS capabilities to your K8s cluster and can serve as an alternative to cloud provider FaaS offerings.
  • Knative: Another serverless computing framework for Kubernetes that has recently been accepted to the CNCF. It was originally founded by Google and has been actively developed since 2018.
  • OpenFaas: Another serverless framework that can be used with Kubernetes or without in a standalone mode. Like the other two serverless frameworks, it supports many programming languages that can be used to write functions, including Golang, Java, Python, Ruby, C#, and others.

You don’t need to know further details about those projects for the KCNA exam or any other Kubernetes certification from CNCF. Just remember that it is possible to orchestrate VMs with the help of KubeVirt and offer FaaS on top of Kubernetes with projects such as Knative. If you’d like to learn more about these projects, you’ll find links in the Further reading section at the end of this chapter.

Note

Even though it is possible to manage VMs with the help of Kubernetes, it is still primarily used to orchestrate containers most of the time.

Before we jump into installing Kubernetes and trying its numerous features out, let’s look at an example of how K8s can be a part of the development workflow, as shown in Figure 5*.5*:

Figure 5.5 – Simple development workflow example with Kubernetes

The simplified workflow may look like this:

  1. A developer writes code for a new microservice and commits it to a GitHub repository. As you may recall, developers don’t need to learn a new programming language to run applications in containers.
  2. There should be a Dockerfile that defines the steps needed to package the application into a container image. Before the container image is built, automated tests are executed in the CI pipeline. If the tests are successful, a Docker image is built and pushed into the image registry.
  3. Next, the deployment of the container is triggered in the Kubernetes cluster. To run containers on Kubernetes, we need a pod spec definition in either YAML or JSON format. The easiest way to apply a spec is simply by using the kubectl tool, which must be configured to work with our K8s cluster.
  4. As the spec is applied, Kubernetes will take care of finding a suitable worker node to download the container image from the registry and start the pod with our containerized application. We can define it to run multiple replicas of applications for high availability requirements and to balance the load.
  5. This process can be repeated many times and Kubernetes can handle deploying the new image with a new application version in a rolling update manner where, for instance, only one replica will be replaced at a time.

A pod is just one example of a Kubernetes object, and it is the smallest deployable unit. In the next chapter, we’ll get to know other, more advanced resources that use Kubernetes controllers and provide more advanced features.

Kubernetes objects

Kubernetes objects are persistent entries that represent the state of the cluster, including information about which containerized applications run and on which nodes, resources available to these applications, and their associated policies (for example, restart policies, scheduling requirements, and so on).

Kubernetes objects are created the moment we apply a spec definition, and they are essentially a record of intent. Once the object has been created, Kubernetes will work to ensure that the object exists and is in the desired state. The time it might take to reach the desired state depends on many factors and might take as little as a second or as much as several minutes if, for instance, the container image that’s downloaded from the image registry is large and the network performance is poor.

Note

Kubernetes spec definition files are also known as Kubernetes manifests. It is a specification of API objects in JSON or YAML format.

Now that we are familiar with some of the basics, let’s try things out ourselves. In the next section, we are going to install a single node Kubernetes to gain hands-on experience.

Installing and exploring K8s with minikube

Section titled “Installing and exploring K8s with minikube”

Today, many projects allow you to quickly bootstrap a simple K8s cluster or a single node Kubernetes for learning or local development purposes. We will be using minikube, a project supported by an official Kubernetes SIG that focuses on cluster deployment and its life cycle. Other projects let you get similar results, such as Kind and CRC.

Important note

miniKube, Kind, and some other projects are not designed to set up production-ready Kubernetes clusters. Do not use these setups to run important workloads!

Quickly make sure that your system meets minikube’s requirements:

  • A recent version of Linux, macOS, or Windows
  • 2+ CPU cores
  • 2+ GB of free RAM
  • 20+ GB of free disk space
  • Internet connection
  • Administrator/superuser privileges
  • Container or VM manager (our Docker Engine installation from previous chapters can be used)

First, open the minikube start documentation (https://minikube.sigs.k8s.io/docs/start/) in your browser and select your operating system under the Installation section. Make sure that you select the Stable release type and the correct CPU architecture if you’re running on macOS or Linux.

Note

If you don’t have the curl tool installed, you can also simply copy the URL from the documentation, paste it into a new browser tab, and save it to your computer, just like any other downloadable. In such a case, the installation command should be executed in the same path where the minikube binary was saved.

Open your Terminal and execute the command for your OS, and enter the password if requested. For example, on macOS with an x86-64 CPU, the output might look like this:

$ curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 68.6M 100 68.6M 0 0 38.5M 0 0:00:01 0:00:01 --:--:-- 38.7M
$ sudo install minikube-darwin-amd64 /usr/local/bin/minikube
Password:

At this point, we are ready to start our local Kubernetes with the help of the minikube start command:

$ minikube start
😄 minikube v1.25.2 on Darwin 12.4
✨ Automatically selected the docker driver. Other choices: hyperkit, ssh
👍 Starting control plane node minikube in cluster minikube
🚜 Pulling base image ...
💾 Downloading Kubernetes v1.23.3 preload ...
> preloaded-images-k8s-v17-v1...: 505.68 MiB / 505.68 MiB 100.00% 40.26 Mi
> gcr.io/k8s-minikube/kicbase: 379.06 MiB / 379.06 MiB 100.00% 14.81 MiB p
🔥 Creating docker container (CPUs=2, Memory=4000MB) ...
🐳 Preparing Kubernetes v1.23.3 on Docker 20.10.12 ...
▪ kubelet.housekeeping-interval=5m
▪ Generating certificates and keys ...
▪ Booting up control plane ...
▪ Configuring RBAC rules ...
🌟 Enabled addons: storage-provisioner, default-storageclass
🏄 Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default

Note

You might have a newer version of Kubernetes and a slightly different output from minikube start. If you encounter an error, there likely will be a link to a related issue in the output that should help you to resolve the problem. If you are using another system than in the previous chapters, you’ll need to install Docker Engine first. Refer to Chapter 3, Getting Started with Containers, for details and the drivers’ documentation page of minikube (https://minikube.sigs.k8s.io/docs/drivers/). For other problems, check the minikube troubleshooting guide linked in the Further reading section of this chapter.

Now that we have Kubernetes up and running, we should be able to access its API using the kubectl CLI tool. You can go and download kubectl yourself, but minikube can do this for you. It is recommended to let minikube do this as it will automatically pick the correct version. All you need to do is run any command with kubectl for the first time – for example, a command to list all Kubernetes nodes in the cluster:

$ minikube kubectl get nodes
> kubectl.sha256: 64 B / 64 B [--------------------------] 100.00% ? p/s 0s
> kubectl: 50.65 MiB / 50.65 MiB [-------------] 100.00% 54.17 MiB p/s 1.1s
NAME STATUS ROLES AGE VERSION
minikube Ready control-plane,master 18m v1.23.3

Minikube has downloaded the K8s CLI for us and ran the command. At no surprise, we only have one node that is called minikube and has roles of control-plane and master.

Let’s see what is currently running in Kubernetes. You can list the pods using the kubectl get pods command:

$ minikube kubectl get pods
No resources found in default namespace.

As we can see, nothing is running at the moment because we’ve just bootstrapped a new cluster. Let’s run the same command with an extra option – that is, --all-namespaces (mind the two extra dashes between kubectl and get; they are needed to separate the kubectl from minikube arguments since both have their own sets of arguments):

$ minikube kubectl -- get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system coredns-64897985d-x28hm 1/1 Running 0 31m
kube-system etcd-minikube 1/1 Running 0 32m
kube-system kube-apiserver-minikube 1/1 Running 0 32m
kube-system kube-controller-manager-minikube 1/1 Running 0 32m
kube-system kube-proxy-hwv2p 1/1 Running 0 32m
kube-system kube-scheduler-minikube 1/1 Running 0 32m
kube-system storage-provisioner 1/1 Running 0 32m

The output has changed quite a bit and we can now see all those components of Kubernetes that we learned about at the beginning of this chapter: kube-apiserver, kube-controller-manager, kube-proxy, kube-scheduler, etcd, and a couple of other running in individual pods in the kube-system namespace.

Kubernetes namespaces

Kubernetes namespaces provide a grouping mechanism to separate Kubernetes objects within a cluster. It is common to use Kubernetes namespaces to group workloads per team, project, or application. The kube-system namespace is reserved for Kubernetes’s components.

Now, let’s see which namespaces we have in our new shiny Kubernetes:

$ minikube kubectl -- get namespaces
NAME STATUS AGE
default Active 56m
kube-node-lease Active 56m
kube-public Active 56m
kube-system Active 56m

The default namespace, as its name suggests, is simply a standard namespace where container workloads will be created by default. kube-node-lease is another reserved Kubernetes namespace for node heartbeats (checks that determine that the node is running) and kube-public is an automatically created namespace for public resources such as those required for cluster discovery.

Normal practice is to create new namespaces either per application, group of microservices working together, or per team. Let’s create a new namespace and call it kcna by executing kubectl -- create namespace kcna:

$ minikube kubectl -- create namespace kcna
namespace/kcna created

Note

You can also set up an alias for minikube kubectl, as suggested in the minikube documentation ($ alias kubectl="minikube kubectl --") to skip writing minikube every time. (Make sure that you remove it when you’re not using minikube anymore.)

Now, let’s deploy a containerized Nginx web server into our new kcna namespace. We can always set the namespace where we want to execute the kubectl command by adding the -- namespace argument:

$ minikube kubectl -- create -f https://k8s.io/examples/pods/simple-pod.yaml --namespace kcna
pod/nginx created

Here, we provided a pod spec file that is located in the examples shown on the https://k8s.io/ web page. The Kubernetes CLI is smart enough to download the file, validate the spec, and apply it to create the objects it defines – in this case, a single pod with Nginx. If we were to write this simple pod specification ourselves in YAML format, it would look like this:

$ cat simple-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80

Let’s see what each line of this spec file means.

apiVersion: v1 defines which version of the Kubernetes API we are using to create this object. As you know, Kubernetes APIs evolve from alpha to beta to stable versions. v1 is the stable version in this example:

  • kind: Pod – Defines the kind of object we are describing.
  • metadata: – Defines metadata for the object, such as name or further annotations.
  • name: nginx – Defines the name of the pod.
  • spec: – Defines the block where we describe the desired state of the object.
  • containers: – Defines the list of containers that are part of this pod.
  • - name: nginx – The name of the first container in the Pod. Multiple containers can run together in one pod.
  • image: nginx:1.14.2 – The name of the image (nginx) that can be optionally preceded by the image registry URL and followed by the image tag (1.14.2). If you run multiple containers in one pod, you’ll need to define the image and name for each one.
  • ports: – This is an optional informational block that tells us about which ports are to be exposed. Those are the ports where the process in the container is listening on. However, not specifying this block does not prevent ports from being exposed.
  • - containerPort: 80 – This is port 80 in this example.

Note

The indentation is very important in YAML format and one missing space or an extra space can make it invalid. kubectl will complain if there are parsing errors when applying a specification. It is recommended to copy example files from this book’s GitHub repository to avoid typos and formatting mistakes.

Alright, so, what happened with our Nginx pod?

$ minikube kubectl -- get pods --namespace kcna
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 10m

It is in a Running status and 1/1 (one out of one) containers in the pod are ready. There are several statuses the pod might be in:

  • Pending: The specification has been accepted by Kubernetes and, currently, the pod is waiting to be scheduled or for a requested container image to be downloaded from the image registry.
  • Running: The pod is assigned to a certain node and all containers in the pod have been created. At least one container is running.
  • Succeeded: All the containers in the pod have successfully finished/exited with a good exit code (for example zero). This happens when, for example, an application in a container has gracefully shut down.
  • Failed: All the containers in the pod terminated and at least one has failed; for example, it has exited with a non-zero exit code.
  • Unknown: The state of the pod cannot be obtained. This might happen when a node where the pod should be running is unreachable, for example, due to network issues.
  • ErrImagePull: The image specified in the manifest cannot be retrieved (pulled). This might be due to a wrong image name or wrong tag that does not exist in the registry.

Additionally, you might encounter a ContainerCreating or Terminating status describing the startup or termination phase of pod containers, respectively.

Currently, our Nginx pod does nothing; it does not serve any applications or content except for its default static page. In the next chapter, we will learn how to expose and access applications in Kubernetes with the Service concept. For now, try to get more details about our nginx pod using the kubectl describe command:

$ minikube kubectl -- describe pods nginx --namespace kcna

You’ll find a lot of information about the pod, such as the node where it runs, its start time, IP address, environment variables, recent events, and much more. This information is very helpful for cases when we need to debug failing pods or applications.

Now that we have used kubectl a bit, let’s try the Kubernetes dashboard as well. Minikube offers a convenient one-command dashboard installation with minikube dashboard:

$ minikube dashboard
🔌 Enabling dashboard ...
▪ Using image kubernetesui/dashboard:v2.3.1
▪ Using image kubernetesui/metrics-scraper:v1.0.7
🤔 Verifying dashboard health ...
🚀 Launching proxy ...
🤔 Verifying proxy health ...
🎉 Opening http://127.0.0.1:55089/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/ in your default browser...

At this point, the dashboard will be installed into a new kubernetes-dashboard namespace and your browser should automatically open it in a new tab (in case it did not, try executing minikube dashboard --url to get the URL of the dashboard). You’ll need to switch to another namespace in the top-left corner drop-down menu as there is nothing currently running in the default namespace. If you switch to the kcna namespace, you’ll be able to see our nginx pod, whereas if you switch to kube-system, you’ll see the Kubernetes control plane components that we described previously in this chapter. You may notice that, besides pods, there are Deployment, Daemon Set and Replica Set workloads. Those will be the topic of the next chapter, where we will see how these can be used to create pods and learn about the features of those K8s resources.

Feel free to explore the dashboard a little more by yourself; when you’re done, delete our Nginx pod using the dashboard or via the kubectl delete command. To interrupt minikube dashboard, you can use Ctrl + C shortcut:

$ minikube kubectl -- delete pods nginx --namespace kcna
pod "nginx" deleted

Note

kubectl is a user-friendly tool that allows you to type pod, pods, or simply po, all of which mean the same thing. It also has a lot of convenient short names, such as ns, for namespaces. To list all short names, run minikube kubectl api-resources.

If you are about to shut down your workstation before moving on to the next chapter, you can also temporarily stop your Kubernetes node by executing the minikube stop command:

$ minikube stop
✋ Stopping node "minikube" ...
🛑 Powering off "minikube" via SSH ...
🛑 1 node stopped.

This has been a long and very intense chapter, so congrats on making it this far! Take a break before moving on to the next chapter and make sure you answer the questions provided.

In this chapter, we finally got our hands on Kubernetes. We learned a lot about its architecture, components, and API. Kubernetes clusters consist of control plane (also known as the master) and worker nodes, where control plane nodes run K8s management components and worker nodes run the actual containerized applications with the help of kubelet, container runtime, and kube-proxy. Among the master node components, there’s kube-apiserver, etcd, kube-scheduler, kube-controller-manager, and, optionally, cloud-controller-manager.

We saw that a pod is the smallest deployable unit of Kubernetes and that it allows us to run individual containers as well as multiple containers together on K8s. Containers inside one pod are coupled and can share storage, network, and memory. The secondary container in the pod is typically called the sidecar and can help the container run the main application by doing log aggregation, for example.

The Kubernetes API is declarative. When we work with K8s, we describe the desired state of resources in the cluster; Kubernetes ensures that the current state reaches the desired state after object creation. Due to rapid development, Kubernetes APIs are grouped and multi-versioned, and by default only enable beta and stable (GA) features. There are several ways to access the Kubernetes API, with the kubectl CLI and dashboard being the most popular ones. One of the specialties of K8s is its ability to extend its APIs through CRDs and aggregation layers.

When it comes to features, Kubernetes has a lot to offer, ranging from automatic rollouts, service discovery, and secret management to auto-scaling, self-healing, and even storage orchestration. We will try many of those features in practice in the next few chapters. It is also possible to use Kubernetes to manage virtual machines or provide FaaS with the help of separate projects such as KubeVirt and Knative.

In the last section, we installed a simple one-node Kubernetes deployment using the minikube project and learned about the concept of Kubernetes namespaces for resource separation and grouping. We also created a pod with a single Nginx container and explored the minimal pod spec definition in YAML format.

In the next chapter, we will learn about other Kubernetes resources and their usage. We will learn how to configure and scale multi-container applications with Kubernetes, how to run stateful workloads with Kubernetes, and learn about exposing applications running in K8s.

As we conclude, here is a list of questions for you to test your knowledge regarding this chapter’s material. You will find the answers in the Assessments section of the Appendix:

  1. Which of the following is the smallest schedulable unit in Kubernetes?
    1. Container 2. Sidecar 3. Pod 4. Deployment
  2. Containers running in one pod share which of the following options (pick multiple)?
    1. Name 2. Storage 3. Networking 4. Memory
  3. Which of the following types of nodes does Kubernetes have (pick multiple)?
    1. Secondary 2. Master 3. Worker 4. Primary
  4. Which of the following are components of control plane nodes (pick multiple)?
    1. Docker, kube-scheduler, cloud-controller-manager 2. kube-master-server, kubelet, kube-proxy 3. kube-scheduler, kube-controller-manager 4. kube-api-server, etcd
  5. Which of the following K8s cluster configuration can be recommended?
    1. 1 master node, 5 worker nodes 2. 2 master nodes, 3 worker nodes 3. 2 master nodes, 20 worker nodes 4. 3 master nodes, 10 worker nodes
  6. Which of the following components are used to store cluster state in Kubernetes?
    1. kube-api-server 2. kube-volume 3. kubelet 4. etcd
  7. Which of the following components is used by Kubernetes to download images and start containers?
    1. Kubelet 2. Container runtime 3. etcd 4. kube-proxy
  8. Which of the following components is responsible for Kubernetes controller processes?
    1. kube-api-server 2. kube-proxy 3. kube-controller-manager 4. kube-scheduler
  9. What can be used to access the Kubernetes API (pick multiple)?
    1. kubeadmin 2. kubectl 3. kubelet 4. dashboard
  10. Kubernetes has a declarative API. What does this mean?
    1. We always need to declare a YAML spec file to use the K8s API 2. We declare the desired state and K8s will reach it once 3. We tell Kubernetes exactly what to do with which resource 4. We declare the desired state and K8s will constantly try to reach it
  11. Which of the following Kubernetes API versions are enabled by default (pick multiple)?
    1. Alpha 2. Beta 3. Gamma 4. Stable
  12. How can you extend the Kubernetes API with new features (pick multiple)?
    1. Code Resource Definitions 2. Aggregation layers 3. Extension layers 4. Custom Resource Definitions
  13. Which of the following projects allows you to extend Kubernetes beyond container orchestration (pick multiple)?
    1. Knative for FaaS 2. Linkerd for IPAM 3. Kvirt for VM orchestration 4. KubeVirt for VM orchestration
  14. What helps detect the difference between the current and desired state of Kubernetes resources?
    1. Container runtime 2. Kubernetes scheduler 3. Custom Resource Definition 4. Reconciliation loop
  15. What are secondary containers running in pod called?
    1. Flatcars 2. Sidecars 3. Podcars 4. Helpcars
  16. Which of the following formats is used to write Kubernetes spec files?
    1. CSV 2. Protobuf 3. YAML 4. Marshal
  17. Which of the following Kubernetes components is responsible for allocating new pods to nodes?
    1. kube-api 2. kube-proxy 3. kube-scheduler 4. kube-controller-manager
  18. Which of the following K8s CLI commands can be used to list pods in the development namespace?
    1. kubectl list pods - n development 2. kubectl get pods -- namespace development 3. kubectl show pods -- namespace development 4. kubectl get pods --all-namespaces
  19. Which of the following K8s CLI commands can be used to list all the namespaces in the cluster?
    1. kubectl list namespaces --all-namespaces 2. kubectl show namespaces 3. kubectl get namespaces 4. kubectl get all
  20. Which of the following pod statuses means its container(s) are currently executing?
    1. Executing 2. Succeeded 3. Running 4. ContainerCreated
  21. Which of the following pod statuses means all its containers are running (pick multiple)?
    1. 100% 2. 1/2 3. 2/2 4. 1/1

To learn more about the topics that were covered in this chapter, take a look at the following resources: