Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md:
category: Container Orchestration
estReadingMinutes: 10
exercises:
-
name: Stateful Sets
description: Create a simple StatefulSet in Kubernetes, understand the lifecycle of StatefulSets.
estMinutes: 120
technologies:
- Kubernetes
- StatefulSets
---

# 9.2.1 Stateful Sets

StatefulSets are a type of workload controller in Kubernetes specifically designed to manage stateful applications—applications that require persistent storage and stable identities for their Pods. Unlike Deployments, where Pods are interchangeable and ephemeral, StatefulSets provide “sticky” identities and guarantees that each Pod maintains a unique, stable network identity and persistent storage across rescheduling, scaling, and updates.

This stickiness is crucial for stateful workloads such as databases, message queues, and distributed systems, where each instance must maintain its state consistently and be reachable by other Pods in a predictable manner.

For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/).

## Exercise 1 - Stateful Sets

1. Destroy and recreate a new cluster.
`unset KUBECONFIG; k3d cluster delete <cluster-name>; k3d cluster create <cluster-name>`.

2. Copy the contents of `examples/ch9/volumes/random-num-pod.yaml` into a new file called `examples/ch9/statefulsets/random-num-statefulset.yaml` and modify it to use a `StatefulSet` resource instead of a `Pod` resource. Set the number of replicas to 3.

> To prevent the container from dying and restarting, add a sleep command to the container:
`args: ["shuf -i 0-100 -n 1 >> /opt/number.out; sleep 10000"]`.

