Kubernetes
Prelude: From Monolith to Microservices
The trend nowadays is that we are moving to more modern ways of developing applications. Monolith applications are increasingly being phased out into loosely coupled microservices.
Container Orchestration
What are containers?
Containers are an application-centric method to deliver high-performing, scalable applications on any infrastructure of your choice.
A container image bundles the application along with its runtime, libraries, and dependencies, and it represents the source of a container deployed to offer an isolated executable environment for the application.
Container orchestration is the process of managing, scheduling, and coordinating the deployment and scaling of containerized applications across a distributed system.
They can be deployed on the infrastructure of our choice — on bare metal, VMs, cloud, etc.
Some of the benefits:
- Schedule containers to run on hosts in the cluster based on resource availability.
- Enable containers in a cluster to communicate with each other regardless of the host they are deployed to in the cluster.
- Bind containers and storage resources.
- Group sets of similar containers and bind them to load-balancing constructs to simplify access to containerized applications by creating an interface, a level of abstraction between the containers and the client.
- Manage and optimize resource usage.
- Allow for implementation of policies to secure access to applications running inside containers.
Kubernetes
Kubernetes (k8s) is an open-source system for automating deployment, scaling and management of containerised applications.
- Automatic bin packing Kubernetes automatically schedules containers based on resource needs and constraints, to maximize utilization without sacrificing availability.
- Self-healing Kubernetes automatically replaces and reschedules containers from failed nodes. It terminates and then restarts containers that become unresponsive to health checks, based on existing rules/policy. It also prevents traffic from being routed to unresponsive containers.
- Horizontal scaling Kubernetes scales applications manually or automatically based on CPU or custom metrics utilization.
- Service discovery and load balancing Containers receive IP addresses from Kubernetes, while it assigns a single Domain Name System (DNS) name to a set of containers to aid in load-balancing requests across the containers of the set.
More other features like automated rollouts and rollbacks, storage orchestration just to name a few.
Kubernetes Architecture
At the very high level, K8s is a cluster of compute systems categorized by their distinct roles:
- One or more control plane nodes
- One or more worker nodes
Control Plane Node
The control plane node provides a running environment for the control plane agents responsible for managing the state of a K8s cluster.
A control plane node runs the following essential control plane components and agents
- API server
- Scheduler
- Controller Manager
- Key-Value Data Store
kube-apiserver
All the administrative tasks are coordinated by the kube-apiserver, a central control plane component running on the control plane node. The API Server intercepts RESTful calls, then validates and processes them. During processing, the API Server reads the Kubernetes cluster’s current state from the KV store, and after a call’s execution, the resulting state of the Kubernetes cluster is saved in the KV store for persistence.
The API Server is the only control plane component to talk to the KV store, both to read from and to save Kubernetes cluster state information.
kube-scheduler
Assigns new workload objects to nodes, based on the current K8s cluster state and new workload object’s requirements. How? It obtains resource usage data from the KV store via API Server.
The scheduling algorithm is non-trivial and takes into account many factors, such as QoS requirements, data locality, affinity and etc (and also customisable). The outcome of the algorithm is communicated back to the API server, which then delegates the workload deployment with other control plane agents (scheduler and kubelet).
Controller Managers
They are components of the control plane node running controllers or operator processes to regulate the state of the K8s cluster. They continuously compare the cluster’s desired state with its current state, in case of a mismatch, corrective action is taken.
etcd (KV store)
Used to persist a K8s cluster’s state. Note that only the API server is able to communicate with it.
etcdctl is a command line tool to interact with etcd, and it provides snapshot save and restore capabilities.
Some K8s cluster bootstrapping tools, such as kudeadm, by default, provision stacked etcd control plane nodes, where the data store runs alongside and shares resources with the other control plane components on the same control plane node.
For data store isolation from the control plane components, the bootstrapping process can be configured for an external etcd topology, where the data store is provisioned on a dedicated separate host, thus reducing the chances of an etcd failure.
Both stacked and external etcd topologies support HA configurations and etcd is based on the Raft Consensus Algorithm.
Worker node
Pods are scheduled on worker nodes. A pod is the smallest scheduling work unit in K8s. It’s a logical collection of 1 or more containers scheduled together, and the collection can be started, stopped, or rescheduled as a single unit of work.
Container Runtime
K8s requires a container runtime on the node where a Pod and its containers are to be scheduled. A runtime is required on each node of a K8s cluster, both control plane and worker.
kubelet
It’s an agent running on every node in a K8s cluster (both control plane and worker nodes). It communicates with the control plane, mainly receiving Pod definitions from the API Server, and manages the containers in those Pods by interacting with the container runtime on the node. It also monitors the health and resources of the running Pods.
The kubelet uses the Container Runtime Interface (CRI) to connect to various container runtimes via a CRI shim. This shim acts as a bridge between the kubelet and the container runtime, allowing for container and image management. The CRI has two main services:
- ImageService: Handles image-related operations (e.g., pulling container images).
- RuntimeService: Manages Pods and container-related operations (e.g., starting and stopping containers).
The kubelet communicates with the CRI shim using gRPC, where the kubelet is the client and the CRI shim is the server, ensuring container operations are abstracted and compatible with different container runtimes. (docker, crio)
kube proxy
The k8s proxy runs on each node. It monitors the changes that happen to Service objects and their endpoints. If changes occur, it translates them into actual network rules inside the node. It’s responsible for providing service discovery and load balancing within the cluster for the Service.
Kube proxy helps with Service to pod mapping by maintaining a network routing table (iptables) that maps Service IP addresses to the IP addresses of the pod that belongs to the Service. When a request is made to a Service, kube proxy uses this mapping to forward the request to a pod belonging to the service.
Networking
Decoupled microservices based applications rely heavily on networking in order to mimic the tight-coupling once available in the monolithic era.
Container-to-Container Communication Inside Pods
When a grouping of containers defined by a Pod is started, a special infrastructure Pause container is initialized by the Container Runtime for the sole purpose of creating a network namespace (isolated network namespace) for the Pod (see each other’s IPC resources). All additional containers created through user requests, running inside the Pod will share the Pause container’s network namespace so that they can all talk to each other via localhost.
Pod-to-Pod Communication Across Nodes
Each Pod is like a virtual machine (VM) with its own unique IP address. This model, known as IP-per-Pod, allows seamless communication between Pods, similar to how VMs interact on the same network.
External-to-Pod Communication
Get Tzehenn’s stories in your inbox
Join Medium for free to get updates from this writer.
By exposing services to the external world with the aid of kube-proxy, applications become accessible from outside the cluster over a virtual IP address and a dedicated port number.
Kubernetes Building Blocks
Kubernetes Object Model
They represent the desired state of the system and are defined using YAML or JSON. Shown below are some examples of object types.
Nodes
- Control Plane Nodes
- Worker Nodes
Pods
- Containers in the pod are scheduled together on the same host as the Pod.
- Share the same network namespace.
- Have access to mount the same external storage (volumes) and other common dependencies.
- Cannot self-heal, so they are used with controllers/operators to heal
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
run: nginx-pod
spec:
containers:
- name: nginx-pod
image: nginx:1.22.1
ports:
- containerPort: 80Namespaces
- Partition the cluster into virtual sub-clusters (resource quotas), providing isolation
Deployments
- Part of the control plane node’s controller manager
- Manages lifecycle of a set of replicated pods, directly manages ReplicaSets for application scaling
- RollingUpdate strategy ensures minimal downtime, as old pods are incrementally retired to make way for new pods
ReplicaSets
- Scales to an arbitrary number of pod instances (limited by node’s resources)
- If one pod is down, the ReplicaSet detects that the current state is no longer matching the desired state and triggers a request for an additional Pod to be created, thus ensuring that the current state matches the desired state.
- Usually indirectly managed by Deployments
DaemonSets
- Operators designed to manage node agents
- Present a distinct feature that enforces a single Pod replica to be placed per Node, on a subset of Nodes
- Commonly used in cases when we need to collect monitoring data for e.g. from all Nodes, to ensure that we have a specific type of Pod running on all Nodes at all times for (kube-proxy)
Services
Service
Higher-level abstraction called, which logically groups Pods and defines a process to access them, achieved via Labels and Selectors. Changes in endpoints caused by scaling and HA are invisible to the user.
The user/client now connects to a Service via its ClusterIP, which forwards traffic to one of the Pods attached to it. A Service provides load balancing by default while selecting the Pods for traffic forwarding.
P.S. containerPort must be the same as targetPort
Traffic Policies
- Cluster (default): allows kube-proxy to target all ready Endpoints of the Service in the load-balancing process
- Local: Isolates the load-balancing process to only include the Endpoints of the Service located on the same node as the requester Pod, or perhaps the node that captures inbound external traffic on its NodePort.
2 types of traffic: Internal or external
ServiceType
ClusterIP
Default ServiceType. A Service receives a Virtual IP address, known as its ClusterIP. This Virtual IP address is used for communicating with the Service and is accessible only from within the cluster.
NodePort
Useful when we want to make our Services accessible from the external world. The end-user connects to any worker node on the specified high-port (30000–32767), which proxies the request internally to the ClusterIP of the Service, then the request is forwarded to the applications running inside the cluster. Let’s not forget that the Service is load balancing such requests, and only forwards the request to one of the Pods running the desired application.
LoadBalancer
- NodePort and ClusterIP are automatically created, and the external load balancer will route to them.
- The Service is exposed at a static port on each worker node.
- The Service is exposed externally using the underlying cloud provider’s load balancer feature.
Kubernetes Volume Management
Ephemeral Volume
Ephemeral Volumes are storage abstractions that allow various storage technologies to be used by K8s and offered to containers in Pods as storage media. It’s essentially a mount point on the container’s file system backed by a storage medium. The storage medium, content and access mode are determined by the Volume Type.
In K8s, an ephemeral Volume is linked to a Pod and can be shared among the containers of that Pod. Although the ephemeral Volume has the same life span as the Pod, the ephemeral Volume outlives the containers of the Pod — this allows data to be preserved across container restarts.
Volume Type
A directory which is mounted inside a Pod is backed by the underlying Volume Type. A Volume Type decides the properties of the directory, like size, content, default access modes, etc.
Persistent Volume
- PVs are a cluster-level resource that exists independently of any specific pod, making them reusable and shareable across pods.
- A PV can be backed by many types of storage, such as network file systems (NFS), cloud provider-managed storage (AWS EBS, GCE Persistent Disk, etc.), local storage, or other storage systems (e.g., Ceph, GlusterFS).
Persistent Volume Claim
A PVC is a request by a user for storage. It specifies the size and access mode (e.g., read-write) that the pod needs.
When a PVC is created, K8s looks for an available PV that matches the request. If a suitable PV is found, it is bound to the PVC, allowing the pod to access the underlying storage.
After a successful bound, the PVC resource can be used by the containers of the Pod. Once a user finishes his work, the attached PVs can be released. Whether or not the data remains after releasing depends on the Reclaim Policy.
Advanced Topics
ConfigMaps and Secrets
ConfigMaps in K8s are a way to store configuration data in KV pairs. They allow you to decouple configuration settings from your application code, making your application more flexible and portable.
Why do we need it?
Imagine you have an application, and it needs certain configuration settings (like database URLs, API keys, or environment-specific values). Instead of hardcoding these settings into the application, you store them in a ConfigMap. This way, the application can load the configuration dynamically from K8s, and you can easily change the configuration without modifying the app itself.
Ingress
Ingress in Kubernetes is an API object that manages external access to services within a cluster, typically HTTP and HTTPS traffic. It defines a set of rules that control how external users access services running inside a Kubernetes cluster. NodePort requires manual port management, which is not suited for production environments, unlike Ingress. With Ingress, users do not connect directly to a Service. Users reach the Ingress endpoint and from there, the request is forwarded to the desired Service.
To allow the inbound connection to reach the cluster Services, Ingress configures a Layer 7 HTTP/HTTPS load balancer for Services and provides the following:
- TLS (Transport Layer Security)
- Name-based virtual hosting
- Fanout routing
- Load Balancing




