NestJS course ยท Module 12: Containers and CI/CD

Kubernetes - Managing the Provinces of the Empire

4 min read ยท
In this lesson8

Salve, legionary! So far we have learned how to build legionary camps (Docker containers) and connect them with roads (Docker Compose). But the Roman Empire managed dozens of provinces simultaneously. It needed a system that automatically deployed legions, replaced fallen soldiers, and scaled forces in response to threats. In the world of applications, this role is fulfilled by Kubernetes (K8s).

What is Kubernetes?

Kubernetes is a platform for container orchestration - it automatically manages deploying, scaling, and operating containers across a cluster of servers. The name comes from the Greek word for "helmsman" - Kubernetes is the helmsman of our container legion.

// Analogy: Roman Empire vs Kubernetes
interface ImperiumKubernetes {
  imperator: 'Control Plane';       // Command center
  provinces: 'Nodes (servers)';     // Machines in the cluster
  legions: 'Pods';                  // Deployment units
  edicts: 'Deployments';            // State declarations
  roads: 'Services';                // Network communication
  gates: 'Ingress';                 // External entry
}

const k8sConcepts = {
  pod: 'Smallest unit - one or more containers',
  deployment: 'Manages pod replicas (how many legions)',
  service: 'Stable network address for pods',
  ingress: 'Entry gateway from outside (HTTP/HTTPS)',
  configMap: 'Configuration without secrets (public edicts)',
  secret: 'Encrypted sensitive data (secret dispatches)',
  namespace: 'Resource isolation (provinces)',
};

Pod - The Smallest Unit

A Pod is the smallest deployment unit in Kubernetes. It contains one or more containers that share networking and storage:

# pod-definition.yaml
apiVersion: v1
kind: Pod
metadata:
  name: roman-api-pod
  labels:
    app: roman-imperium
    tier: backend
spec:
  containers:
    - name: api
      image: roman-imperium-api:1.0
      ports:
        - containerPort: 4000
      env:
        - name: NODE_ENV
          value: "production"

Deployment - The Deployment Edict

A Deployment is a declaration of what our desired state should look like. Kubernetes itself ensures that reality matches the declaration:

# deployment.yaml - NestJS API Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: roman-api
  labels:
    app: roman-imperium
spec:
  replicas: 3                  # 3 legions (instances)
  selector:
    matchLabels:
      app: roman-imperium
  template:
    metadata:
      labels:
        app: roman-imperium
    spec:
      containers:
        - name: api
          image: roman-imperium-api:1.0
          ports:
            - containerPort: 4000
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "500m"
          livenessProbe:         # Is the legion alive?
            httpGet:
              path: /health
              port: 4000
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:        # Is the legion ready for battle?
            httpGet:
              path: /health
              port: 4000
            initialDelaySeconds: 5
            periodSeconds: 5

Service - Roads of the Empire

A Service provides a stable network address for pods, even when pods are being replaced:

# service.yaml - Road to the API
apiVersion: v1
kind: Service
metadata:
  name: roman-api-service
spec:
  selector:
    app: roman-imperium
  ports:
    - protocol: TCP
      port: 80            # External port
      targetPort: 4000    # Container port
  type: ClusterIP          # Available only within the cluster

Ingress - Gateway of the Empire

Ingress routes HTTP/HTTPS traffic from outside to the appropriate services:

# ingress.yaml - Gateway of the Empire
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: roman-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - host: api.roman-imperium.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: roman-api-service
                port:
                  number: 80

ConfigMap and Secret - Edicts and Secret Dispatches

# configmap.yaml - Public configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: roman-config
data:
  NODE_ENV: "production"
  PORT: "4000"
  LOG_LEVEL: "warn"
---
# secret.yaml - Encrypted secrets
apiVersion: v1
kind: Secret
metadata:
  name: roman-secrets
type: Opaque
data:
  DATABASE: bW9uZ29kYjovL2ltcGVyYXRvcjpyb21hQG1vbmdvZGI6MjcwMTcvaW1wZXJpdW0=
  JWT_SECRET: c3VwZXItc2VjcmV0LWtleS1jaGFuZ2UtbWU=

HPA - Autoscaling Legions

Horizontal Pod Autoscaler automatically scales the number of pods in response to load:

# hpa.yaml - Autoscaling
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: roman-api-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: roman-api
  minReplicas: 2          # Minimum 2 legions
  maxReplicas: 10         # Maximum 10 legions
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70    # Scale at 70% CPU

Basic kubectl Commands

# Deploy resources
kubectl apply -f deployment.yaml

# Check pods
kubectl get pods

# Check deployments
kubectl get deployments

# Pod logs
kubectl logs roman-api-xxxxx

# Scale manually
kubectl scale deployment roman-api --replicas=5

# Check HPA status
kubectl get hpa

Kubernetes is the province management system of our Empire - it automatically deploys legions, replaces the fallen, and scales forces in response to threats. It is the foundation of modern production infrastructure.

Code for this lesson: src/kubernetes-concepts.ts
// Kubernetes - Managing Imperium Provinces
console.log("=== KUBERNETES (K8s) ===\n");

interface K8sResource {
  name: string;
  kind: string;
  romanAnalogy: string;
  description: string;
}

const resources: K8sResource[] = [
  {
    name: 'Pod',
    kind: 'v1/Pod',
    romanAnalogy: 'Single legion',
    description: 'Smallest unit - one or more containers',
  },
  {
    name: 'Deployment',
    kind: 'apps/v1/Deployment',
    romanAnalogy: 'Deployment edict',
    description: 'Manages pod replicas',
  },
  {
    name: 'Service',
    kind: 'v1/Service',
    romanAnalogy: 'Roman roads',
    description: 'Permanent network address for pods',
  },
  {
    name: 'Ingress',
    kind: 'networking.k8s.io/v1/Ingress',
    romanAnalogy: 'Imperium Gate',
    description: 'HTTP/HTTPS entry point from outside',
  },
  {
    name: 'ConfigMap',
    kind: 'v1/ConfigMap',
    romanAnalogy: 'Public edicts',
    description: 'Configuration without secrets',
  },
  {
    name: 'Secret',
    kind: 'v1/Secret',
    romanAnalogy: 'Secret dispatches',
    description: 'Encrypted sensitive data',
  },
  {
    name: 'HPA',
    kind: 'autoscaling/v2/HPA',
    romanAnalogy: 'Autoscaling legions',
    description: 'Automatic scaling under load',
  },
];

console.log("Kubernetes resources:\n");
resources.forEach((r, i) => {
  console.log(`${i + 1}. ${r.name} (${r.kind})`);
  console.log(`   Analogy: ${r.romanAnalogy}`);
  console.log(`   Description: ${r.description}\n`);
});

// kubectl commands
console.log("=== kubectl COMMANDS ===\n");
const commands = [
  'kubectl apply -f deployment.yaml',
  'kubectl get pods',
  'kubectl get services',
  'kubectl logs <pod-name>',
  'kubectl scale deployment roman-api --replicas=5',
  'kubectl get hpa',
];

commands.forEach(cmd => console.log(`  $ ${cmd}`));

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is Kubernetes (K8s)?

  2. 2. What is a Pod in Kubernetes?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the definitions of K8s resources: Pod, Deployment, Service, Ingress, ConfigMap, Secret, HPA

  • Vertical ordering

    Arrange the steps of deploying a NestJS application in Kubernetes:

  1. QuestionWhat is Kubernetes
  2. QuestionPod in Kubernetes
  3. Coding taskKubernetes resources in practice
  4. QuestionDeployment in Kubernetes
  5. Put in orderDeploying an application in Kubernetes

Useful articles