Tutorials - Kubernetes
Tutorials - Kubernetes
Tutorials
1: Hello Minikube
2: Learn Kubernetes Basics
2.1: Create a Cluster
2.1.1: Using Minikube to Create a Cluster
2.2: Deploy an App
2.2.1: Using kubectl to Create a Deployment
2.3: Explore Your App
2.3.1: Viewing Pods and Nodes
2.4: Expose Your App Publicly
2.4.1: Using a Service to Expose Your App
2.5: Scale Your App
2.5.1: Running Multiple Instances of Your App
2.6: Update Your App
2.6.1: Performing a Rolling Update
3: Configuration
3.1: Example: Configuring a Java Microservice
3.1.1: Externalizing config using MicroProfile, ConfigMaps and Secrets
3.2: Configuring Redis using a ConfigMap
4: Security
4.1: Apply Pod Security Standards at the Cluster Level
4.2: Apply Pod Security Standards at the Namespace Level
4.3: Restrict a Container's Access to Resources with AppArmor
4.4: Restrict a Container's Syscalls with seccomp
5: Stateless Applications
5.1: Exposing an External IP Address to Access an Application in a Cluster
5.2: Example: Deploying PHP Guestbook application with Redis
6: Stateful Applications
6.1: StatefulSet Basics
6.2: Example: Deploying WordPress and MySQL with Persistent Volumes
6.3: Example: Deploying Cassandra with a StatefulSet
6.4: Running ZooKeeper, A Distributed System Coordinator
7: Services
7.1: Connecting Applications with Services
7.2: Using Source IP
7.3: Explore Termination Behavior for Pods And Their Endpoints
This section of the Kubernetes documentation contains tutorials. A tutorial shows how to
accomplish a goal that is larger than a single task. Typically a tutorial has several sections,
each of which has a sequence of steps. Before walking through each tutorial, you may want to
bookmark the Standardized Glossary page for later references.
Basics
Kubernetes Basics is an in-depth interactive tutorial that helps you understand the
Kubernetes system and try out some basic Kubernetes features.
Hello Minikube
Configuration
Example: Configuring a Java Microservice
https://kubernetes.io/docs/tutorials/_print/ 1/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Stateless Applications
Exposing an External IP Address to Access an Application in a Cluster
Stateful Applications
StatefulSet Basics
Services
Connecting Applications with Services
Using Source IP
Security
Apply Pod Security Standards at Cluster level
Apply Pod Security Standards at Namespace level
AppArmor
seccomp
What's next
If you would like to write a tutorial, see Content Page Types for information about the tutorial
page type.
https://kubernetes.io/docs/tutorials/_print/ 2/155
6/6/23, 4:10 PM Tutorials | Kubernetes
1 - Hello Minikube
This tutorial shows you how to run a sample app on Kubernetes using minikube. The tutorial
provides a container image that uses NGINX to echo back all the requests.
Objectives
Deploy a sample application to minikube.
Run the app.
View application logs.
You also need to install kubectl . See Install tools for installation instructions.
Now, switch back to the terminal where you ran minikube start .
Note:
The dashboard command enables the dashboard add-on and opens the proxy in the
default web browser. You can create Kubernetes resources on the dashboard such
as Deployment and Service.
If you are running in an environment as root, see Open Dashboard with URL.
By default, the dashboard is only accessible from within the internal Kubernetes
virtual network. The dashboard command creates a temporary proxy to make the
dashboard accessible from outside the Kubernetes virtual network.
To stop the proxy, run Ctrl+C to exit the process. After the command exits, the
dashboard remains running in the Kubernetes cluster. You can run the dashboard
command again to create another proxy to access the dashboard.
https://kubernetes.io/docs/tutorials/_print/ 3/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Create a Deployment
A Kubernetes Pod is a group of one or more Containers, tied together for the purposes of
administration and networking. The Pod in this tutorial has only one Container. A Kubernetes
Deployment checks on the health of your Pod and restarts the Pod's Container if it terminates.
Deployments are the recommended way to manage the creation and scaling of Pods.
1. Use the kubectl create command to create a Deployment that manages a Pod. The
Pod runs a Container based on the provided Docker image.
Note: For more information about kubectl commands, see the kubectl overview.
Create a Service
By default, the Pod is only accessible by its internal IP address within the Kubernetes cluster.
To make the hello-node Container accessible from outside the Kubernetes virtual network,
you have to expose the Pod as a Kubernetes Service.
1. Expose the Pod to the public internet using the kubectl expose command:
https://kubernetes.io/docs/tutorials/_print/ 4/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The --type=LoadBalancer flag indicates that you want to expose your Service outside of
the cluster.
The application code inside the test image only listens on TCP port 8080. If you used
kubectl expose to expose a different port, clients could not connect to that other port.
This opens up a browser window that serves your app and shows the app's response.
Enable addons
The minikube tool includes a set of built-in addons that can be enabled, disabled and opened
in the local Kubernetes environment.
addon-manager: enabled
dashboard: enabled
default-storageclass: enabled
efk: disabled
freshpod: disabled
gvisor: disabled
helm-tiller: disabled
ingress: disabled
ingress-dns: disabled
logviewer: disabled
metrics-server: disabled
nvidia-driver-installer: disabled
nvidia-gpu-device-plugin: disabled
registry: disabled
registry-creds: disabled
storage-provisioner: enabled
storage-provisioner-gluster: disabled
https://kubernetes.io/docs/tutorials/_print/ 5/155
6/6/23, 4:10 PM Tutorials | Kubernetes
3. View the Pod and Service you created by installing that addon:
4. Disable metrics-server :
Clean up
Now you can clean up the resources you created in your cluster:
minikube stop
https://kubernetes.io/docs/tutorials/_print/ 6/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# Optional
minikube delete
If you want to use minikube again to learn more about Kubernetes, you don't need to delete
it.
What's next
Learn more about Deployment objects.
Learn more about Deploying applications.
Learn more about Service objects.
https://kubernetes.io/docs/tutorials/_print/ 7/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The tutorials will cease to function after the 31st of March, 2023. For more
information, see "Free Katacoda Kubernetes Tutorials Are Shutting Down."
Kubernetes Basics
This tutorial provides a walkthrough of the basics of the
Kubernetes cluster orchestration system. Each module contains
some background information on major Kubernetes features and
concepts, and includes an interactive online tutorial. These
interactive tutorials let you manage a simple cluster and its
containerized applications for yourself.
https://kubernetes.io/docs/tutorials/_print/ 8/155
6/6/23, 4:10 PM Tutorials | Kubernetes
https://kubernetes.io/docs/tutorials/_print/ 9/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Learn what a Kubernetes cluster is.
Learn what Minikube is.
Start a Kubernetes cluster on your computer.
Kubernetes Clusters
Kubernetes coordinates a highly available cluster of
Summary:
computers that are connected to work as a single unit. Kubernetes
The abstractions in Kubernetes allow you to deploy cluster
containerized applications to a cluster without tying them Minikube
specifically to individual machines. To make use of this
new model of deployment, applications need to be
packaged in a way that decouples them from individual
hosts: they need to be containerized. Containerized Kubernetes is a
applications are more flexible and available than in past production-grade,
deployment models, where applications were installed open-source platform
directly onto specific machines as packages deeply that orchestrates the
integrated into the host. Kubernetes automates the placement (scheduling)
distribution and scheduling of application containers and execution of
across a cluster in a more efficient way. Kubernetes is application containers
an open-source platform and is production-ready. within and across
computer clusters.
A Kubernetes cluster consists of two types of resources:
Cluster Diagram
Node
Control Plane
Node Processes
Kubernetes Cluster
https://kubernetes.io/docs/tutorials/_print/ 10/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Now that you know more about what Kubernetes is, visit
Hello Minikube to try this out on your computer.
https://kubernetes.io/docs/tutorials/_print/ 11/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Learn about application Deployments.
Deploy your first app on Kubernetes with kubectl.
Kubernetes Deployments
Once you have a running Kubernetes cluster, you can
Summary:
deploy your containerized applications on top of it. To do Deployments
so, you create a Kubernetes Deployment. The Kubectl
Deployment instructs Kubernetes how to create and
update instances of your application. Once you've created
a Deployment, the Kubernetes control plane schedules
the application instances included in that Deployment to A Deployment is
run on individual Nodes in the cluster. responsible for
creating and updating
Once the application instances are created, a Kubernetes instances of your
Deployment controller continuously monitors those application
instances. If the Node hosting an instance goes down or is
deleted, the Deployment controller replaces the instance
with an instance on another Node in the cluster. This
provides a self-healing mechanism to address machine
failure or maintenance.
Node
containerized app
Deployment
Control Plane
node processes
Kubernetes Cluster
https://kubernetes.io/docs/tutorials/_print/ 12/155
6/6/23, 4:10 PM Tutorials | Kubernetes
kubectl basics
The common format of a kubectl command is: kubectl
action resource
Check that kubectl is installed and you can see both the
client and the server versions.
Deploy an app
Let’s deploy our first app on Kubernetes with the kubectl create deployment command.
We need to provide the deployment name and app image location (include the full
repository url for images hosted outside Docker hub).
Great! You just deployed your first application by creating a deployment. This performed
a few things for you:
searched for a suitable node where an instance of the application could be run (we
have only 1 available node)
scheduled the application to run on that Node
https://kubernetes.io/docs/tutorials/_print/ 13/155
6/6/23, 4:10 PM Tutorials | Kubernetes
configured the cluster to reschedule the instance on a new Node when needed
We see that there is 1 deployment running a single instance of your app. The instance is
running inside a container on your node.
We will cover other options on how to expose your application outside the kubernetes
cluster in Module 4.
The kubectl command can create a proxy that will forward communications into the
cluster-wide, private network. The proxy can be terminated by pressing control-C and
won't show any output while its running.
kubectl proxy
We now have a connection between our host (the online terminal) and the Kubernetes
cluster. The proxy enables direct access to the API from these terminals.
You can see all those APIs hosted through the proxy endpoint. For example, we can query
the version directly through the API using the curl command:
curl http://localhost:8001/version
Note: If Port 8001 is not accessible, ensure that the kubectl proxy that you started
above is running in the second terminal.
The API server will automatically create an endpoint for each pod, based on the pod
name, that is also accessible through the proxy.
First we need to get the Pod name, and we'll store in the environment variable POD_NAME:
You can access the Pod through the proxied API, by running:
curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME/
In order for the new Deployment to be accessible without using the proxy, a Service is
required which will be explained in the next modules.
https://kubernetes.io/docs/tutorials/_print/ 14/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Learn about Kubernetes Pods.
Learn about Kubernetes Nodes.
Troubleshoot deployed applications.
Pods overview
https://kubernetes.io/docs/tutorials/_print/ 15/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Node overview
https://kubernetes.io/docs/tutorials/_print/ 16/155
6/6/23, 4:10 PM Tutorials | Kubernetes
If no pods are running, please wait a couple of seconds and list the Pods again. You can
continue once you see one Pod running.
Next, to view what containers are inside that Pod and what images are used to build
those containers we run the kubectl describe pods command:
We see here details about the Pod’s container: IP address, the ports used and a list of
events related to the lifecycle of the Pod.
The output of the describe subcommand is extensive and covers some concepts that we
didn’t explain yet, but don’t worry, they will become familiar by the end of this bootcamp.
Note: the describe subcommand can be used to get detailed information about most of the
Kubernetes primitives, including Nodes, Pods, and Deployments. The describe output is
designed to be human readable, not to be scripted against.
kubectl proxy
Now again, we'll get the Pod name and query that pod directly through the proxy. To get
the Pod name and store it in the POD_NAME environment variable:
curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME/proxy/
Note: We don't need to specify the container name, because we only have one container inside
the pod.
Again, it's worth mentioning that the name of the container itself can be omitted since we
only have a single container in the Pod.
We have now an open console on the container where we run our NodeJS application.
The source code of the app is in the server.js file:
cat server.js
curl http://localhost:8080
Note: here we used localhost because we executed the command inside the NodeJS Pod. If
you cannot connect to localhost:8080, check to make sure you have run the kubectl exec
command and are launching the command from within the Pod
https://kubernetes.io/docs/tutorials/_print/ 18/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Learn about a Service in Kubernetes
Understand how labels and selectors relate to a
Service
Expose an application outside a Kubernetes cluster
using a Service
https://kubernetes.io/docs/tutorials/_print/ 20/155
6/6/23, 4:10 PM Tutorials | Kubernetes
If no pods are running then it means the interactive environment is still reloading its
previous state. Please wait a couple of seconds and list the Pods again. You can continue
once you see the one Pod running.
We have a Service called kubernetes that is created by default when minikube starts the
cluster. To create a new service and expose it to external traffic we'll use the expose
command with NodePort as parameter.
We have now a running Service called kubernetes-bootcamp. Here we see that the Service
received a unique cluster-IP, an internal port and an external-IP (the IP of the Node).
To find out what port was opened externally (for the type: NodePort Service) we’ll run
the describe service subcommand:
Create an environment variable called NODE_PORT that has the value of the Node port
assigned:
Now we can test that the app is exposed outside of the cluster using curl , the IP address
of the Node and the externally exposed port:
Let’s use this label to query our list of Pods. We’ll use the kubectl get pods command
with -l as a parameter, followed by the label values:
Get the name of the Pod and store it in the POD_NAME environment variable:
To apply a new label we use the label subcommand followed by the object type, object
name and the new label:
This will apply a new label to our Pod (we pinned the application version to the Pod), and
we can check it with the describe pod command:
https://kubernetes.io/docs/tutorials/_print/ 21/155
6/6/23, 4:10 PM Tutorials | Kubernetes
We see here that the label is attached now to our Pod. And we can query now the list of
pods using the new label:
This confirms that our Service was removed. To confirm that route is not exposed
anymore you can curl the previously exposed IP and port:
This proves that the application is not reachable anymore from outside of the cluster. You
can confirm that the app is still running with a curl from inside the pod:
We see here that the application is up. This is because the Deployment is managing the
application. To shut down the application, you would need to delete the Deployment as
well.
https://kubernetes.io/docs/tutorials/_print/ 22/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Scale an app using kubectl.
Scaling an application
Previously we created a Deployment, and then exposed it
Summary:
publicly via a Service. The Deployment created only one Scaling a
Pod for running our application. When traffic increases, Deployment
we will need to scale the application to keep up with user
demand.
If you haven't worked through the earlier sections, start You can create from
from Using minikube to create a cluster. the start a Deployment
Scaling is accomplished by changing the number of with multiple instances
replicas in a Deployment using the --replicas
parameter for the
kubectl create
deployment command
Scaling overview
https://kubernetes.io/docs/tutorials/_print/ 23/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Scaling a deployment
To list your deployments use the get deployments subcommand: kubectl get
deployments
We should have 1 Pod. If not, run the command again. This shows:
DESIRED displays the desired number of replicas of the application, which you define
when you create the Deployment. This is the desired state.
CURRENT displays how many replicas are currently running.
Next, let’s scale the Deployment to 4 replicas. We’ll use the kubectl scale command,
followed by the deployment type, name and desired number of instances:
The change was applied, and we have 4 instances of the application available. Next, let’s
check if the number of Pods changed:
There are 4 Pods now, with different IP addresses. The change was registered in the
Deployment events log. To check that, use the describe subcommand:
You can also view in the output of this command that there are 4 replicas now.
https://kubernetes.io/docs/tutorials/_print/ 24/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Load Balancing
Let's check that the Service is load-balancing the traffic. To find out the exposed IP and
Port we can use the describe service as we learned in the previous part of the tutorial:
Create an environment variable called NODE_PORT that has a value as the Node port:
echo NODE_PORT=$NODE_PORT
Next, we’ll do a curl to the exposed IP address and port. Execute the command multiple
times:
We hit a different Pod with every request. This demonstrates that the load-balancing is
working.
Scale Down
To scale down the Deployment to 2 replicas, run again the scale subcommand:
List the Deployments to check if the change was applied with the get deployments
subcommand:
The number of replicas decreased to 2. List the number of Pods, with get pods :
https://kubernetes.io/docs/tutorials/_print/ 25/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Perform a rolling update using kubectl.
Updating an application
Users expect applications to be available all the time and
Summary:
developers are expected to deploy new versions of them Updating an
several times a day. In Kubernetes this is done with rolling app
updates. Rolling updates allow Deployments' update to
take place with zero downtime by incrementally updating
Pods instances with new ones. The new Pods will be
scheduled on Nodes with available resources. Rolling updates allow
Deployments' update
In the previous module we scaled our application to run to take place with zero
multiple instances. This is a requirement for performing downtime by
updates without affecting application availability. By incrementally updating
default, the maximum number of Pods that can be Pods instances with
unavailable during the update and the maximum number new ones.
of new Pods that can be created, is one. Both options can
be configured to either numbers or percentages (of Pods).
In Kubernetes, updates are versioned and any
Deployment update can be reverted to a previous (stable)
version.
To view the current image version of the app, run the describe pods subcommand and
look for the Image field:
To update the image of the application to version 2, use the set image subcommand,
followed by the deployment name and the new image version:
The command notified the Deployment to use a different image for your app and initiated
a rolling update. Check the status of the new Pods, and view the old one terminating with
the get pods subcommand:
Create an environment variable called NODE_PORT that has the value of the Node port
assigned:
Every time you run the curl command, you will hit a different Pod. Notice that all Pods
are now running the latest version (v2).
You can also confirm the update by running the rollout status subcommand:
To view the current image version of the app, run the describe pods subcommand:
In the Image field of the output, verify that you are running the latest image version (v2).
https://kubernetes.io/docs/tutorials/_print/ 27/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Notice that the output doesn't list the desired number of available Pods. Run the get
pods subcommand to list all Pods:
To get more insight into the problem, run the describe pods subcommand:
In the Events section of the output for the affected Pods, notice that the v10 image
version did not exist in the repository.
To roll back the deployment to your last working version, use the rollout undo
subcommand:
The rollout undo command reverts the deployment to the previous known state (v2 of
the image). Updates are versioned and you can revert to any previously known state of a
Deployment.
Four Pods are running. To check the image deployed on these Pods, use the describe
pods subcommand:
The Deployment is once again using a stable version of the app (v2). The rollback was
successful.
https://kubernetes.io/docs/tutorials/_print/ 28/155
6/6/23, 4:10 PM Tutorials | Kubernetes
3 - Configuration
3.1 - Example: Configuring a Java
Microservice
3.1.1 - Externalizing config using
MicroProfile, ConfigMaps and Secrets
In this tutorial you will learn how and why to externalize your microservice’s configuration.
Specifically, you will learn how to use Kubernetes ConfigMaps and Secrets to set environment
variables and then consume them using MicroProfile Config.
ConfigMaps are API Objects that store non-confidential key-value pairs. In the Interactive
Tutorial you will learn how to use a ConfigMap to store the application's name. For more
information regarding ConfigMaps, you can find the documentation here.
Although Secrets are also used to store key-value pairs, they differ from ConfigMaps in that
they're intended for confidential/sensitive information and are stored using Base64 encoding.
This makes secrets the appropriate choice for storing such things as credentials, keys, and
tokens, the former of which you'll do in the Interactive Tutorial. For more information on
Secrets, you can find the documentation here.
Many open source frameworks and runtimes implement and support MicroProfile Config.
Throughout the interactive tutorial, you'll be using Open Liberty, a flexible open-source Java
runtime for building and running cloud-native apps and microservices. However, any
MicroProfile compatible runtime could be used instead.
https://kubernetes.io/docs/tutorials/_print/ 29/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Create a Kubernetes ConfigMap and Secret
Inject microservice configuration using MicroProfile Config
https://kubernetes.io/docs/tutorials/_print/ 30/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Create a ConfigMap with Redis configuration values
Create a Redis Pod that mounts and uses the created ConfigMap
Verify that the configuration was correctly applied.
Killercoda
Play with Kubernetes
The example shown on this page works with kubectl 1.14 and above.
Understand Configure a Pod to Use a ConfigMap.
Apply the ConfigMap created above, along with a Redis pod manifest:
Examine the contents of the Redis pod manifest and note the following:
This has the net effect of exposing the data in data.redis-config from the example-redis-
config ConfigMap above as /redis-master/redis.conf inside the Pod.
pods/config/redis-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: redis
spec:
containers:
- name: redis
image: redis:5.0.4
command:
- redis-server
- "/redis-master/redis.conf"
env:
- name: MASTER
value: "true"
ports:
- containerPort: 6379
resources:
limits:
cpu: "0.1"
volumeMounts:
- mountPath: /redis-master-data
name: data
- mountPath: /redis-master
name: config
volumes:
- name: data
emptyDir: {}
- name: config
configMap:
name: example-redis-config
items:
- key: redis-config
path: redis.conf
https://kubernetes.io/docs/tutorials/_print/ 32/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Name: example-redis-config
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
redis-config:
Use kubectl exec to enter the pod and run the redis-cli tool to check the current
configuration:
Check maxmemory :
1) "maxmemory"
2) "0"
1) "maxmemory-policy"
2) "noeviction"
pods/config/example-redis-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: example-redis-config
data:
redis-config: |
maxmemory 2mb
maxmemory-policy allkeys-lru
Name: example-redis-config
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
redis-config:
----
maxmemory 2mb
maxmemory-policy allkeys-lru
Check the Redis Pod again using redis-cli via kubectl exec to see if the configuration was
applied:
Check maxmemory :
1) "maxmemory"
2) "0"
Returns:
1) "maxmemory-policy"
2) "noeviction"
The configuration values have not changed because the Pod needs to be restarted to grab
updated values from associated ConfigMaps. Let's delete and recreate the Pod:
https://kubernetes.io/docs/tutorials/_print/ 34/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Check maxmemory :
1) "maxmemory"
2) "2097152"
1) "maxmemory-policy"
2) "allkeys-lru"
What's next
Learn more about ConfigMaps.
https://kubernetes.io/docs/tutorials/_print/ 35/155
6/6/23, 4:10 PM Tutorials | Kubernetes
4 - Security
4.1 - Apply Pod Security Standards at
the Cluster Level
Note
This tutorial applies only for new clusters.
Pod Security admission (PSA) is enabled by default in v1.23 and later, as it has graduated to
beta. Pod Security is an admission controller that carries out checks against the Kubernetes
Pod Security Standards when new pods are created. This tutorial shows you how to enforce
the baseline Pod Security Standard at the cluster level which applies a standard
configuration to all namespaces in a cluster.
To apply Pod Security Standards to specific namespaces, refer to Apply Pod Security
Standards at the namespace level.
If you are running a version of Kubernetes other than v1.27, check the documentation for that
version.
KinD
kubectl
This tutorial demonstrates what you can configure for a Kubernetes cluster that you fully
control. If you are learning how to configure Pod Security Admission for a managed cluster
where you are not able to configure the control plane, read Apply Pod Security Standards at
the namespace level.
To gather information that helps you to choose the Pod Security Standards that are most
appropriate for your configuration, do the following:
https://kubernetes.io/docs/tutorials/_print/ 36/155
6/6/23, 4:10 PM Tutorials | Kubernetes
To further debug and diagnose cluster problems, use 'kubectl cluster-info dum
kubectl get ns
1. Privileged
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
namespace/kube-system labeled
namespace/local-path-storage labeled
2. Baseline
https://kubernetes.io/docs/tutorials/_print/ 37/155
6/6/23, 4:10 PM Tutorials | Kubernetes
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
Warning: existing pods in namespace "kube-system" violate the new PodSec
Warning: etcd-psa-wo-cluster-pss-control-plane (and 3 other pods): host
Warning: kindnet-vzj42: non-default capabilities, host namespaces, hostP
Warning: kube-proxy-m6hwf: host namespaces, hostPath volumes, privileged
namespace/kube-system labeled
namespace/local-path-storage labeled
3. Restricted
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
Warning: existing pods in namespace "kube-system" violate the new PodSec
Warning: coredns-7bb9c7b568-hsptc (and 1 other pod): unrestricted capabi
Warning: etcd-psa-wo-cluster-pss-control-plane (and 3 other pods): host
Warning: kindnet-vzj42: non-default capabilities, host namespaces, hostP
Warning: kube-proxy-m6hwf: host namespaces, hostPath volumes, privileged
namespace/kube-system labeled
Warning: existing pods in namespace "local-path-storage" violate the new
Warning: local-path-provisioner-d6d9f7ffc-lw9lh: allowPrivilegeEscalatio
namespace/local-path-storage labeled
From the previous output, you'll notice that applying the privileged Pod Security Standard
shows no warnings for any namespaces. However, baseline and restricted standards
both have warnings, specifically in the kube-system namespace.
The baseline Pod Security Standard provides a convenient middle ground that allows
keeping the exemption list short and prevents known privilege escalations.
Additionally, to prevent pods from failing in kube-system , you'll exempt the namespace from
having Pod Security Standards applied.
When you implement Pod Security Admission in your own environment, consider the
following:
1. Based on the risk posture applied to a cluster, a stricter Pod Security Standard like
restricted might be a better choice.
https://kubernetes.io/docs/tutorials/_print/ 38/155
6/6/23, 4:10 PM Tutorials | Kubernetes
mkdir -p /tmp/pss
cat <<EOF > /tmp/pss/cluster-level-pss.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
configuration:
apiVersion: pod-security.admission.config.k8s.io/v1
kind: PodSecurityConfiguration
defaults:
enforce: "baseline"
enforce-version: "latest"
audit: "restricted"
audit-version: "latest"
warn: "restricted"
warn-version: "latest"
exemptions:
usernames: []
runtimeClasses: []
namespaces: [kube-system]
EOF
4. Configure the API server to consume this file during cluster creation:
Note: If you use Docker Desktop with KinD on macOS, you can add /tmp as a Shared
https://kubernetes.io/docs/tutorials/_print/ 39/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Directory under the menu item Preferences > Resources > File Sharing.
5. Create a cluster that uses Pod Security Admission to apply these Pod Security Standards:
To further debug and diagnose cluster problems, use 'kubectl cluster-info dum
Clean up
Now delete the clusters which you created above by running the following command:
https://kubernetes.io/docs/tutorials/_print/ 40/155
6/6/23, 4:10 PM Tutorials | Kubernetes
What's next
Run a shell script to perform all the preceding steps at once:
1. Create a Pod Security Standards based cluster level Configuration
2. Create a file to let API server consume this configuration
3. Create a cluster that creates an API server with this configuration
4. Set kubectl context to this new cluster
5. Create a minimal pod yaml file
6. Apply this file to create a Pod in the new cluster
Pod Security Admission
Pod Security Standards
Apply Pod Security Standards at the namespace level
https://kubernetes.io/docs/tutorials/_print/ 41/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Pod Security admission (PSA) is enabled by default in v1.23 and later, as it graduated to beta.
Pod Security Admission is an admission controller that applies Pod Security Standards when
pods are created. In this tutorial, you will enforce the baseline Pod Security Standard, one
namespace at a time.
You can also apply Pod Security Standards to multiple namespaces at once at the cluster level.
For instructions, refer to Apply Pod Security Standards at the cluster level.
KinD
kubectl
Create cluster
1. Create a KinD cluster as follows:
To further debug and diagnose cluster problems, use 'kubectl cluster-info dum
https://kubernetes.io/docs/tutorials/_print/ 42/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Create a namespace
Create a new namespace called example :
namespace/example created
2. You can configure multiple pod security standard checks on any namespace, using
labels. The following command will enforce the baseline Pod Security Standard, but
warn and audit for restricted Pod Security Standards as per the latest version
(default value)
The Pod does start OK; the output includes a warning. For example:
https://kubernetes.io/docs/tutorials/_print/ 43/155
6/6/23, 4:10 PM Tutorials | Kubernetes
pod/nginx created
The Pod Security Standards enforcement and warning settings were applied only to the
example namespace. You could create the same Pod in the default namespace with no
warnings.
Clean up
Now delete the cluster which you created above by running the following command:
What's next
Run a shell script to perform all the preceding steps all at once.
4. Create a new pod with the following pod security standards applied
Pod Security Admission
https://kubernetes.io/docs/tutorials/_print/ 44/155
6/6/23, 4:10 PM Tutorials | Kubernetes
AppArmor is a Linux kernel security module that supplements the standard Linux user and
group based permissions to confine programs to a limited set of resources. AppArmor can be
configured for any application to reduce its potential attack surface and provide greater in-
depth defense. It is configured through profiles tuned to allow the access needed by a specific
program or container, such as Linux capabilities, network access, file permissions, etc. Each
profile can be run in either enforcing mode, which blocks access to disallowed resources, or
complain mode, which only reports violations.
AppArmor can help you to run a more secure deployment by restricting what containers are
allowed to do, and/or provide better auditing through system logs. However, it is important to
keep in mind that AppArmor is not a silver bullet and can only do so much to protect against
exploits in your application code. It is important to provide good, restrictive profiles, and
harden your applications and cluster from other angles as well.
Objectives
See an example of how to load a profile on a node
Learn how to enforce the profile on a Pod
Learn how to check that the profile is loaded
See what happens when a profile is violated
See what happens when a profile cannot be loaded
1. Kubernetes version is at least v1.4 -- Kubernetes support for AppArmor was added in
v1.4. Kubernetes components older than v1.4 are not aware of the new AppArmor
annotations, and will silently ignore any AppArmor settings that are provided. To
ensure that your Pods are receiving the expected protections, it is important to verify
the Kubelet version of your nodes:
gke-test-default-pool-239f5d02-gyn2: v1.4.0
gke-test-default-pool-239f5d02-x1kf: v1.4.0
gke-test-default-pool-239f5d02-xwux: v1.4.0
2. AppArmor kernel module is enabled -- For the Linux kernel to enforce an AppArmor
profile, the AppArmor kernel module must be installed and enabled. Several
distributions enable the module by default, such as Ubuntu and SUSE, and many others
provide optional support. To check whether the module is enabled, check the
/sys/module/apparmor/parameters/enabled file:
cat /sys/module/apparmor/parameters/enabled
Y
If the Kubelet contains AppArmor support (>= v1.4), it will refuse to run a Pod with
AppArmor options if the kernel module is not enabled.
https://kubernetes.io/docs/tutorials/_print/ 45/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Note: Ubuntu carries many AppArmor patches that have not been merged into the
upstream Linux kernel, including patches that add additional hooks and features.
Kubernetes has only been tested with the upstream version, and does not promise
support for other features.
apparmor-test-deny-write (enforce)
apparmor-test-audit-write (enforce)
docker-default (enforce)
k8s-nginx (enforce)
For more details on loading profiles on nodes, see Setting up nodes with profiles.
As long as the Kubelet version includes AppArmor support (>= v1.4), the Kubelet will reject a
Pod with AppArmor options if any of the prerequisites are not met. You can also verify
AppArmor support on nodes by checking the node ready condition message (though this is
likely to be removed in a later release):
Securing a Pod
Note: AppArmor is currently in beta, so options are specified as annotations. Once
support graduates to general availability, the annotations will be replaced with first-class
fields.
AppArmor profiles are specified per-container. To specify the AppArmor profile to run a Pod
container with, add an annotation to the Pod's metadata:
container.apparmor.security.beta.kubernetes.io/<container_name>: <profile_ref>
Where <container_name> is the name of the container to apply the profile to, and
<profile_ref> specifies the profile to apply. The profile_ref can be one of:
https://kubernetes.io/docs/tutorials/_print/ 46/155
6/6/23, 4:10 PM Tutorials | Kubernetes
localhost/<profile_name> to apply the profile loaded on the host with the name
<profile_name>
See the API Reference for the full details on the annotation and profile name formats.
Kubernetes AppArmor enforcement works by first checking that all the prerequisites have
been met, and then forwarding the profile selection to the container runtime for
enforcement. If the prerequisites have not been met, the Pod will be rejected, and will not
run.
To verify that the profile was applied, you can look for the AppArmor security option listed in
the container created event:
You can also verify directly that the container's root process is running with the correct profile
by checking its proc attr:
k8s-apparmor-example-deny-write (enforce)
Example
This example assumes you have already set up a cluster with AppArmor support.
First, we need to load the profile we want to use onto our nodes. This profile denies all file
writes:
#include <tunables/global>
file,
Since we don't know where the Pod will be scheduled, we'll need to load the profile on all our
nodes. For this example we'll use SSH to install the profiles, but other approaches are
discussed in Setting up nodes with profiles.
https://kubernetes.io/docs/tutorials/_print/ 47/155
6/6/23, 4:10 PM Tutorials | Kubernetes
NODES=(
# The SSH-accessible domain names of your nodes
gke-test-default-pool-239f5d02-gyn2.us-central1-a.my-k8s
gke-test-default-pool-239f5d02-x1kf.us-central1-a.my-k8s
gke-test-default-pool-239f5d02-xwux.us-central1-a.my-k8s)
for NODE in ${NODES[*]}; do ssh $NODE 'sudo apparmor_parser -q <<EOF
#include <tunables/global>
file,
Next, we'll run a simple "Hello AppArmor" pod with the deny-write profile:
pods/security/hello-apparmor.yaml
apiVersion: v1
kind: Pod
metadata:
name: hello-apparmor
annotations:
# Tell Kubernetes to apply the AppArmor profile "k8s-apparmor-example-deny-wr
# Note that this is ignored if the Kubernetes node is not running version 1.4
container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-
spec:
containers:
- name: hello
image: busybox:1.28
command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
If we look at the pod events, we can see that the Pod container was created with the
AppArmor profile "k8s-apparmor-example-deny-write":
We can verify that the container is actually running with that profile by checking its proc attr:
https://kubernetes.io/docs/tutorials/_print/ 48/155
6/6/23, 4:10 PM Tutorials | Kubernetes
k8s-apparmor-example-deny-write (enforce)
Finally, we can see what happens if we try to violate the profile by writing to a file:
To wrap up, let's look at what happens if we try to specify a profile that hasn't been loaded:
apiVersion: v1
kind: Pod
metadata:
name: hello-apparmor-2
annotations:
container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-
spec:
containers:
- name: hello
image: busybox:1.28
command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
EOF
pod/hello-apparmor-2 created
https://kubernetes.io/docs/tutorials/_print/ 49/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Name: hello-apparmor-2
Namespace: default
Node: gke-test-default-pool-239f5d02-x1kf/
Start Time: Tue, 30 Aug 2016 17:58:56 -0700
Labels: <none>
Annotations: container.apparmor.security.beta.kubernetes.io/hello=localhost/k8s
Status: Pending
Reason: AppArmor
Message: Pod Cannot enforce AppArmor: profile "k8s-apparmor-example-allow-w
IP:
Controllers: <none>
Containers:
hello:
Container ID:
Image: busybox
Image ID:
Port:
Command:
sh
-c
echo 'Hello AppArmor!' && sleep 1h
State: Waiting
Reason: Blocked
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-dnz7v (ro)
Conditions:
Type Status
Initialized True
Ready False
PodScheduled True
Volumes:
default-token-dnz7v:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-dnz7v
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: <none>
Events:
FirstSeen LastSeen Count From SubobjectPath
--------- -------- ----- ---- -------------
23s 23s 1 {default-scheduler } N
23s 23s 1 {kubelet e2e-test-stclair-node-pool-t1f5}
Note the pod status is Pending, with a helpful error message: Pod Cannot enforce AppArmor:
profile "k8s-apparmor-example-allow-write" is not loaded . An event was also recorded
with the same message.
Administration
Setting up nodes with profiles
Kubernetes does not currently provide any native mechanisms for loading AppArmor profiles
onto nodes. There are lots of ways to set up the profiles though, such as:
Through a DaemonSet that runs a Pod on each node to ensure the correct profiles are
loaded. An example implementation can be found here.
At node initialization time, using your node initialization scripts (e.g. Salt, Ansible, etc.) or
image.
By copying the profiles to each node and loading them through SSH, as demonstrated in
the Example.
https://kubernetes.io/docs/tutorials/_print/ 50/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The scheduler is not aware of which profiles are loaded onto which node, so the full set of
profiles must be loaded onto every node. An alternative approach is to add a node label for
each profile (or class of profiles) on the node, and use a node selector to ensure the Pod is
run on a node with the required profile.
Disabling AppArmor
If you do not want AppArmor to be available on your cluster, it can be disabled by a
command-line flag:
--feature-gates=AppArmor=false
When disabled, any Pod that includes an AppArmor profile will fail validation with a
"Forbidden" error.
Note: Even if the Kubernetes feature is disabled, runtimes may still enforce the default
profile. The option to disable the AppArmor feature will be removed when AppArmor
graduates to general availability (GA).
Authoring Profiles
Getting AppArmor profiles specified correctly can be a tricky business. Fortunately there are
some tools to help with that:
To debug problems with AppArmor, you can check the system logs to see what, specifically,
was denied. AppArmor logs verbose messages to dmesg , and errors can usually be found in
the system logs or through journalctl . More information is provided in AppArmor failures.
API Reference
Pod Annotation
Specifying the profile a container will run with:
key: Where
container.apparmor.security.beta.kubernetes.io/<container_name>
<container_name> matches the name of a container in the Pod. A separate profile can
be specified for each container in the Pod.
value: a profile reference, described below
Profile Reference
runtime/default : Refers to the default runtime profile.
Equivalent to not specifying a profile, except it still requires AppArmor to be
enabled.
In practice, many container runtimes use the same OCI default profile, defined
here:
https://github.com/containers/common/blob/main/pkg/apparmor/apparmor_linux_template.go
localhost/<profile_name> : Refers to a profile loaded on the node (localhost) by name.
The possible profile names are detailed in the core policy reference.
unconfined : This effectively disables AppArmor on the container.
https://kubernetes.io/docs/tutorials/_print/ 51/155
6/6/23, 4:10 PM Tutorials | Kubernetes
What's next
Additional resources:
https://kubernetes.io/docs/tutorials/_print/ 52/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Seccomp stands for secure computing mode and has been a feature of the Linux kernel since
version 2.6.12. It can be used to sandbox the privileges of a process, restricting the calls it is
able to make from userspace into the kernel. Kubernetes lets you automatically apply
seccomp profiles loaded onto a node to your Pods and containers.
Identifying the privileges required for your workloads can be difficult. In this tutorial, you will
go through how to load seccomp profiles into a local Kubernetes cluster, how to apply them
to a Pod, and how you can begin to craft profiles that give only the necessary privileges to
your container processes.
Objectives
Learn how to load seccomp profiles on a node
Learn how to apply a seccomp profile to a container
Observe auditing of syscalls made by a container process
Observe behavior when a missing profile is specified
Observe a violation of a seccomp profile
Learn how to create fine-grained seccomp profiles
Learn how to apply a container runtime default seccomp profile
This tutorial shows some examples that are still beta (since v1.25) and others that use only
generally available seccomp functionality. You should make sure that your cluster is
configured correctly for the version you are using.
The tutorial also uses the curl tool for downloading examples to your computer. You can
adapt the steps to use a different tool if you prefer.
pods/security/seccomp/profiles/audit.json
{
"defaultAction": "SCMP_ACT_LOG"
}
https://kubernetes.io/docs/tutorials/_print/ 53/155
6/6/23, 4:10 PM Tutorials | Kubernetes
mkdir ./profiles
curl -L -o profiles/audit.json https://k8s.io/examples/pods/security/seccomp/prof
curl -L -o profiles/violation.json https://k8s.io/examples/pods/security/seccomp/
curl -L -o profiles/fine-grained.json https://k8s.io/examples/pods/security/secco
ls profiles
You should see three profiles listed at the end of the final step:
pods/security/seccomp/kind.yaml
apiVersion: kind.x-k8s.io/v1alpha4
kind: Cluster
nodes:
- role: control-plane
extraMounts:
- hostPath: "./profiles"
containerPath: "/var/lib/kubelet/seccomp/profiles"
Download that example kind configuration, and save it to a file named kind.yaml :
curl -L -O https://k8s.io/examples/pods/security/seccomp/kind.yaml
You can set a specific Kubernetes version by setting the node's container image. See Nodes
within the kind documentation about configuration for more details on this. This tutorial
assumes you are using Kubernetes v1.27.
As a beta feature, you can configure Kubernetes to use the profile that the container runtime
prefers by default, rather than falling back to Unconfined . If you want to try that, see enable
the use of RuntimeDefault as the default seccomp profile for all workloads before you
continue.
Once you have a kind configuration in place, create the kind cluster with that configuration:
After the new Kubernetes cluster is ready, identify the Docker container running as the single
node cluster:
docker ps
You should see output indicating that a container is running with name kind-control-plane .
The output is similar to:
https://kubernetes.io/docs/tutorials/_print/ 54/155
6/6/23, 4:10 PM Tutorials | Kubernetes
If observing the filesystem of that container, you should see that the profiles/ directory has
been successfully loaded into the default seccomp path of the kubelet. Use docker exec to
run a command in the Pod:
You have verified that these seccomp profiles are available to the kubelet running within kind.
To use seccomp profile defaulting, you must run the kubelet with the --seccomp-default
command line flag enabled for each node where you want to use it.
If enabled, the kubelet will use the RuntimeDefault seccomp profile by default, which is
defined by the container runtime, instead of using the Unconfined (seccomp disabled) mode.
The default profiles aim to provide a strong set of security defaults while preserving the
functionality of the workload. It is possible that the default profiles differ between container
runtimes and their release versions, for example when comparing those from CRI-O and
containerd.
Some workloads may require a lower amount of syscall restrictions than others. This means
that they can fail during runtime even with the RuntimeDefault profile. To mitigate such a
failure, you can:
If you were introducing this feature into production-like cluster, the Kubernetes project
recommends that you enable this feature gate on a subset of your nodes and then test
workload execution before rolling the change out cluster-wide.
You can find more detailed information about a possible upgrade and downgrade strategy in
the related Kubernetes Enhancement Proposal (KEP): Enable seccomp by default.
Kubernetes 1.27 lets you configure the seccomp profile that applies when the spec for a Pod
doesn't define a specific seccomp profile. However, you still need to enable this defaulting for
each node where you would like to use it.
If you are running a Kubernetes 1.27 cluster and want to enable the feature, either run the
kubelet with the --seccomp-default command line flag, or enable it through the kubelet
configuration file. To enable the feature gate in kind, ensure that kind provides the
https://kubernetes.io/docs/tutorials/_print/ 55/155
6/6/23, 4:10 PM Tutorials | Kubernetes
minimum required Kubernetes version and enables the SeccompDefault feature in the kind
configuration:
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
image: kindest/node:v1.23.0@sha256:49824ab1727c04e56a21a5d8372a402fcd32ea51ac
kubeadmConfigPatches:
- |
kind: JoinConfiguration
nodeRegistration:
kubeletExtraArgs:
seccomp-default: "true"
- role: worker
image: kindest/node:v1.23.0@sha256:49824ab1727c04e56a21a5d8372a402fcd32ea51ac
kubeadmConfigPatches:
- |
kind: JoinConfiguration
nodeRegistration:
kubeletExtraArgs:
seccomp-default: "true"
Should now have the default seccomp profile attached. This can be verified by using docker
exec to run crictl inspect for the container on the kind worker:
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_X86", "SCMP_ARCH_X32"],
"syscalls": [
{
"names": ["..."]
}
]
}
Note: If you have the seccompDefault configuration enabled, then Pods use the
RuntimeDefault seccomp profile whenever no other seccomp profile is specified.
Otherwise, the default is Unconfined.
https://kubernetes.io/docs/tutorials/_print/ 56/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Here's a manifest for a Pod that requests the RuntimeDefault seccomp profile for all its
containers:
pods/security/seccomp/ga/default-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: default-pod
labels:
app: default-pod
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: test-container
image: hashicorp/http-echo:0.2.3
args:
- "-text=just made some more syscalls!"
securityContext:
allowPrivilegeEscalation: false
Finally, now that you saw that work OK, clean up:
pods/security/seccomp/ga/audit-pod.yaml
https://kubernetes.io/docs/tutorials/_print/ 57/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Pod
metadata:
name: audit-pod
labels:
app: audit-pod
spec:
securityContext:
seccompProfile:
type: Localhost
localhostProfile: profiles/audit.json
containers:
- name: test-container
image: hashicorp/http-echo:0.2.3
args:
- "-text=just made some syscalls!"
securityContext:
allowPrivilegeEscalation: false
Note: Older versions of Kubernetes allowed you to configure seccomp behavior using
annotations. Kubernetes 1.27 only supports using fields within .spec.securityContext to
configure seccomp, and this tutorial explains that approach.
This profile does not restrict any syscalls, so the Pod should start successfully.
In order to be able to interact with this endpoint exposed by this container, create a NodePort
Services that allows access to the endpoint from inside the kind control plane container.
Check what port the Service has been assigned on the node.
https://kubernetes.io/docs/tutorials/_print/ 58/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Now you can use curl to access that endpoint from inside the kind control plane container,
at the port exposed by this Service. Use docker exec to run the curl command within the
container belonging to that control plane container:
# Change 6a96207fed4b to the control plane container ID you saw from "docker ps"
docker exec -it 6a96207fed4b curl localhost:32373
You can see that the process is running, but what syscalls did it actually make? Because this
Pod is running in a local cluster, you should be able to see those in /var/log/syslog . Open
up a new terminal window and tail the output for calls from http-echo :
You should already see some logs of syscalls made by http-echo , and if you curl the
endpoint in the control plane container you will see more written.
For example:
You can begin to understand the syscalls required by the http-echo process by looking at
the syscall= entry on each line. While these are unlikely to encompass all syscalls it uses, it
can serve as a basis for a seccomp profile for this container.
Clean up that Pod and Service before moving to the next section:
pods/security/seccomp/ga/violation-pod.yaml
https://kubernetes.io/docs/tutorials/_print/ 59/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Pod
metadata:
name: violation-pod
labels:
app: violation-pod
spec:
securityContext:
seccompProfile:
type: Localhost
localhostProfile: profiles/violation.json
containers:
- name: test-container
image: hashicorp/http-echo:0.2.3
args:
- "-text=just made some syscalls!"
securityContext:
allowPrivilegeEscalation: false
The Pod creates, but there is an issue. If you check the status of the Pod, you should see that
it failed to start.
As seen in the previous example, the http-echo process requires quite a few syscalls. Here
seccomp has been instructed to error on any syscall by setting "defaultAction":
"SCMP_ACT_ERRNO" . This is extremely secure, but removes the ability to do anything
meaningful. What you really want is to give workloads only the privileges they need.
pods/security/seccomp/ga/fine-pod.yaml
https://kubernetes.io/docs/tutorials/_print/ 60/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Pod
metadata:
name: fine-pod
labels:
app: fine-pod
spec:
securityContext:
seccompProfile:
type: Localhost
localhostProfile: profiles/fine-grained.json
containers:
- name: test-container
image: hashicorp/http-echo:0.2.3
args:
- "-text=just made some syscalls!"
securityContext:
allowPrivilegeEscalation: false
Open up a new terminal window and use tail to monitor for log entries that mention calls
from http-echo :
Check what port the Service has been assigned on the node:
https://kubernetes.io/docs/tutorials/_print/ 61/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Use curl to access that endpoint from inside the kind control plane container:
# Change 6a96207fed4b to the control plane container ID you saw from "docker ps"
docker exec -it 6a96207fed4b curl localhost:32373
You should see no output in the syslog . This is because the profile allowed all necessary
syscalls and specified that an error should occur if one outside of the list is invoked. This is an
ideal situation from a security perspective, but required some effort in analyzing the program.
It would be nice if there was a simple way to get closer to this security without requiring as
much effort.
Clean up that Pod and Service before moving to the next section:
What's next
You can learn more about Linux seccomp:
A seccomp Overview
Seccomp Security Profiles for Docker
https://kubernetes.io/docs/tutorials/_print/ 62/155
6/6/23, 4:10 PM Tutorials | Kubernetes
5 - Stateless Applications
5.1 - Exposing an External IP Address to
Access an Application in a Cluster
This page shows how to create a Kubernetes Service object that exposes an external IP
address.
Objectives
Run five instances of a Hello World application.
Create a Service object that exposes an external IP address.
Use the Service object to access the running application.
service/load-balancer-example.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: load-balancer-example
name: hello-world
spec:
replicas: 5
selector:
matchLabels:
app.kubernetes.io/name: load-balancer-example
template:
metadata:
labels:
app.kubernetes.io/name: load-balancer-example
spec:
containers:
- image: gcr.io/google-samples/node-hello:1.0
name: hello-world
ports:
- containerPort: 8080
https://kubernetes.io/docs/tutorials/_print/ 63/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Note: If the external IP address is shown as <pending>, wait for a minute and enter
the same command again.
https://kubernetes.io/docs/tutorials/_print/ 64/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Name: my-service
Namespace: default
Labels: app.kubernetes.io/name=load-balancer-example
Annotations: <none>
Selector: app.kubernetes.io/name=load-balancer-example
Type: LoadBalancer
IP: 10.3.245.137
LoadBalancer Ingress: 104.198.205.71
Port: <unset> 8080/TCP
NodePort: <unset> 32377/TCP
Endpoints: 10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more...
Session Affinity: None
Events: <none>
7. In the preceding output, you can see that the service has several endpoints:
10.0.0.6:8080,10.0.1.6:8080,10.0.1.7:8080 + 2 more. These are internal addresses of the
pods that are running the Hello World application. To verify these are pod addresses,
enter this command:
8. Use the external IP address ( LoadBalancer Ingress ) to access the Hello World
application:
curl http://<external-ip>:<port>
Hello Kubernetes!
Cleaning up
To delete the Service, enter this command:
https://kubernetes.io/docs/tutorials/_print/ 65/155
6/6/23, 4:10 PM Tutorials | Kubernetes
To delete the Deployment, the ReplicaSet, and the Pods that are running the Hello World
application, enter this command:
What's next
Learn more about connecting applications with services.
https://kubernetes.io/docs/tutorials/_print/ 66/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Objectives
Start up a Redis leader.
Start up two Redis followers.
Start up the guestbook frontend.
Expose and view the Frontend Service.
Clean up.
Killercoda
Play with Kubernetes
Your Kubernetes server must be at or later than version v1.14. To check the version, enter
kubectl version.
application/guestbook/redis-leader-deployment.yaml
https://kubernetes.io/docs/tutorials/_print/ 67/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-leader
labels:
app: redis
role: leader
tier: backend
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
role: leader
tier: backend
spec:
containers:
- name: leader
image: "docker.io/redis:6.0.5"
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 6379
1. Launch a terminal window in the directory you downloaded the manifest files.
3. Query the list of Pods to verify that the Redis Pod is running:
4. Run the following command to view the logs from the Redis leader Pod:
application/guestbook/redis-leader-service.yaml
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: redis-leader
labels:
app: redis
role: leader
tier: backend
spec:
ports:
- port: 6379
targetPort: 6379
selector:
app: redis
role: leader
tier: backend
2. Query the list of Services to verify that the Redis Service is running:
Note: This manifest file creates a Service named redis-leader with a set of labels that
match the labels previously defined, so the Service routes network traffic to the Redis
Pod.
application/guestbook/redis-follower-deployment.yaml
https://kubernetes.io/docs/tutorials/_print/ 69/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-follower
labels:
app: redis
role: follower
tier: backend
spec:
replicas: 2
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
role: follower
tier: backend
spec:
containers:
- name: follower
image: gcr.io/google_samples/gb-redis-follower:v2
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 6379
2. Verify that the two Redis follower replicas are running by querying the list of Pods:
application/guestbook/redis-follower-service.yaml
https://kubernetes.io/docs/tutorials/_print/ 70/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: redis-follower
labels:
app: redis
role: follower
tier: backend
spec:
ports:
# the port that this service should serve on
- port: 6379
selector:
app: redis
role: follower
tier: backend
2. Query the list of Services to verify that the Redis Service is running:
Note: This manifest file creates a Service named redis-follower with a set of labels that
match the labels previously defined, so the Service routes network traffic to the Redis
Pod.
The guestbook app uses a PHP frontend. It is configured to communicate with either the
Redis follower or leader Services, depending on whether the request is a read or a write. The
frontend exposes a JSON interface, and serves a jQuery-Ajax-based UX.
https://kubernetes.io/docs/tutorials/_print/ 71/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
selector:
matchLabels:
app: guestbook
tier: frontend
template:
metadata:
labels:
app: guestbook
tier: frontend
spec:
containers:
- name: php-redis
image: gcr.io/google_samples/gb-frontend:v5
env:
- name: GET_HOSTS_FROM
value: "dns"
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 80
2. Query the list of Pods to verify that the three frontend replicas are running:
If you want guests to be able to access your guestbook, you must configure the frontend
Service to be externally visible, so a client can request the Service from outside the
Kubernetes cluster. However a Kubernetes user can use kubectl port-forward to access the
service even though it uses a ClusterIP .
https://kubernetes.io/docs/tutorials/_print/ 72/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Note: Some cloud providers, like Google Compute Engine or Google Kubernetes Engine,
support external load balancers. If your cloud provider supports load balancers and you
want to use it, uncomment type: LoadBalancer.
application/guestbook/frontend-service.yaml
# SOURCE: https://cloud.google.com/kubernetes-engine/docs/tutorials/guestbook
apiVersion: v1
kind: Service
metadata:
name: frontend
labels:
app: guestbook
tier: frontend
spec:
# if your cluster supports it, uncomment the following to automatically create
# an external load-balanced IP for the frontend service.
# type: LoadBalancer
#type: LoadBalancer
ports:
# the port that this service should serve on
- port: 80
selector:
app: guestbook
tier: frontend
2. Query the list of Services to verify that the frontend Service is running:
https://kubernetes.io/docs/tutorials/_print/ 73/155
6/6/23, 4:10 PM Tutorials | Kubernetes
1. Run the following command to get the IP address for the frontend Service.
2. Copy the external IP address, and load the page in your browser to view your guestbook.
Note: Try adding some guestbook entries by typing in a message, and clicking Submit.
The message you typed appears in the frontend. This message indicates that data is
successfully added to Redis through the Services you created earlier.
2. Query the list of Pods to verify the number of frontend Pods running:
3. Run the following command to scale down the number of frontend Pods:
https://kubernetes.io/docs/tutorials/_print/ 74/155
6/6/23, 4:10 PM Tutorials | Kubernetes
4. Query the list of Pods to verify the number of frontend Pods running:
Cleaning up
Deleting the Deployments and Services also deletes any running Pods. Use labels to delete
multiple resources with one command.
1. Run the following commands to delete all Pods, Deployments, and Services.
What's next
Complete the Kubernetes Basics Interactive Tutorials
Use Kubernetes to create a blog using Persistent Volumes for MySQL and Wordpress
Read more about connecting applications with services
Read more about Managing Resources
https://kubernetes.io/docs/tutorials/_print/ 75/155
6/6/23, 4:10 PM Tutorials | Kubernetes
6 - Stateful Applications
6.1 - StatefulSet Basics
This tutorial provides an introduction to managing applications with StatefulSets. It
demonstrates how to create, delete, scale, and update the Pods of StatefulSets.
Pods
Cluster DNS
Headless Services
PersistentVolumes
PersistentVolume Provisioning
StatefulSets
The kubectl command line tool
Note: This tutorial assumes that your cluster is configured to dynamically provision
PersistentVolumes. If your cluster is not configured to do so, you will have to manually
provision two 1 GiB volumes prior to starting this tutorial.
Objectives
StatefulSets are intended to be used with stateful applications and distributed systems.
However, the administration of stateful applications and distributed systems on Kubernetes is
a broad, complex topic. In order to demonstrate the basic features of a StatefulSet, and not to
conflate the former topic with the latter, you will deploy a simple web application using a
StatefulSet.
Creating a StatefulSet
Begin by creating a StatefulSet using the example below. It is similar to the example
presented in the StatefulSets concept. It creates a headless Service, nginx , to publish the IP
addresses of Pods in the StatefulSet, web .
application/web/web.yaml
https://kubernetes.io/docs/tutorials/_print/ 76/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: "nginx"
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: registry.k8s.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
You will need to use two terminal windows. In the first terminal, use kubectl get to watch
the creation of the StatefulSet's Pods.
In the second terminal, use kubectl apply to create the headless Service and StatefulSet
defined in web.yaml .
https://kubernetes.io/docs/tutorials/_print/ 77/155
6/6/23, 4:10 PM Tutorials | Kubernetes
service/nginx created
statefulset.apps/web created
The command above creates two Pods, each running an NGINX webserver. Get the nginx
Service...
...then get the web StatefulSet, to verify that both were created successfully:
Notice that the web-1 Pod is not launched until the web-0 Pod is Running (see Pod Phase)
and Ready (see type in Pod Conditions).
Note: To configure the integer ordinal assigned to each Pod in a StatefulSet, see Start
ordinal.
Pods in a StatefulSet
Pods in a StatefulSet have a unique ordinal index and a stable network identity.
https://kubernetes.io/docs/tutorials/_print/ 78/155
6/6/23, 4:10 PM Tutorials | Kubernetes
As mentioned in the StatefulSets concept, the Pods in a StatefulSet have a sticky, unique
identity. This identity is based on a unique ordinal index that is assigned to each Pod by the
StatefulSet controller.
The Pods' names take the form <statefulset name>-<ordinal index> . Since the web
StatefulSet has two replicas, it creates two Pods, web-0 and web-1 .
web-0
web-1
Use to execute a container that provides the nslookup command from the
kubectl run
dnsutils package. Using nslookup on the Pods' hostnames, you can examine their in-
cluster DNS addresses:
Server: 10.0.0.10
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: web-0.nginx
Address 1: 10.244.1.6
nslookup web-1.nginx
Server: 10.0.0.10
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: web-1.nginx
Address 1: 10.244.2.6
The CNAME of the headless service points to SRV records (one for each Pod that is Running
and Ready). The SRV records point to A record entries that contain the Pods' IP addresses.
https://kubernetes.io/docs/tutorials/_print/ 79/155
6/6/23, 4:10 PM Tutorials | Kubernetes
In a second terminal, use kubectl delete to delete all the Pods in the StatefulSet:
Wait for the StatefulSet to restart them, and for both Pods to transition to Running and Ready:
Use kubectl exec and kubectl run to view the Pods' hostnames and in-cluster DNS entries.
First, view the Pods' hostnames:
web-0
web-1
then, run:
https://kubernetes.io/docs/tutorials/_print/ 80/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Server: 10.0.0.10
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: web-0.nginx
Address 1: 10.244.1.7
nslookup web-1.nginx
Server: 10.0.0.10
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: web-1.nginx
Address 1: 10.244.2.8
The Pods' ordinals, hostnames, SRV records, and A record names have not changed, but the
IP addresses associated with the Pods may have changed. In the cluster used for this tutorial,
they have. This is why it is important not to configure other applications to connect to Pods in
a StatefulSet by IP address.
If you need to find and connect to the active members of a StatefulSet, you should query the
CNAME of the headless Service ( nginx.default.svc.cluster.local ). The SRV records
associated with the CNAME will contain only the Pods in the StatefulSet that are Running and
Ready.
If your application already implements connection logic that tests for liveness and readiness,
you can use the SRV records of the Pods ( web-0.nginx.default.svc.cluster.local , web-
1.nginx.default.svc.cluster.local ), as they are stable, and your application will be able to
discover the Pods' addresses when they transition to Running and Ready.
The StatefulSet controller created two PersistentVolumeClaims that are bound to two
PersistentVolumes.
Write the Pods' hostnames to their index.html files and verify that the NGINX webservers
serve the hostnames:
https://kubernetes.io/docs/tutorials/_print/ 81/155
6/6/23, 4:10 PM Tutorials | Kubernetes
web-0
web-1
Note:
If you instead see 403 Forbidden responses for the above curl command, you will need to
fix the permissions of the directory mounted by the volumeMounts (due to a bug when
using hostPath volumes), by running:
Examine the output of the kubectl get command in the first terminal, and wait for all of the
Pods to transition to Running and Ready.
web-0
web-1
Even though web-0 and web-1 were rescheduled, they continue to serve their hostnames
because the PersistentVolumes associated with their PersistentVolumeClaims are remounted
to their volumeMounts . No matter what node web-0 and web-1 are scheduled on, their
PersistentVolumes will be mounted to the appropriate mount points.
https://kubernetes.io/docs/tutorials/_print/ 82/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Scaling a StatefulSet
Scaling a StatefulSet refers to increasing or decreasing the number of replicas. This is
accomplished by updating the replicas field. You can use either kubectl scale or kubectl
patch to scale a StatefulSet.
Scaling Up
In one terminal window, watch the Pods in the StatefulSet:
In another terminal window, use kubectl scale to scale the number of replicas to 5:
statefulset.apps/web scaled
Examine the output of the kubectl get command in the first terminal, and wait for the three
additional Pods to transition to Running and Ready.
The StatefulSet controller scaled the number of replicas. As with StatefulSet creation, the
StatefulSet controller created each Pod sequentially with respect to its ordinal index, and it
waited for each Pod's predecessor to be Running and Ready before launching the subsequent
Pod.
Scaling Down
In one terminal, watch the StatefulSet's Pods:
In another terminal, use kubectl patch to scale the StatefulSet back down to three replicas:
https://kubernetes.io/docs/tutorials/_print/ 83/155
6/6/23, 4:10 PM Tutorials | Kubernetes
statefulset.apps/web patched
There are still five PersistentVolumeClaims and five PersistentVolumes. When exploring a
Pod's stable storage, we saw that the PersistentVolumes mounted to the Pods of a StatefulSet
are not deleted when the StatefulSet's Pods are deleted. This is still true when Pod deletion is
caused by scaling the StatefulSet down.
Updating StatefulSets
In Kubernetes 1.7 and later, the StatefulSet controller supports automated updates. The
strategy used is determined by the spec.updateStrategy field of the StatefulSet API Object.
This feature can be used to upgrade the container images, resource requests and/or limits,
labels, and annotations of the Pods in a StatefulSet. There are two valid update strategies,
RollingUpdate and OnDelete .
https://kubernetes.io/docs/tutorials/_print/ 84/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Rolling Update
The RollingUpdate update strategy will update all Pods in a StatefulSet, in reverse ordinal
order, while respecting the StatefulSet guarantees.
statefulset.apps/web patched
In one terminal window, patch the web StatefulSet to change the container image again:
statefulset.apps/web patched
https://kubernetes.io/docs/tutorials/_print/ 85/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The Pods in the StatefulSet are updated in reverse ordinal order. The StatefulSet controller
terminates each Pod, and waits for it to transition to Running and Ready prior to updating the
next Pod. Note that, even though the StatefulSet controller will not proceed to update the
next Pod until its ordinal successor is Running and Ready, it will restore any Pod that fails
during the update to its current version.
Pods that have already received the update will be restored to the updated version, and Pods
that have not yet received the update will be restored to the previous version. In this way, the
controller attempts to continue to keep the application healthy and the update consistent in
the presence of intermittent failures.
registry.k8s.io/nginx-slim:0.8
registry.k8s.io/nginx-slim:0.8
registry.k8s.io/nginx-slim:0.8
All the Pods in the StatefulSet are now running the previous container image.
Note: You can also use kubectl rollout status sts/<name> to view the status of a
rolling update to a StatefulSet
Staging an Update
You can stage an update to a StatefulSet by using the partition parameter of the
RollingUpdate update strategy. A staged update will keep all of the Pods in the StatefulSet at
the current version while allowing mutations to the StatefulSet's .spec.template .
statefulset.apps/web patched
statefulset.apps/web patched
https://kubernetes.io/docs/tutorials/_print/ 86/155
6/6/23, 4:10 PM Tutorials | Kubernetes
registry.k8s.io/nginx-slim:0.8
Notice that, even though the update strategy is RollingUpdate the StatefulSet restored the
Pod with its original container. This is because the ordinal of the Pod is less than the
partition specified by the updateStrategy .
statefulset.apps/web patched
registry.k8s.io/nginx-slim:0.7
When you changed the partition , the StatefulSet controller automatically updated the web-
2 Pod because the Pod's ordinal was greater than or equal to the partition .
https://kubernetes.io/docs/tutorials/_print/ 87/155
6/6/23, 4:10 PM Tutorials | Kubernetes
registry.k8s.io/nginx-slim:0.8
web-1 was restored to its original configuration because the Pod's ordinal was less than the
partition. When a partition is specified, all Pods with an ordinal that is greater than or equal to
the partition will be updated when the StatefulSet's .spec.template is updated. If a Pod that
has an ordinal less than the partition is deleted or otherwise terminated, it will be restored to
its original configuration.
statefulset.apps/web patched
Wait for all of the Pods in the StatefulSet to become Running and Ready.
https://kubernetes.io/docs/tutorials/_print/ 88/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Get the container image details for the Pods in the StatefulSet:
registry.k8s.io/nginx-slim:0.7
registry.k8s.io/nginx-slim:0.7
registry.k8s.io/nginx-slim:0.7
By moving the partition to 0 , you allowed the StatefulSet to continue the update process.
On Delete
The OnDelete update strategy implements the legacy (1.6 and prior) behavior, When you
select this update strategy, the StatefulSet controller will not automatically update Pods when
a modification is made to the StatefulSet's .spec.template field. This strategy can be
selected by setting the .spec.template.updateStrategy.type to OnDelete .
Deleting StatefulSets
StatefulSet supports both Non-Cascading and Cascading deletion. In a Non-Cascading Delete,
the StatefulSet's Pods are not deleted when the StatefulSet is deleted. In a Cascading Delete,
both the StatefulSet and its Pods are deleted.
Non-Cascading Delete
In one terminal window, watch the Pods in the StatefulSet.
Use kubectl delete to delete the StatefulSet. Make sure to supply the --cascade=orphan
parameter to the command. This parameter tells Kubernetes to only delete the StatefulSet,
and to not delete any of its Pods.
Even though web has been deleted, all of the Pods are still Running and Ready. Delete web-
0 :
As the web StatefulSet has been deleted, web-0 has not been relaunched.
In a second terminal, recreate the StatefulSet. Note that, unless you deleted the nginx
Service (which you should not have), you will see an error indicating that the Service already
exists.
statefulset.apps/web created
service/nginx unchanged
Ignore the error. It only indicates that an attempt was made to create the nginx headless
Service even though that Service already exists.
Examine the output of the kubectl get command running in the first terminal.
https://kubernetes.io/docs/tutorials/_print/ 90/155
6/6/23, 4:10 PM Tutorials | Kubernetes
When the web StatefulSet was recreated, it first relaunched web-0 . Since web-1 was already
Running and Ready, when web-0 transitioned to Running and Ready, it adopted this Pod.
Since you recreated the StatefulSet with replicas equal to 2, once web-0 had been
recreated, and once web-1 had been determined to already be Running and Ready, web-2
was terminated.
Let's take another look at the contents of the index.html file served by the Pods' webservers:
web-0
web-1
Even though you deleted both the StatefulSet and the web-0 Pod, it still serves the hostname
originally entered into its index.html file. This is because the StatefulSet never deletes the
PersistentVolumes associated with a Pod. When you recreated the StatefulSet and it
relaunched web-0 , its original PersistentVolume was remounted.
Cascading Delete
In one terminal window, watch the Pods in the StatefulSet.
In another terminal, delete the StatefulSet again. This time, omit the --cascade=orphan
parameter.
Examine the output of the kubectl get command running in the first terminal, and wait for
all of the Pods to transition to Terminating.
https://kubernetes.io/docs/tutorials/_print/ 91/155
6/6/23, 4:10 PM Tutorials | Kubernetes
As you saw in the Scaling Down section, the Pods are terminated one at a time, with respect
to the reverse order of their ordinal indices. Before terminating a Pod, the StatefulSet
controller waits for the Pod's successor to be completely terminated.
Note: Although a cascading delete removes a StatefulSet together with its Pods, the
cascade does not delete the headless Service associated with the StatefulSet. You must
delete the nginx Service manually.
service/nginx created
statefulset.apps/web created
When all of the StatefulSet's Pods transition to Running and Ready, retrieve the contents of
their index.html files:
web-0
web-1
Even though you completely deleted the StatefulSet, and all of its Pods, the Pods are
recreated with their PersistentVolumes mounted, and web-0 and web-1 continue to serve
their hostnames.
application/web/web-parallel.yaml
https://kubernetes.io/docs/tutorials/_print/ 93/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: "nginx"
podManagementPolicy: "Parallel"
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: registry.k8s.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
This manifest is identical to the one you downloaded above except that the
.spec.podManagementPolicy of the web StatefulSet is set to Parallel .
https://kubernetes.io/docs/tutorials/_print/ 94/155
6/6/23, 4:10 PM Tutorials | Kubernetes
service/nginx created
statefulset.apps/web created
Examine the output of the kubectl get command that you executed in the first terminal.
The StatefulSet controller launched both web-0 and web-1 at the same time.
Keep the second terminal open, and, in another terminal window scale the StatefulSet:
statefulset.apps/web scaled
Examine the output of the terminal where the kubectl get command is running.
The StatefulSet launched two new Pods, and it did not wait for the first to become Running
and Ready prior to launching the second.
Cleaning up
You should have two terminals open, ready for you to run kubectl commands as part of
cleanup.
You can watch kubectl get to see those Pods being deleted.
https://kubernetes.io/docs/tutorials/_print/ 95/155
6/6/23, 4:10 PM Tutorials | Kubernetes
During deletion, a StatefulSet removes all Pods concurrently; it does not wait for a Pod's
ordinal successor to terminate prior to deleting that Pod.
Close the terminal where the kubectl get command is running and delete the nginx
Service:
Delete the persistent storage media for the PersistentVolumes used in this tutorial.
kubectl get pv
https://kubernetes.io/docs/tutorials/_print/ 96/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Note: You also need to delete the persistent storage media for the PersistentVolumes
used in this tutorial. Follow the necessary steps, based on your environment, storage
configuration, and provisioning method, to ensure that all storage is reclaimed.
https://kubernetes.io/docs/tutorials/_print/ 97/155
6/6/23, 4:10 PM Tutorials | Kubernetes
A PersistentVolume (PV) is a piece of storage in the cluster that has been manually
provisioned by an administrator, or dynamically provisioned by Kubernetes using a
StorageClass. A PersistentVolumeClaim (PVC) is a request for storage by a user that can be
fulfilled by a PV. PersistentVolumes and PersistentVolumeClaims are independent from Pod
lifecycles and preserve data through restarting, rescheduling, and even deleting Pods.
Warning: This deployment is not suitable for production use cases, as it uses single
instance WordPress and MySQL Pods. Consider using WordPress Helm Chart to deploy
WordPress in production.
Note: The files provided in this tutorial are using GA Deployment APIs and are specific to
kubernetes version 1.9 and later. If you wish to use this tutorial with an earlier version of
Kubernetes, please update the API version appropriately, or reference earlier versions of
this tutorial.
Objectives
Create PersistentVolumeClaims and PersistentVolumes
Create a kustomization.yaml with
a Secret generator
MySQL resource configs
WordPress resource configs
Apply the kustomization directory by kubectl apply -k ./
Clean up
Killercoda
Play with Kubernetes
The example shown on this page works with kubectl 1.14 and above.
1. mysql-deployment.yaml
2. wordpress-deployment.yaml
https://kubernetes.io/docs/tutorials/_print/ 98/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Many cluster environments have a default StorageClass installed. When a StorageClass is not
specified in the PersistentVolumeClaim, the cluster's default StorageClass is used instead.
Warning: In local clusters, the default StorageClass uses the hostPath provisioner.
hostPath volumes are only suitable for development and testing. With hostPath volumes,
your data lives in /tmp on the node the Pod is scheduled onto and does not move
between nodes. If a Pod dies and gets scheduled to another node in the cluster, or the
node is rebooted, the data is lost.
Note: If you are bringing up a cluster that needs to use the hostPath provisioner, the --
enable-hostpath-provisioner flag must be set in the controller-manager component.
Note: If you have a Kubernetes cluster running on Google Kubernetes Engine, please
follow this guide.
Create a kustomization.yaml
Add a Secret generator
A Secret is an object that stores a piece of sensitive data like a password or key. Since 1.14,
kubectl supports the management of Kubernetes objects using a kustomization file. You can
create a Secret by generators in kustomization.yaml .
Add a Secret generator in kustomization.yaml from the following command. You will need to
replace YOUR_PASSWORD with the password you want to use.
application/wordpress/mysql-deployment.yaml
https://kubernetes.io/docs/tutorials/_print/ 99/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: wordpress-mysql
labels:
app: wordpress
spec:
ports:
- port: 3306
selector:
app: wordpress
tier: mysql
clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pv-claim
labels:
app: wordpress
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: wordpress-mysql
labels:
app: wordpress
spec:
selector:
matchLabels:
app: wordpress
tier: mysql
strategy:
type: Recreate
template:
metadata:
labels:
app: wordpress
tier: mysql
spec:
containers:
- image: mysql:5.6
name: mysql
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-pass
key: password
ports:
- containerPort: 3306
name: mysql
volumeMounts:
- name: mysql-persistent-storage
mountPath: /var/lib/mysql
volumes:
- name: mysql-persistent-storage
persistentVolumeClaim:
claimName: mysql-pv-claim
https://kubernetes.io/docs/tutorials/_print/ 100/155
6/6/23, 4:10 PM Tutorials | Kubernetes
application/wordpress/wordpress-deployment.yaml
https://kubernetes.io/docs/tutorials/_print/ 101/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: wordpress
labels:
app: wordpress
spec:
ports:
- port: 80
selector:
app: wordpress
tier: frontend
type: LoadBalancer
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: wp-pv-claim
labels:
app: wordpress
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: wordpress
labels:
app: wordpress
spec:
selector:
matchLabels:
app: wordpress
tier: frontend
strategy:
type: Recreate
template:
metadata:
labels:
app: wordpress
tier: frontend
spec:
containers:
- image: wordpress:4.8-apache
name: wordpress
env:
- name: WORDPRESS_DB_HOST
value: wordpress-mysql
- name: WORDPRESS_DB_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-pass
key: password
ports:
- containerPort: 80
name: wordpress
volumeMounts:
- name: wordpress-persistent-storage
mountPath: /var/www/html
volumes:
- name: wordpress-persistent-storage
persistentVolumeClaim:
https://kubernetes.io/docs/tutorials/_print/ 102/155
6/6/23, 4:10 PM Tutorials | Kubernetes
claimName: wp-pv-claim
kubectl apply -k ./
Note: It can take up to a few minutes for the PVs to be provisioned and bound.
https://kubernetes.io/docs/tutorials/_print/ 103/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Note: It can take up to a few minutes for the Pod's Status to be RUNNING.
Note: Minikube can only expose Services through NodePort. The EXTERNAL-IP is
always pending.
5. Run the following command to get the IP Address for the WordPress Service:
http://1.2.3.4:32406
6. Copy the IP address, and load the page in your browser to view your site.
You should see the WordPress set up page similar to the following screenshot.
https://kubernetes.io/docs/tutorials/_print/ 104/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Warning: Do not leave your WordPress installation on this page. If another user
finds it, they can set up a website on your instance and use it to serve malicious
content.
Cleaning up
1. Run the following command to delete your Secret, Deployments, Services and
PersistentVolumeClaims:
kubectl delete -k ./
What's next
Learn more about Introspection and Debugging
Learn more about Jobs
Learn more about Port Forwarding
Learn how to Get a Shell to a Container
https://kubernetes.io/docs/tutorials/_print/ 105/155
6/6/23, 4:10 PM Tutorials | Kubernetes
StatefulSets make it easier to deploy stateful applications into your Kubernetes cluster. For
more information on the features used in this tutorial, see StatefulSet.
Note:
Cassandra and Kubernetes both use the term node to mean a member of a cluster. In this
tutorial, the Pods that belong to the StatefulSet are Cassandra nodes and are members of
the Cassandra cluster (called a ring). When those Pods run in your Kubernetes cluster, the
Kubernetes control plane schedules those Pods onto Kubernetes Nodes.
When a Cassandra node starts, it uses a seed list to bootstrap discovery of other nodes in
the ring. This tutorial deploys a custom Cassandra seed provider that lets the database
discover new Cassandra Pods as they appear inside your Kubernetes cluster.
Objectives
Create and validate a Cassandra headless Service.
Use a StatefulSet to create a Cassandra ring.
Validate the StatefulSet.
Modify the StatefulSet.
Delete the StatefulSet and its Pods.
Killercoda
Play with Kubernetes
To complete this tutorial, you should already have a basic familiarity with Pods, Services, and
StatefulSets.
Caution:
Minikube defaults to 2048MB of memory and 2 CPU. Running Minikube with the default
resource configuration results in insufficient resource errors during this tutorial. To avoid
these errors, start Minikube with the following settings:
https://kubernetes.io/docs/tutorials/_print/ 106/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The following Service is used for DNS lookups between Cassandra Pods and clients within
your cluster:
application/cassandra/cassandra-service.yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: cassandra
name: cassandra
spec:
clusterIP: None
ports:
- port: 9042
selector:
app: cassandra
Create a Service to track all Cassandra StatefulSet members from the cassandra-
service.yaml file:
Validating (optional)
Get the Cassandra Service.
The response is
If you don't see a Service named cassandra , that means creation failed. Read Debug Services
for help troubleshooting common issues.
The StatefulSet manifest, included below, creates a Cassandra ring that consists of three
Pods.
Note: This example uses the default provisioner for Minikube. Please update the
following StatefulSet for the cloud you are working with.
application/cassandra/cassandra-statefulset.yaml
https://kubernetes.io/docs/tutorials/_print/ 107/155
6/6/23, 4:10 PM Tutorials | Kubernetes
https://kubernetes.io/docs/tutorials/_print/ 108/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: cassandra
labels:
app: cassandra
spec:
serviceName: cassandra
replicas: 3
selector:
matchLabels:
app: cassandra
template:
metadata:
labels:
app: cassandra
spec:
terminationGracePeriodSeconds: 1800
containers:
- name: cassandra
image: gcr.io/google-samples/cassandra:v13
imagePullPolicy: Always
ports:
- containerPort: 7000
name: intra-node
- containerPort: 7001
name: tls-intra-node
- containerPort: 7199
name: jmx
- containerPort: 9042
name: cql
resources:
limits:
cpu: "500m"
memory: 1Gi
requests:
cpu: "500m"
memory: 1Gi
securityContext:
capabilities:
add:
- IPC_LOCK
lifecycle:
preStop:
exec:
command:
- /bin/sh
- -c
- nodetool drain
env:
- name: MAX_HEAP_SIZE
value: 512M
- name: HEAP_NEWSIZE
value: 100M
- name: CASSANDRA_SEEDS
value: "cassandra-0.cassandra.default.svc.cluster.local"
- name: CASSANDRA_CLUSTER_NAME
value: "K8Demo"
- name: CASSANDRA_DC
value: "DC1-K8Demo"
- name: CASSANDRA_RACK
value: "Rack1-K8Demo"
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
https://kubernetes.io/docs/tutorials/_print/ 109/155
6/6/23, 4:10 PM Tutorials | Kubernetes
readinessProbe:
exec:
command:
- /bin/bash
- -c
- /ready-probe.sh
initialDelaySeconds: 15
timeoutSeconds: 5
# These volume mounts are persistent. They are like inline claims,
# but not exactly because the names need to match exactly one of
# the stateful pod volumes.
volumeMounts:
- name: cassandra-data
mountPath: /cassandra_data
# These are converted to volume claims by the controller
# and mounted at the paths mentioned above.
# do not use these in production until ssd GCEPersistentDisk or other ssd pd
volumeClaimTemplates:
- metadata:
name: cassandra-data
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: fast
resources:
requests:
storage: 1Gi
---
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: fast
provisioner: k8s.io/minikube-hostpath
parameters:
type: pd-ssd
https://kubernetes.io/docs/tutorials/_print/ 110/155
6/6/23, 4:10 PM Tutorials | Kubernetes
It can take several minutes for all three Pods to deploy. Once they are deployed, the
same command returns output similar to:
3. Run the Cassandra nodetool inside the first Pod, to display the status of the ring.
Datacenter: DC1-K8Demo
======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns (effective) Host ID
UN 172.17.0.5 83.57 KiB 32 74.0% e2dd09e6-d9d3-477e-
UN 172.17.0.4 101.04 KiB 32 58.8% f89d6835-3a42-4419
UN 172.17.0.6 84.74 KiB 32 67.1% a6a1e8c2-3dc5-4417-
This command opens an editor in your terminal. The line you need to change is the
replicas field. The following sample is an excerpt of the StatefulSet file:
https://kubernetes.io/docs/tutorials/_print/ 111/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving thi
# reopened with the relevant failures.
#
apiVersion: apps/v1
kind: StatefulSet
metadata:
creationTimestamp: 2016-08-13T18:40:58Z
generation: 1
labels:
app: cassandra
name: cassandra
namespace: default
resourceVersion: "323"
uid: 7a219483-6185-11e6-a910-42010a8a0fc0
spec:
replicas: 3
Cleaning up
Deleting or scaling a StatefulSet down does not delete the volumes associated with the
StatefulSet. This setting is for your safety because your data is more valuable than
automatically purging all related StatefulSet resources.
Warning: Depending on the storage class and reclaim policy, deleting the
PersistentVolumeClaims may cause the associated volumes to also be deleted. Never
assume you'll be able to access data if its volume claims are deleted.
1. Run the following commands (chained together into a single command) to delete
everything in the Cassandra StatefulSet:
2. Run the following command to delete the Service you set up for Cassandra:
https://kubernetes.io/docs/tutorials/_print/ 112/155
6/6/23, 4:10 PM Tutorials | Kubernetes
This image includes a standard Cassandra installation from the Apache Debian repo. By using
environment variables you can change values that are inserted into cassandra.yaml .
CASSANDRA_NUM_TOKENS 32
CASSANDRA_RPC_ADDRESS 0.0.0.0
What's next
Learn how to Scale a StatefulSet.
Learn more about the KubernetesSeedProvider
See more custom Seed Provider Configurations
https://kubernetes.io/docs/tutorials/_print/ 113/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Pods
Cluster DNS
Headless Services
PersistentVolumes
PersistentVolume Provisioning
StatefulSets
PodDisruptionBudgets
PodAntiAffinity
kubectl CLI
You must have a cluster with at least four nodes, and each node requires at least 2 CPUs and
4 GiB of memory. In this tutorial you will cordon and drain the cluster's nodes. This means
that the cluster will terminate and evict all Pods on its nodes, and the nodes will
temporarily become unschedulable. You should use a dedicated cluster for this tutorial, or
you should ensure that the disruption you cause will not interfere with other tenants.
This tutorial assumes that you have configured your cluster to dynamically provision
PersistentVolumes. If your cluster is not configured to do so, you will have to manually
provision three 20 GiB volumes before starting this tutorial.
Objectives
After this tutorial, you will know the following.
ZooKeeper
Apache ZooKeeper is a distributed, open-source coordination service for distributed
applications. ZooKeeper allows you to read, write, and observe updates to data. Data are
organized in a file system like hierarchy and replicated to all ZooKeeper servers in the
ensemble (a set of ZooKeeper servers). All operations on data are atomic and sequentially
consistent. ZooKeeper ensures this by using the Zab consensus protocol to replicate a state
machine across all servers in the ensemble.
The ensemble uses the Zab protocol to elect a leader, and the ensemble cannot write data
until that election is complete. Once complete, the ensemble uses Zab to ensure that it
replicates all writes to a quorum before it acknowledges and makes them visible to clients.
Without respect to weighted quorums, a quorum is a majority component of the ensemble
containing the current leader. For instance, if the ensemble has three servers, a component
that contains the leader and one other server constitutes a quorum. If the ensemble can not
achieve a quorum, the ensemble cannot write data.
https://kubernetes.io/docs/tutorials/_print/ 114/155
6/6/23, 4:10 PM Tutorials | Kubernetes
ZooKeeper servers keep their entire state machine in memory, and write every mutation to a
durable WAL (Write Ahead Log) on storage media. When a server crashes, it can recover its
previous state by replaying the WAL. To prevent the WAL from growing without bound,
ZooKeeper servers will periodically snapshot them in memory state to storage media. These
snapshots can be loaded directly into memory, and all WAL entries that preceded the
snapshot may be discarded.
application/zookeeper/zookeeper.yaml
https://kubernetes.io/docs/tutorials/_print/ 115/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: zk-hs
labels:
app: zk
spec:
ports:
- port: 2888
name: server
- port: 3888
name: leader-election
clusterIP: None
selector:
app: zk
---
apiVersion: v1
kind: Service
metadata:
name: zk-cs
labels:
app: zk
spec:
ports:
- port: 2181
name: client
selector:
app: zk
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: zk-pdb
spec:
selector:
matchLabels:
app: zk
maxUnavailable: 1
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: zk
spec:
selector:
matchLabels:
app: zk
serviceName: zk-hs
replicas: 3
updateStrategy:
type: RollingUpdate
podManagementPolicy: OrderedReady
template:
metadata:
labels:
app: zk
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: "app"
operator: In
values:
- zk
https://kubernetes.io/docs/tutorials/_print/ 116/155
6/6/23, 4:10 PM Tutorials | Kubernetes
topologyKey: "kubernetes.io/hostname"
containers:
- name: kubernetes-zookeeper
imagePullPolicy: Always
image: "registry.k8s.io/kubernetes-zookeeper:1.0-3.4.10"
resources:
requests:
memory: "1Gi"
cpu: "0.5"
ports:
- containerPort: 2181
name: client
- containerPort: 2888
name: server
- containerPort: 3888
name: leader-election
command:
- sh
- -c
- "start-zookeeper \
--servers=3 \
--data_dir=/var/lib/zookeeper/data \
--data_log_dir=/var/lib/zookeeper/data/log \
--conf_dir=/opt/zookeeper/conf \
--client_port=2181 \
--election_port=3888 \
--server_port=2888 \
--tick_time=2000 \
--init_limit=10 \
--sync_limit=5 \
--heap=512M \
--max_client_cnxns=60 \
--snap_retain_count=3 \
--purge_interval=12 \
--max_session_timeout=40000 \
--min_session_timeout=4000 \
--log_level=INFO"
readinessProbe:
exec:
command:
- sh
- -c
- "zookeeper-ready 2181"
initialDelaySeconds: 10
timeoutSeconds: 5
livenessProbe:
exec:
command:
- sh
- -c
- "zookeeper-ready 2181"
initialDelaySeconds: 10
timeoutSeconds: 5
volumeMounts:
- name: datadir
mountPath: /var/lib/zookeeper
securityContext:
runAsUser: 1000
fsGroup: 1000
volumeClaimTemplates:
- metadata:
name: datadir
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi
https://kubernetes.io/docs/tutorials/_print/ 117/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Open a terminal, and use the kubectl apply command to create the manifest.
This creates the zk-hs Headless Service, the zk-cs Service, the zk-pdb
PodDisruptionBudget, and the zk StatefulSet.
service/zk-hs created
service/zk-cs created
poddisruptionbudget.policy/zk-pdb created
statefulset.apps/zk created
Use kubectl get to watch the StatefulSet controller create the StatefulSet's Pods.
Once the zk-2 Pod is Running and Ready, use CTRL-C to terminate kubectl.
The StatefulSet controller creates three Pods, and each Pod has a container with a ZooKeeper
server.
Use kubectl exec to get the hostnames of the Pods in the zk StatefulSet.
The StatefulSet controller provides each Pod with a unique hostname based on its ordinal
index. The hostnames take the form of <statefulset name>-<ordinal index> . Because the
replicas field of the zk StatefulSet is set to 3 , the Set's controller creates three Pods with
their hostnames set to zk-0 , zk-1 , and zk-2 .
https://kubernetes.io/docs/tutorials/_print/ 118/155
6/6/23, 4:10 PM Tutorials | Kubernetes
zk-0
zk-1
zk-2
The servers in a ZooKeeper ensemble use natural numbers as unique identifiers, and store
each server's identifier in a file called myid in the server's data directory.
To examine the contents of the myid file for each server use the following command.
Because the identifiers are natural numbers and the ordinal indices are non-negative
integers, you can generate an identifier by adding 1 to the ordinal.
myid zk-0
1
myid zk-1
2
myid zk-2
3
To get the Fully Qualified Domain Name (FQDN) of each Pod in the zk StatefulSet use the
following command.
The zk-hs Service creates a domain for all of the Pods, zk-hs.default.svc.cluster.local .
zk-0.zk-hs.default.svc.cluster.local
zk-1.zk-hs.default.svc.cluster.local
zk-2.zk-hs.default.svc.cluster.local
The A records in Kubernetes DNS resolve the FQDNs to the Pods' IP addresses. If Kubernetes
reschedules the Pods, it will update the A records with the Pods' new IP addresses, but the A
records names will not change.
ZooKeeper stores its application configuration in a file named zoo.cfg . Use kubectl exec to
view the contents of the zoo.cfg file in the zk-0 Pod.
In the server.1 , server.2 , and server.3 properties at the bottom of the file, the 1 , 2 ,
and 3 correspond to the identifiers in the ZooKeeper servers' myid files. They are set to the
FQDNs for the Pods in the zk StatefulSet.
https://kubernetes.io/docs/tutorials/_print/ 119/155
6/6/23, 4:10 PM Tutorials | Kubernetes
clientPort=2181
dataDir=/var/lib/zookeeper/data
dataLogDir=/var/lib/zookeeper/log
tickTime=2000
initLimit=10
syncLimit=2000
maxClientCnxns=60
minSessionTimeout= 4000
maxSessionTimeout= 40000
autopurge.snapRetainCount=3
autopurge.purgeInterval=0
server.1=zk-0.zk-hs.default.svc.cluster.local:2888:3888
server.2=zk-1.zk-hs.default.svc.cluster.local:2888:3888
server.3=zk-2.zk-hs.default.svc.cluster.local:2888:3888
Achieving consensus
Consensus protocols require that the identifiers of each participant be unique. No two
participants in the Zab protocol should claim the same unique identifier. This is necessary to
allow the processes in the system to agree on which processes have committed which data. If
two Pods are launched with the same ordinal, two ZooKeeper servers would both identify
themselves as the same server.
The A records for each Pod are entered when the Pod becomes Ready. Therefore, the FQDNs
of the ZooKeeper servers will resolve to a single endpoint, and that endpoint will be the
unique ZooKeeper server claiming the identity configured in its myid file.
zk-0.zk-hs.default.svc.cluster.local
zk-1.zk-hs.default.svc.cluster.local
zk-2.zk-hs.default.svc.cluster.local
This ensures that the servers properties in the ZooKeepers' zoo.cfg files represents a
correctly configured ensemble.
server.1=zk-0.zk-hs.default.svc.cluster.local:2888:3888
server.2=zk-1.zk-hs.default.svc.cluster.local:2888:3888
server.3=zk-2.zk-hs.default.svc.cluster.local:2888:3888
When the servers use the Zab protocol to attempt to commit a value, they will either achieve
consensus and commit the value (if leader election has succeeded and at least two of the
Pods are Running and Ready), or they will fail to do so (if either of the conditions are not met).
No state will arise where one server acknowledges a write on behalf of another.
https://kubernetes.io/docs/tutorials/_print/ 120/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The command below executes the zkCli.sh script to write world to the path /hello on
the zk-0 Pod in the ensemble.
WATCHER::
To get the data from the zk-1 Pod use the following command.
The data that you created on zk-0 is available on all the servers in the ensemble.
WATCHER::
https://kubernetes.io/docs/tutorials/_print/ 121/155
6/6/23, 4:10 PM Tutorials | Kubernetes
This creates the zk StatefulSet object, but the other API objects in the manifest are not
modified because they already exist.
Once the zk-2 Pod is Running and Ready, use CTRL-C to terminate kubectl.
Use the command below to get the value you entered during the sanity test, from the zk-2
Pod.
Even though you terminated and recreated all of the Pods in the zk StatefulSet, the
ensemble still serves the original value.
https://kubernetes.io/docs/tutorials/_print/ 122/155
6/6/23, 4:10 PM Tutorials | Kubernetes
WATCHER::
volumeClaimTemplates:
- metadata:
name: datadir
annotations:
volume.alpha.kubernetes.io/storage-class: anything
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 20Gi
When the StatefulSet recreated its Pods, it remounts the Pods' PersistentVolumes.
The volumeMounts section of the StatefulSet 's container template mounts the
PersistentVolumes in the ZooKeeper servers' data directories.
volumeMounts:
- name: datadir
mountPath: /var/lib/zookeeper
https://kubernetes.io/docs/tutorials/_print/ 123/155
6/6/23, 4:10 PM Tutorials | Kubernetes
…
command:
- sh
- -c
- "start-zookeeper \
--servers=3 \
--data_dir=/var/lib/zookeeper/data \
--data_log_dir=/var/lib/zookeeper/data/log \
--conf_dir=/opt/zookeeper/conf \
--client_port=2181 \
--election_port=3888 \
--server_port=2888 \
--tick_time=2000 \
--init_limit=10 \
--sync_limit=5 \
--heap=512M \
--max_client_cnxns=60 \
--snap_retain_count=3 \
--purge_interval=12 \
--max_session_timeout=40000 \
--min_session_timeout=4000 \
--log_level=INFO"
…
The command used to start the ZooKeeper servers passed the configuration as command line
parameter. You can also use environment variables to pass configuration to the ensemble.
Configuring logging
One of the files generated by the zkGenConfig.sh script controls ZooKeeper's logging.
ZooKeeper uses Log4j, and, by default, it uses a time and size based rolling file appender for
its logging configuration.
Use the command below to get the logging configuration from one of Pods in the zk
StatefulSet .
The logging configuration below will cause the ZooKeeper process to write all of its logs to the
standard output file stream.
zookeeper.root.logger=CONSOLE
zookeeper.console.threshold=INFO
log4j.rootLogger=${zookeeper.root.logger}
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=${zookeeper.console.threshold}
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} [myid:%X{myid}] - %-5
https://kubernetes.io/docs/tutorials/_print/ 124/155
6/6/23, 4:10 PM Tutorials | Kubernetes
This is the simplest possible way to safely log inside the container. Because the applications
write logs to standard out, Kubernetes will handle log rotation for you. Kubernetes also
implements a sane retention policy that ensures application logs written to standard out and
standard error do not exhaust local storage media.
Use kubectl logs to retrieve the last 20 log lines from one of the Pods.
You can view application logs written to standard out or standard error using kubectl logs
and from the Kubernetes Dashboard.
Kubernetes integrates with many logging solutions. You can choose a logging solution that
best fits your cluster and applications. For cluster-level logging and aggregation, consider
deploying a sidecar container to rotate and ship your logs.
securityContext:
runAsUser: 1000
fsGroup: 1000
In the Pods' containers, UID 1000 corresponds to the zookeeper user and GID 1000
corresponds to the zookeeper group.
As the runAsUser field of the securityContext object is set to 1000, instead of running as
root, the ZooKeeper process runs as the zookeeper user.
https://kubernetes.io/docs/tutorials/_print/ 125/155
6/6/23, 4:10 PM Tutorials | Kubernetes
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
4 S zookeep+ 1 0 0 80 0 - 1127 - 20:46 ? 00:00:00 sh -c
0 S zookeep+ 27 1 0 80 0 - 1155556 - 20:46 ? 00:00:19 /usr/l
By default, when the Pod's PersistentVolumes is mounted to the ZooKeeper server's data
directory, it is only accessible by the root user. This configuration prevents the ZooKeeper
process from writing to its WAL and storing its snapshots.
Use the command below to get the file permissions of the ZooKeeper data directory on the
zk-0 Pod.
Because the fsGroup field of the securityContext object is set to 1000, the ownership of
the Pods' PersistentVolumes is set to the zookeeper group, and the ZooKeeper process is able
to read and write its data.
You can use kubectl patch to update the number of cpus allocated to the servers.
statefulset.apps/zk patched
https://kubernetes.io/docs/tutorials/_print/ 126/155
6/6/23, 4:10 PM Tutorials | Kubernetes
This terminates the Pods, one at a time, in reverse ordinal order, and recreates them with the
new configuration. This ensures that quorum is maintained during a rolling update.
Use the kubectl rollout history command to view a history or previous configurations.
statefulsets "zk"
REVISION
1
2
Use the kubectl rollout undo command to roll back the modification.
Use the following command to examine the process tree for the ZooKeeper server running in
the zk-0 Pod.
The command used as the container's entry point has PID 1, and the ZooKeeper process, a
child of the entry point, has PID 27.
In another terminal watch the Pods in the zk StatefulSet with the following command.
In another terminal, terminate the ZooKeeper process in Pod zk-0 with the following
command.
https://kubernetes.io/docs/tutorials/_print/ 127/155
6/6/23, 4:10 PM Tutorials | Kubernetes
The termination of the ZooKeeper process caused its parent process to terminate. Because
the RestartPolicy of the container is Always, it restarted the parent process.
If your application uses a script (such as zkServer.sh ) to launch the process that implements
the application's business logic, the script must terminate with the child process. This ensures
that Kubernetes will restart the application's container when the process implementing the
application's business logic fails.
livenessProbe:
exec:
command:
- sh
- -c
- "zookeeper-ready 2181"
initialDelaySeconds: 15
timeoutSeconds: 5
The probe calls a bash script that uses the ZooKeeper ruok four letter word to test the
server's health.
In one terminal window, use the following command to watch the Pods in the zk StatefulSet.
In another window, using the following command to delete the zookeeper-ready script from
the file system of Pod zk-0 .
When the liveness probe for the ZooKeeper process fails, Kubernetes will automatically
restart the process for you, ensuring that unhealthy processes in the ensemble are restarted.
https://kubernetes.io/docs/tutorials/_print/ 128/155
6/6/23, 4:10 PM Tutorials | Kubernetes
If you specify a readiness probe, Kubernetes will ensure that your application's processes will
not receive network traffic until their readiness checks pass.
For a ZooKeeper server, liveness implies readiness. Therefore, the readiness probe from the
zookeeper.yaml manifest is identical to the liveness probe.
readinessProbe:
exec:
command:
- sh
- -c
- "zookeeper-ready 2181"
initialDelaySeconds: 15
timeoutSeconds: 5
Even though the liveness and readiness probes are identical, it is important to specify both.
This ensures that only healthy servers in the ZooKeeper ensemble receive network traffic.
By default, Kubernetes may co-locate Pods in a StatefulSet on the same node. For the three
server ensemble you created, if two servers are on the same node, and that node fails, the
clients of your ZooKeeper service will experience an outage until at least one of the Pods can
be rescheduled.
You should always provision additional capacity to allow the processes of critical systems to
be rescheduled in the event of node failures. If you do so, then the outage will only last until
the Kubernetes scheduler reschedules one of the ZooKeeper servers. However, if you want
your service to tolerate node failures with no downtime, you should set podAntiAffinity .
Use the command below to get the nodes for Pods in the zk StatefulSet .
https://kubernetes.io/docs/tutorials/_print/ 129/155
6/6/23, 4:10 PM Tutorials | Kubernetes
kubernetes-node-cxpk
kubernetes-node-a5aq
kubernetes-node-2g2d
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: "app"
operator: In
values:
- zk
topologyKey: "kubernetes.io/hostname"
Surviving maintenance
In this section you will cordon and drain nodes. If you are using this tutorial on a shared
cluster, be sure that this will not adversely affect other tenants.
The previous section showed you how to spread your Pods across nodes to survive
unplanned node failures, but you also need to plan for temporary node failures that occur
due to planned maintenance.
This tutorial assumes a cluster with at least four nodes. If the cluster has more than four, use
kubectl cordon to cordon all but four nodes. Constraining to four nodes will ensure
Kubernetes encounters affinity and PodDisruptionBudget constraints when scheduling
zookeeper Pods in the following maintenance simulation.
The max-unavailable field indicates to Kubernetes that at most one Pod from zk
StatefulSet can be unavailable at any time.
https://kubernetes.io/docs/tutorials/_print/ 130/155
6/6/23, 4:10 PM Tutorials | Kubernetes
In one terminal, use this command to watch the Pods in the zk StatefulSet .
In another terminal, use this command to get the nodes that the Pods are currently scheduled
on.
kubernetes-node-pb41
kubernetes-node-ixsl
kubernetes-node-i4c4
Use kubectl drain to cordon and drain the node on which the zk-0 Pod is scheduled.
As there are four nodes in your cluster, kubectl drain , succeeds and the zk-0 is
rescheduled to another node.
Keep watching the StatefulSet 's Pods in the first terminal and drain the node on which zk-
1 is scheduled.
"kubernetes-node-ixsl" cordoned
WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, or
pod "zk-1" deleted
node "kubernetes-node-ixsl" drained
Continue to watch the Pods of the StatefulSet, and drain the node on which zk-2 is
scheduled.
You cannot drain the third node because evicting zk-2 would violate zk-budget . However,
the node will remain cordoned.
Use zkCli.sh to retrieve the value you entered during the sanity test from zk-0 .
https://kubernetes.io/docs/tutorials/_print/ 132/155
6/6/23, 4:10 PM Tutorials | Kubernetes
zk-1 is rescheduled on this node. Wait until zk-1 is Running and Ready.
https://kubernetes.io/docs/tutorials/_print/ 133/155
6/6/23, 4:10 PM Tutorials | Kubernetes
You can use kubectl drain in conjunction with PodDisruptionBudgets to ensure that your
services remain available during maintenance. If drain is used to cordon nodes and evict pods
prior to taking the node offline for maintenance, services that express a disruption budget will
have that budget respected. You should always allocate additional capacity for critical services
so that their Pods can be immediately rescheduled.
Cleaning up
Use kubectl uncordon to uncordon all the nodes in your cluster.
You must delete the persistent storage media for the PersistentVolumes used in this
tutorial. Follow the necessary steps, based on your environment, storage configuration,
and provisioning method, to ensure that all storage is reclaimed.
https://kubernetes.io/docs/tutorials/_print/ 134/155
6/6/23, 4:10 PM Tutorials | Kubernetes
7 - Services
7.1 - Connecting Applications with
Services
Kubernetes assumes that pods can communicate with other pods, regardless of which host
they land on. Kubernetes gives every pod its own cluster-private IP address, so you do not
need to explicitly create links between pods or map container ports to host ports. This means
that containers within a Pod can all reach each other's ports on localhost, and all pods in a
cluster can see each other without NAT. The rest of this document elaborates on how you can
run reliable services on such a networking model.
This tutorial uses a simple nginx web server to demonstrate the concept.
service/networking/run-my-nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
run: my-nginx
replicas: 2
template:
metadata:
labels:
run: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
This makes it accessible from any node in your cluster. Check the nodes the Pod is running
on:
https://kubernetes.io/docs/tutorials/_print/ 135/155
6/6/23, 4:10 PM Tutorials | Kubernetes
You should be able to ssh into any node in your cluster and use a tool such as curl to make
queries against both IPs. Note that the containers are not using port 80 on the node, nor are
there any special NAT rules to route traffic to the pod. This means you can run multiple nginx
pods on the same node all using the same containerPort , and access them from any other
pod or node in your cluster using the assigned IP address for the Service. If you want to
arrange for a specific port on the host Node to be forwarded to backing Pods, you can - but
the networking model should mean that you do not need to do so.
You can read more about the Kubernetes Networking Model if you're curious.
Creating a Service
So we have pods running nginx in a flat, cluster wide, address space. In theory, you could talk
to these pods directly, but what happens when a node dies? The pods die with it, and the
Deployment will create new ones, with different IPs. This is the problem a Service solves.
A Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere
in your cluster, that all provide the same functionality. When created, each Service is assigned
a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service,
and will not change while the Service is alive. Pods can be configured to talk to the Service,
and know that communication to the Service will be automatically load-balanced out to some
pod that is a member of the Service.
You can create a Service for your 2 nginx replicas with kubectl expose :
service/my-nginx exposed
service/networking/nginx-svc.yaml
https://kubernetes.io/docs/tutorials/_print/ 136/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: v1
kind: Service
metadata:
name: my-nginx
labels:
run: my-nginx
spec:
ports:
- port: 80
protocol: TCP
selector:
run: my-nginx
This specification will create a Service which targets TCP port 80 on any Pod with the run: my-
nginx label, and expose it on an abstracted Service port ( targetPort : is the port the
container accepts traffic on, port : is the abstracted Service port, which can be any port other
pods use to access the Service). View Service API object to see the list of supported fields in
service definition. Check your Service:
As mentioned previously, a Service is backed by a group of Pods. These Pods are exposed
through EndpointSlices. The Service's selector will be evaluated continuously and the results
will be POSTed to an EndpointSlice that is connected to the Service using a labels. When a Pod
dies, it is automatically removed from the EndpointSlices that contain it as an endpoint. New
Pods that match the Service's selector will automatically get added to an EndpointSlice for
that Service. Check the endpoints, and note that the IPs are the same as the Pods created in
the first step:
Name: my-nginx
Namespace: default
Labels: run=my-nginx
Annotations: <none>
Selector: run=my-nginx
Type: ClusterIP
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.0.162.149
IPs: 10.0.162.149
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: 10.244.2.5:80,10.244.3.4:80
Session Affinity: None
Events: <none>
https://kubernetes.io/docs/tutorials/_print/ 137/155
6/6/23, 4:10 PM Tutorials | Kubernetes
You should now be able to curl the nginx Service on <CLUSTER-IP>:<PORT> from any node in
your cluster. Note that the Service IP is completely virtual, it never hits the wire. If you're
curious about how this works you can read more about the service proxy.
Note: If the service environment variables are not desired (because possible clashing with
expected program ones, too many variables to process, only using DNS, etc) you can
disable this mode by setting the enableServiceLinks flag to false on the pod spec.
Environment Variables
When a Pod runs on a Node, the kubelet adds a set of environment variables for each active
Service. This introduces an ordering problem. To see why, inspect the environment of your
running nginx Pods (your Pod name will be different):
KUBERNETES_SERVICE_HOST=10.0.0.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
Note there's no mention of your Service. This is because you created the replicas before the
Service. Another disadvantage of doing this is that the scheduler might put both Pods on the
same machine, which will take your entire Service down if it dies. We can do this the right way
by killing the 2 Pods and waiting for the Deployment to recreate them. This time around the
Service exists before the replicas. This will give you scheduler-level Service spreading of your
Pods (provided all your nodes have equal capacity), as well as the right environment variables:
You may notice that the pods have different names, since they are killed and recreated.
https://kubernetes.io/docs/tutorials/_print/ 138/155
6/6/23, 4:10 PM Tutorials | Kubernetes
KUBERNETES_SERVICE_PORT=443
MY_NGINX_SERVICE_HOST=10.0.162.149
KUBERNETES_SERVICE_HOST=10.0.0.1
MY_NGINX_SERVICE_PORT=80
KUBERNETES_SERVICE_PORT_HTTPS=443
DNS
Kubernetes offers a DNS cluster addon Service that automatically assigns dns names to other
Services. You can check if it's running on your cluster:
The rest of this section will assume you have a Service with a long lived IP (my-nginx), and a
DNS server that has assigned a name to that IP. Here we use the CoreDNS cluster addon
(application name kube-dns ), so you can talk to the Service from any pod in your cluster
using standard methods (e.g. gethostbyname() ). If CoreDNS isn't running, you can enable it
referring to the CoreDNS README or Installing CoreDNS. Let's run another curl application to
test this:
Name: my-nginx
Address 1: 10.0.162.149
Self signed certificates for https (unless you already have an identity certificate)
An nginx server configured to use the certificates
A secret that makes the certificates accessible to pods
You can acquire all these from the nginx https example. This requires having go and make
tools installed. If you don't want to install those, then follow the manual steps later. In short:
https://kubernetes.io/docs/tutorials/_print/ 139/155
6/6/23, 4:10 PM Tutorials | Kubernetes
secret/nginxsecret created
configmap/nginxconfigmap created
Following are the manual steps to follow in case you run into problems running make (on
windows for example):
Use the output from the previous commands to create a yaml file as follows. The base64
encoded value should all be on a single line.
apiVersion: "v1"
kind: "Secret"
metadata:
name: "nginxsecret"
namespace: "default"
type: kubernetes.io/tls
data:
tls.crt: "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURIekNDQWdlZ0F3SUJBZ0lKQUp5M
tls.key: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2UUlCQURBTkJna3Foa2lHOXcwQ
https://kubernetes.io/docs/tutorials/_print/ 140/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Now modify your nginx replicas to start an https server using the certificate in the secret, and
the Service, to expose both ports (80 and 443):
service/networking/nginx-secure-app.yaml
apiVersion: v1
kind: Service
metadata:
name: my-nginx
labels:
run: my-nginx
spec:
type: NodePort
ports:
- port: 8080
targetPort: 80
protocol: TCP
name: http
- port: 443
protocol: TCP
name: https
selector:
run: my-nginx
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
run: my-nginx
replicas: 1
template:
metadata:
labels:
run: my-nginx
spec:
volumes:
- name: secret-volume
secret:
secretName: nginxsecret
- name: configmap-volume
configMap:
name: nginxconfigmap
containers:
- name: nginxhttps
image: bprashanth/nginxhttps:1.0
ports:
- containerPort: 443
- containerPort: 80
volumeMounts:
- mountPath: /etc/nginx/ssl
name: secret-volume
- mountPath: /etc/nginx/conf.d
name: configmap-volume
At this point you can reach the nginx server from any node.
Note how we supplied the -k parameter to curl in the last step, this is because we don't
know anything about the pods running nginx at certificate generation time, so we have to tell
curl to ignore the CName mismatch. By creating a Service we linked the CName used in the
certificate with the actual DNS name used by pods during Service lookup. Let's test this from a
pod (the same secret is being reused for simplicity, the pod only needs nginx.crt to access the
Service):
service/networking/curlpod.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: curl-deployment
spec:
selector:
matchLabels:
app: curlpod
replicas: 1
template:
metadata:
labels:
app: curlpod
spec:
volumes:
- name: secret-volume
secret:
secretName: nginxsecret
containers:
- name: curlpod
command:
- sh
- -c
- while true; do sleep 1; done
image: radial/busyboxplus:curl
volumeMounts:
- mountPath: /etc/nginx/ssl
name: secret-volume
https://kubernetes.io/docs/tutorials/_print/ 142/155
6/6/23, 4:10 PM Tutorials | Kubernetes
$ curl https://<EXTERNAL-IP>:<NODE-PORT> -k
...
<h1>Welcome to nginx!</h1>
Let's now recreate the Service to use a cloud load balancer. Change the Type of my-nginx
Service from NodePort to LoadBalancer :
https://kubernetes.io/docs/tutorials/_print/ 143/155
6/6/23, 4:10 PM Tutorials | Kubernetes
curl https://<EXTERNAL-IP> -k
...
<title>Welcome to nginx!</title>
The IP address in the EXTERNAL-IP column is the one that is available on the public internet.
The CLUSTER-IP is only available inside your cluster/private cloud network.
Note that on AWS, type LoadBalancer creates an ELB, which uses a (long) hostname, not an
IP. It's too long to fit in the standard kubectl get svc output, in fact, so you'll need to do
kubectl describe service my-nginx to see it. You'll see something like this:
What's next
Learn more about Using a Service to Access an Application in a Cluster
Learn more about Connecting a Front End to a Back End Using a Service
Learn more about Creating an External Load Balancer
https://kubernetes.io/docs/tutorials/_print/ 144/155
6/6/23, 4:10 PM Tutorials | Kubernetes
NAT
network address translation
Source NAT
replacing the source IP on a packet; in this page, that usually means replacing with the IP
address of a node.
Destination NAT
replacing the destination IP on a packet; in this page, that usually means replacing with the
IP address of a Pod
VIP
a virtual IP address, such as the one assigned to every Service in Kubernetes
kube-proxy
a network daemon that orchestrates Service VIP management on every node
Prerequisites
You need to have a Kubernetes cluster, and the kubectl command-line tool must be
configured to communicate with your cluster. It is recommended to run this tutorial on a
cluster with at least two nodes that are not acting as control plane hosts. If you do not already
have a cluster, you can create one by using minikube or you can use one of these Kubernetes
playgrounds:
Killercoda
Play with Kubernetes
The examples use a small nginx webserver that echoes back the source IP of requests it
receives through an HTTP header. You can create it as follows:
deployment.apps/source-ip-app created
Objectives
Expose a simple application through various types of Services
Understand how each Service type handles source IP NAT
Understand the tradeoffs involved in preserving source IP
https://kubernetes.io/docs/tutorials/_print/ 145/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Get the proxy mode on one of the nodes (kube-proxy listens on port 10249):
iptables
You can test source IP preservation by creating a Service over the source IP app:
service/clusterip exposed
Waiting for pod default/busybox to be running, status is Pending, pod ready: fals
If you don't see a command prompt, try pressing enter.
https://kubernetes.io/docs/tutorials/_print/ 146/155
6/6/23, 4:10 PM Tutorials | Kubernetes
# Replace "10.0.170.92" with the IPv4 address of the Service named "clusterip"
wget -qO - 10.0.170.92
CLIENT VALUES:
client_address=10.244.3.8
command=GET
...
The client_address is always the client pod's IP address, whether the client pod and server
pod are in the same node or in different nodes.
service/nodeport exposed
If you're running on a cloud provider, you may need to open up a firewall-rule for the
nodes:nodeport reported above. Now you can try reaching the Service from outside the
cluster through the node port allocated above.
https://kubernetes.io/docs/tutorials/_print/ 147/155
6/6/23, 4:10 PM Tutorials | Kubernetes
client_address=10.180.1.1
client_address=10.240.0.5
client_address=10.240.0.3
Note that these are not the correct client IPs, they're cluster internal IPs. This is what happens:
Visually:
SNAT
client Node 2 Node 1 Endpoint
SNAT
To avoid this, Kubernetes has a feature to preserve the client source IP. If you set
service.spec.externalTrafficPolicy to the value Local , kube-proxy only proxies proxy
requests to local endpoints, and does not forward traffic to other nodes. This approach
preserves the original source IP address. If there are no local endpoints, packets sent to the
node are dropped, so you can rely on the correct source-ip in any packet processing rules you
might apply a packet that make it through to the endpoint.
service/nodeport patched
client_address=198.51.100.79
Note that you only got one reply, with the right client IP, from the one node on which the
endpoint pod is running.
Visually:
https://kubernetes.io/docs/tutorials/_print/ 148/155
6/6/23, 4:10 PM Tutorials | Kubernetes
client
Node 1 Node 2
endpoint
Packets sent to Services with Type=LoadBalancer are source NAT'd by default, because all
schedulable Kubernetes nodes in the Ready state are eligible for load-balanced traffic. So if
packets arrive at a node without an endpoint, the system proxies it to a node with an
endpoint, replacing the source IP on the packet with the IP of the node (as described in the
previous section).
You can test this by exposing the source-ip-app through a load balancer:
service/loadbalancer exposed
curl 203.0.113.140
CLIENT VALUES:
client_address=10.240.0.5
...
https://kubernetes.io/docs/tutorials/_print/ 149/155
6/6/23, 4:10 PM Tutorials | Kubernetes
Visually:
configuration
Load balancer
Service
Health Health
check of check of
node 1 node 2
returns returns
200 500
Node 1 Node 2
healthCheckNodePort: 32122
https://kubernetes.io/docs/tutorials/_print/ 150/155
6/6/23, 4:10 PM Tutorials | Kubernetes
A controller running on the control plane is responsible for allocating the cloud load balancer.
The same controller also allocates HTTP health checks pointing to this port/path on each
node. Wait about 10 seconds for the 2 nodes without endpoints to fail health checks, then use
curl to query the IPv4 address of the load balancer:
curl 203.0.113.140
CLIENT VALUES:
client_address=198.51.100.79
...
Cross-platform support
Only some cloud providers offer support for source IP preservation through Services with
Type=LoadBalancer . The cloud provider you're running on might fulfill the request for a
loadbalancer in a few different ways:
1. With a proxy that terminates the client connection and opens a new connection to your
nodes/endpoints. In such cases the source IP will always be that of the cloud LB, not that
of the client.
2. With a packet forwarder, such that requests from the client sent to the loadbalancer VIP
end up at the node with the source IP of the client, not an intermediate proxy.
Load balancers in the first category must use an agreed upon protocol between the
loadbalancer and backend to communicate the true client IP such as the HTTP Forwarded or
X-FORWARDED-FOR headers, or the proxy protocol. Load balancers in the second category
can leverage the feature described above by creating an HTTP health check pointing at the
port stored in the service.spec.healthCheckNodePort field on the Service.
Cleaning up
Delete the Services:
What's next
Learn more about connecting applications via services
Read how to Create an External Load Balancer
https://kubernetes.io/docs/tutorials/_print/ 151/155
6/6/23, 4:10 PM Tutorials | Kubernetes
This tutorial explains the flow of Pod termination in connection with the corresponding
endpoint state and removal by using a simple nginx web server to demonstrate the concept.
Let's say you have a Deployment containing of a single nginx replica (just for demonstration
purposes) and a Service:
service/pod-with-graceful-termination.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
terminationGracePeriodSeconds: 120 # extra long grace period
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
lifecycle:
preStop:
exec:
# Real life termination may take any time up to terminationGracePer
# In this example - just hang around for at least the duration of t
# at 120 seconds container will be forcibly terminated.
# Note, all this time nginx will keep processing requests.
command: [
"/bin/sh", "-c", "sleep 180"
]
https://kubernetes.io/docs/tutorials/_print/ 152/155
6/6/23, 4:10 PM Tutorials | Kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
terminationGracePeriodSeconds: 120 # extra long grace period
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
lifecycle:
preStop:
exec:
# Real life termination may take any time up to terminationGracePer
# In this example - just hang around for at least the duration of t
# at 120 seconds container will be forcibly terminated.
# Note, all this time nginx will keep processing requests.
command: [
"/bin/sh", "-c", "sleep 180"
]
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
Once the Pod and Service are running, you can get the name of any associated
EndpointSlices:
You can see its status, and validate that there is one endpoint registered:
https://kubernetes.io/docs/tutorials/_print/ 153/155
6/6/23, 4:10 PM Tutorials | Kubernetes
{
"addressType": "IPv4",
"apiVersion": "discovery.k8s.io/v1",
"endpoints": [
{
"addresses": [
"10.12.1.201"
],
"conditions": {
"ready": true,
"serving": true,
"terminating": false
Now let's terminate the Pod and validate that the Pod is being terminated respecting the
graceful termination period configuration:
All pods:
While the new endpoint is being created for the new Pod, the old endpoint is still around in
the terminating state:
https://kubernetes.io/docs/tutorials/_print/ 154/155
6/6/23, 4:10 PM Tutorials | Kubernetes
{
"addressType": "IPv4",
"apiVersion": "discovery.k8s.io/v1",
"endpoints": [
{
"addresses": [
"10.12.1.201"
],
"conditions": {
"ready": false,
"serving": true,
"terminating": true
},
"nodeName": "gke-main-default-pool-dca1511c-d17b",
"targetRef": {
"kind": "Pod",
"name": "nginx-deployment-7768647bf9-b4b9s",
"namespace": "default",
"uid": "66fa831c-7eb2-407f-bd2c-f96dfe841478"
},
"zone": "us-central1-c"
},
{
"addresses": [
"10.12.1.202"
],
"conditions": {
"ready": true,
"serving": true,
"terminating": false
},
"nodeName": "gke-main-default-pool-dca1511c-d17b",
"targetRef": {
"kind": "Pod",
"name": "nginx-deployment-7768647bf9-rkxlw",
"namespace": "default",
"uid": "722b1cbe-dcd7-4ed4-8928-4a4d0e2bbe35"
},
"zone": "us-central1-c"
This allows applications to communicate their state during termination and clients (such as
load balancers) to implement a connections draining functionality. These clients may detect
terminating endpoints and implement a special logic for them.
In Kubernetes, endpoints that are terminating always have their ready status set as as
false . This needs to happen for backward compatibility, so existing load balancers will not
use it for regular traffic. If traffic draining on terminating pod is needed, the actual readiness
can be checked as a condition serving .
What's next
Learn how to Connect Applications with Services
Learn more about Using a Service to Access an Application in a Cluster
Learn more about Connecting a Front End to a Back End Using a Service
Learn more about Creating an External Load Balancer
https://kubernetes.io/docs/tutorials/_print/ 155/155