-
Notifications
You must be signed in to change notification settings - Fork 51
Updated the StatefulSet second exercise #781
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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
|
||
|
|
||
| 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
|
||
|
|
||
| 2. Create a `StatefulSet` for the counterapp. | ||
jburns24 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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
|
||
|
|
||
| 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`? | ||
| 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"] |
| 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" | ||
| } | ||
| } |
| 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; | ||
| } | ||
jburns24 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| 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}`); | ||
| }); | ||
| 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(); | ||
| }); |
| 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> |
| 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; } |
Uh oh!
There was an error while loading. Please reload this page.