Skip to content

Commit 7d1b026

Browse files
committed
Updated the StatefulSet second exercise
1 parent 98fae5e commit 7d1b026

File tree

8 files changed

+244
-0
lines changed

8 files changed

+244
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
---
2+
docs/9-kubernetes-container-orchestration/9.2.1-stateful-sets.md:
3+
category: Container Orchestration
4+
estReadingMinutes: 10
5+
exercises:
6+
-
7+
name: Stateful Sets
8+
description: Create a simple StatefulSet in Kubernetes, understand the lifecycle of StatefulSets.
9+
estMinutes: 120
10+
technologies:
11+
- Kubernetes
12+
- StatefulSets
13+
---
14+
15+
# 9.2.1 Stateful Sets
16+
17+
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.
18+
19+
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.
20+
21+
For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/).
22+
23+
## Exercise 1 - Stateful Sets
24+
25+
1. Destroy and recreate a new cluster.
26+
`unset KUBECONFIG; k3d cluster delete <cluster-name>; k3d cluster create <cluster-name>`.
27+
28+
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.
29+
30+
> To prevent the container from dying and restarting, add a sleep command to the container:
31+
`args: ["shuf -i 0-100 -n 1 >> /opt/number.out; sleep 10000"]`.
32+
33+
?> [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.
34+
35+
3. Apply the `StatefulSet` to the cluster.
36+
37+
4. Exec into each pod and view the contents of `/opt/number.out` or use the command:
38+
```shell
39+
kubectl get pods -l app=<statefulset-label> -o name | xargs -I {} sh -c 'echo {}; kubectl exec {} -- cat /opt/number.out'
40+
```
41+
42+
5. Delete one of the pods from the `StatefulSet`, run the command again and observe the output.
43+
44+
?> Notice that deleting the pod may take a while to actually terminate. Take note on why you think this is the case.
45+
46+
## Exercise 2 - More Stateful Sets
47+
48+
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.
49+
50+
1. Destroy and recreate a new cluster.
51+
`unset KUBECONFIG; k3d cluster delete <cluster-name>; k3d cluster create <cluster-name>`.
52+
53+
2. Create a `StatefulSet` for the counterapp.
54+
55+
3. Create a `Service` for the `StatefulSet`.
56+
57+
?> `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
58+
59+
4. Apply both the `StatefulSet` and `Service` to the cluster.
60+
61+
5. Port forward each pod, delete one of the pods and observe each instance of the counter app in your browser.
62+
63+
?> Notice that deleting the pod may take a while to actually terminate. Take note on why you think this is the case.
64+
65+
## Deliverables
66+
67+
- Look into other workload controllers (Deployments, ReplicaSets, DaemonSets, etc.), what are the differences between them? Why might you use one over the other?
68+
- What are some downsides to using `StatefulSets`?

docs/_sidebar.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@
140140
- [9.1.4 - Cluster Management](9-kubernetes-container-orchestration/9.1.4-cluster-management.md)
141141
- [9.1.5 - Kubectl Settings and Usage](9-kubernetes-container-orchestration/9.1.5-kubectl-settings-and-usage.md)
142142
- [9.2 - Volumes](9-kubernetes-container-orchestration/9.2-volumes.md)
143+
- [9.2.1 - Stateful Sets](9-kubernetes-container-orchestration/9.2.1-stateful-sets.md)
143144
- [9.3 - Probes](9-kubernetes-container-orchestration/9.3-probes.md)
144145
- [9.4 - RBAC](9-kubernetes-container-orchestration/9.4-rbac.md)
145146
- [9.5 - HPAs](9-kubernetes-container-orchestration/9.5-hpas.md)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
FROM node:18-alpine
2+
3+
WORKDIR /app
4+
5+
COPY package*.json ./
6+
7+
RUN npm install --omit=dev
8+
9+
COPY server.js ./
10+
COPY src/ ./src/
11+
12+
RUN mkdir -p /data && chown -R node:node /data
13+
14+
USER node
15+
16+
EXPOSE 3000
17+
18+
CMD ["npm", "start"]
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "counterapp",
3+
"version": "1.0.0",
4+
"private": true,
5+
"description": "StatefulSet demo counter app with persistent per-pod state",
6+
"main": "server.js",
7+
"scripts": {
8+
"start": "node server.js"
9+
},
10+
"dependencies": {
11+
"express": "^4.18.2"
12+
}
13+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
const express = require('express');
2+
const fs = require('fs');
3+
const path = require('path');
4+
const os = require('os');
5+
6+
const app = express();
7+
const PORT = process.env.PORT || 3000;
8+
const DATA_DIR = process.env.DATA_DIR || '/data';
9+
const DATA_FILE = path.join(DATA_DIR, 'counter.json');
10+
const POD_NAME = process.env.POD_NAME || os.hostname();
11+
12+
app.use(express.json());
13+
app.use(express.static(path.join(__dirname, 'src')));
14+
app.get('/', (_req, res) => {
15+
res.sendFile(path.join(__dirname, 'src', 'index.html'));
16+
});
17+
18+
function readCounter() {
19+
try {
20+
if (!fs.existsSync(DATA_DIR)) {
21+
fs.mkdirSync(DATA_DIR, { recursive: true });
22+
}
23+
if (!fs.existsSync(DATA_FILE)) {
24+
fs.writeFileSync(DATA_FILE, JSON.stringify({ count: 0 }), 'utf8');
25+
return 0;
26+
}
27+
const raw = fs.readFileSync(DATA_FILE, 'utf8');
28+
const obj = JSON.parse(raw);
29+
return typeof obj.count === 'number' ? obj.count : 0;
30+
} catch (e) {
31+
return 0;
32+
}
33+
}
34+
35+
function writeCounter(value) {
36+
try {
37+
fs.writeFileSync(DATA_FILE, JSON.stringify({ count: value }), 'utf8');
38+
return true;
39+
} catch (e) {
40+
return false;
41+
}
42+
}
43+
44+
app.get('/healthz', (_req, res) => {
45+
res.status(200).send('ok');
46+
});
47+
48+
app.get('/api/state', (_req, res) => {
49+
const count = readCounter();
50+
res.json({ count, podName: POD_NAME });
51+
});
52+
53+
app.post('/api/increment', (_req, res) => {
54+
let count = readCounter();
55+
count += 1;
56+
if (!writeCounter(count)) {
57+
return res.status(500).json({ error: 'failed_to_persist' });
58+
}
59+
res.json({ count, podName: POD_NAME });
60+
});
61+
62+
app.listen(PORT, () => {
63+
console.log(`server listening on ${PORT} as ${POD_NAME}`);
64+
});
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
async function fetchState() {
2+
const res = await fetch('/api/state');
3+
if (!res.ok) return;
4+
const data = await res.json();
5+
document.getElementById('count').textContent = data.count;
6+
document.getElementById('podName').textContent = `pod: ${data.podName}`;
7+
}
8+
9+
async function increment() {
10+
const res = await fetch('/api/increment', { method: 'POST' });
11+
if (!res.ok) return;
12+
const data = await res.json();
13+
document.getElementById('count').textContent = data.count;
14+
}
15+
16+
window.addEventListener('DOMContentLoaded', () => {
17+
document.getElementById('incrementBtn').addEventListener('click', increment);
18+
fetchState();
19+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1" />
6+
<title>Counter</title>
7+
<link rel="stylesheet" href="/style.css" />
8+
</head>
9+
<body>
10+
<div class="container">
11+
<div class="card">
12+
<div class="header">
13+
<h1>Counter</h1>
14+
</div>
15+
<div class="status">
16+
<div class="pill" id="podName">pod: …</div>
17+
</div>
18+
<div class="counter">
19+
<div class="count" id="count">0</div>
20+
<button id="incrementBtn" class="btn">Increment</button>
21+
</div>
22+
</div>
23+
</div>
24+
<script src="/app.js"></script>
25+
</body>
26+
</html>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
* { box-sizing: border-box; }
2+
:root {
3+
--bg: #0f1419;
4+
--card: #1a1f2e;
5+
--text: #e5e7eb;
6+
--muted: #9ca3af;
7+
--liatrio-green: #24AE1D;
8+
--liatrio-green-light: #2ec725;
9+
--liatrio-green-selection: #c3e788;
10+
--pill: #1f2937;
11+
}
12+
html, body { height: 100%; }
13+
body {
14+
margin: 0;
15+
font-family: 'Open Sans', ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica Neue, Arial, sans-serif;
16+
background: radial-gradient(1000px 600px at 20% 10%, rgba(36,174,29,0.12), transparent),
17+
radial-gradient(800px 500px at 80% 30%, rgba(36,174,29,0.08), transparent),
18+
var(--bg);
19+
color: var(--text);
20+
}
21+
.container { min-height: 100%; display: grid; place-items: center; padding: 24px; }
22+
.card {
23+
width: 100%; max-width: 480px; background: var(--card); border: 1px solid rgba(36,174,29,0.15);
24+
border-radius: 16px; padding: 28px; box-shadow: 0 10px 30px rgba(0,0,0,0.35);
25+
}
26+
.header { text-align: center; margin-bottom: 18px; }
27+
.header h1 { margin: 0 0 4px; font-size: 26px; letter-spacing: 0.2px; color: var(--liatrio-green-light); }
28+
.subtitle { margin: 0; color: var(--muted); font-size: 14px; }
29+
.status { display: flex; justify-content: center; margin: 6px 0 16px; }
30+
.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; }
31+
.counter { display: grid; gap: 16px; justify-items: center; padding: 8px 0 6px; }
32+
.count { font-size: 64px; font-weight: 700; letter-spacing: 1px; color: var(--liatrio-green); }
33+
.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; }
34+
.btn:hover { background: var(--liatrio-green-light); }
35+
footer { margin-top: 16px; text-align: center; color: var(--muted); font-size: 12px; }

0 commit comments

Comments
 (0)