?> [VolumeClaimTemplates](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#volume-claim-templates) give each statefulset replica an automatically managed, per-pod persistent volume that sticks to the Pod’s ordinal, avoids manual PVC creation, and prevents unsafe volume sharing.

3. Apply the `StatefulSet` to the cluster.

4. Exec into each pod and view the contents of `/opt/number.out` or use the command:
```shell
kubectl get pods -l app=<statefulset-label> -o name | xargs -I {} sh -c 'echo {}; kubectl exec {} -- cat /opt/number.out'
```

5. Delete one of the pods from the `StatefulSet`, run the command again and observe the output.

?> Notice that deleting the pod may take a while to actually terminate. Take note on why you think this is the case.

## Exercise 2 - More Stateful Sets

Navigate to `examples/ch9/statefulsets/counterapp/`, there is a Dockerfile and a directory `src` which contains a simple web application that displays a counter and the name of the pod it's running on.

Check failure on line 48 in docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md

View workflow job for this annotation

GitHub Actions / lint

Trailing spaces

docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md:48:202 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.38.0/doc/md009.md

1. Destroy and recreate a new cluster.
`unset KUBECONFIG; k3d cluster delete <cluster-name>; k3d cluster create <cluster-name>`.

Check failure on line 51 in docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md

View workflow job for this annotation

GitHub Actions / lint

Trailing spaces

docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md:51:90 MD009/no-trailing-spaces Trailing spaces [Expected: 0 or 2; Actual: 1] https://github.com/DavidAnson/markdownlint/blob/v0.38.0/doc/md009.md

2. Create a `StatefulSet` for the counterapp.

3. Create a `Service` for the `StatefulSet`.

?> `StatefulSets` are a bit unique and require a `Headless Service` to function properly. This is because `StatefulSets` require stable network identities for their pods, and a `Headless Service` provides this by not load balancing traffic across pods, but instead routing traffic to specific pods based on their stable network identity. For more information: https://kubernetes.io/docs/concepts/services-networking/service/#headless-services

Check failure on line 57 in docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md

View workflow job for this annotation

GitHub Actions / lint

Bare URL used

docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md:57:361 MD034/no-bare-urls Bare URL used [Context: "https://kubernetes.io/docs/con..."] https://github.com/DavidAnson/markdownlint/blob/v0.38.0/doc/md034.md

4. Apply both the `StatefulSet` and `Service` to the cluster.

5. Port forward each pod, delete one of the pods and observe each instance of the counter app in your browser.

?> Notice that deleting the pod may take a while to actually terminate. Take note on why you think this is the case.

## Deliverables

- Look into other workload controllers (Deployments, ReplicaSets, DaemonSets, etc.), what are the differences between them? Why might you use one over the other?
- What are some downsides to using `StatefulSets`?
1 change: 1 addition & 0 deletions docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@
- [9.1.4 - Cluster Management](9-kubernetes-container-orchestration/9.1.4-cluster-management.md)
- [9.1.5 - Kubectl Settings and Usage](9-kubernetes-container-orchestration/9.1.5-kubectl-settings-and-usage.md)
- [9.2 - Volumes](9-kubernetes-container-orchestration/9.2-volumes.md)
- [9.2.1 - Stateful Sets](9-kubernetes-container-orchestration/9.2.1-stateful-sets.md)
- [9.3 - Probes](9-kubernetes-container-orchestration/9.3-probes.md)
- [9.4 - RBAC](9-kubernetes-container-orchestration/9.4-rbac.md)
- [9.5 - HPAs](9-kubernetes-container-orchestration/9.5-hpas.md)
Expand Down
18 changes: 18 additions & 0 deletions examples/ch9/statefulsets/counterapp/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./

RUN npm install --omit=dev

COPY server.js ./
COPY src/ ./src/

RUN mkdir -p /data && chown -R node:node /data

USER node

EXPOSE 3000

CMD ["npm", "start"]
13 changes: 13 additions & 0 deletions examples/ch9/statefulsets/counterapp/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "counterapp",
"version": "1.0.0",
"private": true,
"description": "StatefulSet demo counter app with persistent per-pod state",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
64 changes: 64 additions & 0 deletions examples/ch9/statefulsets/counterapp/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');

const app = express();
const PORT = process.env.PORT || 3000;
const DATA_DIR = process.env.DATA_DIR || '/data';
const DATA_FILE = path.join(DATA_DIR, 'counter.json');
const POD_NAME = process.env.POD_NAME || os.hostname();

app.use(express.json());
app.use(express.static(path.join(__dirname, 'src')));
app.get('/', (_req, res) => {
res.sendFile(path.join(__dirname, 'src', 'index.html'));
});

function readCounter() {
try {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
if (!fs.existsSync(DATA_FILE)) {
fs.writeFileSync(DATA_FILE, JSON.stringify({ count: 0 }), 'utf8');
return 0;
}
const raw = fs.readFileSync(DATA_FILE, 'utf8');
const obj = JSON.parse(raw);
return typeof obj.count === 'number' ? obj.count : 0;
} catch (e) {
return 0;
}
}

function writeCounter(value) {
try {
fs.writeFileSync(DATA_FILE, JSON.stringify({ count: value }), 'utf8');
return true;
} catch (e) {
return false;
}
}

app.get('/healthz', (_req, res) => {
res.status(200).send('ok');
});

app.get('/api/state', (_req, res) => {
const count = readCounter();
res.json({ count, podName: POD_NAME });
});

app.post('/api/increment', (_req, res) => {
let count = readCounter();
count += 1;
if (!writeCounter(count)) {
return res.status(500).json({ error: 'failed_to_persist' });
}
res.json({ count, podName: POD_NAME });
});

app.listen(PORT, () => {
console.log(`server listening on ${PORT} as ${POD_NAME}`);
});
19 changes: 19 additions & 0 deletions examples/ch9/statefulsets/counterapp/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
async function fetchState() {
const res = await fetch('/api/state');
if (!res.ok) return;
const data = await res.json();
document.getElementById('count').textContent = data.count;
document.getElementById('podName').textContent = `pod: ${data.podName}`;
}

async function increment() {
const res = await fetch('/api/increment', { method: 'POST' });
if (!res.ok) return;
const data = await res.json();
document.getElementById('count').textContent = data.count;
}

window.addEventListener('DOMContentLoaded', () => {
document.getElementById('incrementBtn').addEventListener('click', increment);
fetchState();
});
26 changes: 26 additions & 0 deletions examples/ch9/statefulsets/counterapp/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Counter</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="container">
<div class="card">
<div class="header">
<h1>Counter</h1>
</div>
<div class="status">
<div class="pill" id="podName">pod: …</div>
</div>
<div class="counter">
<div class="count" id="count">0</div>
<button id="incrementBtn" class="btn">Increment</button>
</div>
</div>
</div>
<script src="/app.js"></script>
</body>
</html>
35 changes: 35 additions & 0 deletions examples/ch9/statefulsets/counterapp/src/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
* { box-sizing: border-box; }
:root {
--bg: #0f1419;
--card: #1a1f2e;
--text: #e5e7eb;
--muted: #9ca3af;
--liatrio-green: #24AE1D;
--liatrio-green-light: #2ec725;
--liatrio-green-selection: #c3e788;
--pill: #1f2937;
}
html, body { height: 100%; }
body {
margin: 0;
font-family: 'Open Sans', ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica Neue, Arial, sans-serif;
background: radial-gradient(1000px 600px at 20% 10%, rgba(36,174,29,0.12), transparent),
radial-gradient(800px 500px at 80% 30%, rgba(36,174,29,0.08), transparent),
var(--bg);
color: var(--text);
}
.container { min-height: 100%; display: grid; place-items: center; padding: 24px; }
.card {
width: 100%; max-width: 480px; background: var(--card); border: 1px solid rgba(36,174,29,0.15);
border-radius: 16px; padding: 28px; box-shadow: 0 10px 30px rgba(0,0,0,0.35);
}
.header { text-align: center; margin-bottom: 18px; }
.header h1 { margin: 0 0 4px; font-size: 26px; letter-spacing: 0.2px; color: var(--liatrio-green-light); }
.subtitle { margin: 0; color: var(--muted); font-size: 14px; }
.status { display: flex; justify-content: center; margin: 6px 0 16px; }
.pill { background: var(--pill); color: var(--liatrio-green-selection); border: 1px solid rgba(36,174,29,0.2); padding: 6px 10px; border-radius: 999px; font-size: 12px; font-weight: 500; }
.counter { display: grid; gap: 16px; justify-items: center; padding: 8px 0 6px; }
.count { font-size: 64px; font-weight: 700; letter-spacing: 1px; color: var(--liatrio-green); }
.btn { background: var(--liatrio-green); color: white; border: none; padding: 12px 16px; border-radius: 10px; font-weight: 600; cursor: pointer; font-size: 16px; transition: background 0.2s ease; }
.btn:hover { background: var(--liatrio-green-light); }
footer { margin-top: 16px; text-align: center; color: var(--muted); font-size: 12px; }
Loading