Kubernetes — The course

Guide 03 / 3

Kubernetes configuration · YAML

Understand apiVersion, kind, metadata, spec and the main fields of Deployments, Services, ConfigMaps and PVCs.

Expected outcome :

Write and review a consistent set of manifests and anticipate its runtime conditions.

Reading
0%

01 · Anatomy of a manifest

A manifest describes a Kubernetes object. The fields are nested: their location matters as much as their name.

apiVersion

The version of the API group the resource belongs to. A Deployment uses apps/v1, a Pod or Service uses v1.

apiVersion: apps/v1
Remember :

This field does not mean “installed Kubernetes version”.

kind

The type of object to create: Deployment, Pod, Service, ConfigMap, Job, etc.

kind: Deployment

metadata.name

The object's unique name within its naming scope.

metadata:
  name: web

metadata.namespace

The target namespace when the resource is namespaced.

metadata:
  namespace: dev
Remember :

The namespace must already exist or be declared elsewhere.

metadata.labels

Labels attached to the object, handy for filtering and selection.

metadata:
  labels:
    app: web

metadata.annotations

Additional metadata readable by tools or controllers.

metadata:
  annotations:
    exemple.fr/owner: formation

spec

The block describing the desired state. Its structure depends on the object type (kind).

spec:
  replicas: 2
Remember :

A Service and a Deployment do not have the same spec fields.

status

A block filled in by the system describing the observed situation. It is normally read, not supplied by the author.

status.readyReplicas: 2
Remember :

Do not include status in source manifests.

02 · Describing a Pod's containers

For a durable application, these fields are often placed under spec.template.spec in a Deployment.

spec.containers[].name

The container's distinctive name inside the Pod; kubectl can use it to target logs.

containers:
  - name: nginx

spec.containers[].image

The container image to download and run, with a name and a tag or digest.

image: nginx:stable
Remember :

Do not rely on latest for reproducible deployments.

spec.containers[].ports[].containerPort

An indication of the port on which the application in the container is meant to listen.

ports:
  - containerPort: 80
Remember :

Declaring containerPort does not publish the Pod to the outside.

spec.containers[].command / args

command replaces the image's ENTRYPOINT; args replaces its CMD, depending on the image's configuration.

command: ["sh", "-c"]
args: ["echo bonjour; sleep 3600"]
Remember :

A badly defined command can cause CrashLoopBackOff.

spec.containers[].env

Declares environment variables supplied to the process.

env:
  - name: MODE
    value: "demo"

spec.containers[].envFrom

Imports several keys from a ConfigMap or Secret as environment variables.

envFrom:
  - configMapRef:
      name: web-config
Remember :

Environment changes are not re-injected into a process that is already running.

spec.containers[].resources.requests

The amount of CPU and memory requested for scheduling; the scheduler uses these values to choose the node.

requests:
  cpu: 100m
  memory: 64Mi

spec.containers[].resources.limits

The resource ceiling enforced at run time; CPU can be throttled, memory can cause an OOM kill.

limits:
  cpu: 500m
  memory: 256Mi

spec.containers[].readinessProbe

A periodic test that indicates whether the Pod can receive traffic via Services.

readinessProbe:
  httpGet: {path: /, port: 80}
  periodSeconds: 5

spec.containers[].livenessProbe

A test indicating whether the container should be restarted because it no longer responds correctly.

livenessProbe:
  httpGet: {path: /, port: 80}
  initialDelaySeconds: 10

spec.containers[].startupProbe

An optional test that lets a slow application finish starting before the usual probes.

startupProbe:
  httpGet: {path: /, port: 80}
  failureThreshold: 30
  periodSeconds: 2

spec.imagePullSecrets

References a Secret holding the credentials for accessing a private registry, when needed.

imagePullSecrets:
  - name: registry-creds

03 · Deployment and other controllers

A Deployment describes not only an image, but also how to run it and update it several times.

Deployment.spec.replicas

The number of Pods wanted for the application, managed indirectly through a ReplicaSet.

spec:
  replicas: 3

Deployment.spec.selector.matchLabels

Labels that let the controller recognise which Pods belong to this Deployment.

selector:
  matchLabels:
    app: web
Remember :

Must match the template's labels; the selector is immutable in many cases.

Deployment.spec.template

The Pod template Kubernetes uses to create the replicas. Contains the Pod's metadata and spec.

template:
  metadata:
    labels: {app: web}
  spec:
    containers: ...

Deployment.spec.strategy

The update strategy. RollingUpdate gradually replaces the Pods, Recreate renews them all together.

strategy:
  type: RollingUpdate

maxSurge / maxUnavailable

With RollingUpdate, maxSurge allows extra Pods; maxUnavailable bounds the number that can be missing during the update.

rollingUpdate:
  maxSurge: 1
  maxUnavailable: 0

Pod.spec.restartPolicy

Indicates when to restart a Pod's containers. For a Deployment's Pod, Always is imposed.

restartPolicy: Always
Remember :

Job also allows OnFailure or Never.

Job.spec.template / backoffLimit

The Job uses a Pod template and can limit the number of attempts on failure.

backoffLimit: 3

CronJob.spec.schedule

A five-field cron expression used to create Jobs on a calendar.

schedule: "0 2 * * *"
Remember :

Check the time zone via timeZone if needed.

04 · Services, ports and HTTP entry

The Service chooses Pods using labels and separates the stable address from the ephemeral instances.

Service.spec.type

Defines the Service's exposure: ClusterIP by default, NodePort, LoadBalancer or ExternalName.

type: ClusterIP

Service.spec.selector

Labels of the Pods to route traffic to.

selector:
  app: web
Remember :

Selects no Pod if the labels differ.

Service.spec.ports[].port

The Service port that clients call, for example 80.

ports:
  - port: 80

Service.spec.ports[].targetPort

The container port or named port to which the Service redirects traffic.

targetPort: 80
Remember :

port and targetPort can be different.

Service.spec.ports[].nodePort

A port reachable on the nodes with type NodePort; must be within the configured range.

nodePort: 30080
Remember :

Does not automatically open the system's firewalls.

Ingress.spec.ingressClassName

The name of the Ingress class used to pick the appropriate controller.

ingressClassName: nginx
Remember :

An Ingress controller must exist and handle this class.

Ingress.spec.rules

Defines HTTP hosts and paths that route to cluster Services.

rules:
  - host: web.exemple.test

Ingress.spec.tls

Associates TLS hosts with a certificate Secret to serve HTTPS.

tls:
  - hosts: [web.exemple.test]
    secretName: web-tls

05 · Configuration and storage

You must distinguish application configuration, secrets and data that must survive the disappearance of a Pod.

ConfigMap.data

A key-value set for non-sensitive parameters, consumed by Pods.

data:
  MODE: "production"

Secret.stringData / data

stringData accepts plain text on input; data carries base64-encoded values.

stringData:
  PASSWORD: exemple-fictif
Remember :

Never commit real secrets. Base64 is not encryption.

spec.volumes

Declares the volumes available in the Pod: emptyDir, Secret, ConfigMap, PVC, etc.

volumes:
  - name: cache
    emptyDir: {}

volumeMounts

Defines where a declared volume is visible in a container.

volumeMounts:
  - name: cache
    mountPath: /tmp/cache

persistentVolumeClaim.claimName

Links a Pod volume to an already declared PVC, for persistent storage.

volumes:
  - name: donnees
    persistentVolumeClaim:
      claimName: donnees-pvc

PVC.spec.accessModes

Requests the access modes supported by the storage, for example ReadWriteOnce.

accessModes: [ReadWriteOnce]
Remember :

RWO does not necessarily mean “a single Pod”; see the volume's semantics.

PVC.spec.resources.requests.storage

The amount of storage requested from the storage system.

resources:
  requests:
    storage: 2Gi

PVC.spec.storageClassName

The name of the requested storage class; its availability depends on the cluster.

storageClassName: standard
Remember :

Without a provisioner or compatible PV, a PVC can stay Pending.

06 · Security and placement

These fields influence the process's identity, the workloads' permissions and their placement on nodes.

securityContext.runAsNonRoot

Requires that the process not run with UID 0 in the container.

securityContext:
  runAsNonRoot: true
Remember :

The image must be compatible with a non-root user.

securityContext.allowPrivilegeEscalation

Prevents, where supported, a process from gaining new privileges at run time.

allowPrivilegeEscalation: false

securityContext.readOnlyRootFilesystem

Mounts the container's root file system read-only.

readOnlyRootFilesystem: true
Remember :

Provide volumes for the paths that must stay writable.

securityContext.capabilities.drop

Lets you remove Linux capabilities the process does not need.

capabilities:
  drop: ["ALL"]

spec.serviceAccountName

Associates a Kubernetes workload identity with the Pod, used notably for its requests to the API.

serviceAccountName: lecteur-pods
Remember :

Do not grant more permissions than necessary.

RBAC Role / RoleBinding

Role describes rules within a namespace; RoleBinding grants that role to a subject.

resources: ["pods"]
verbs: ["get", "list"]
Remember :

ClusterRole and ClusterRoleBinding concern reusable or cluster-wide permissions.

nodeSelector / affinity

Constrain or steer the choice of a node according to its labels or to relationships between Pods.

nodeSelector:
  kubernetes.io/os: linux

tolerations / taints

A taint repels certain Pods; a toleration allows a compatible Pod to be scheduled despite that taint.

tolerations:
  - key: dedicated
    operator: Equal
    value: lab
    effect: NoSchedule
Remember :

A toleration does not force the choice of that node.

NetworkPolicy.spec.podSelector

Determines which Pods in the namespace are subject to a NetworkPolicy.

podSelector:
  matchLabels: {app: db}
Remember :

The application requires a compatible CNI.

07 · Common mix-ups

Some properties look like those of Docker Compose, but Kubernetes's behaviour is different.

containerPort ≠ public exposure

containerPort describes the container's port; a Service, then possibly an Ingress or Gateway, defines the network access wanted.

containerPort: 80 ≠ LoadBalancer

Labels ≠ service names

Selectors link Services, Deployments and Pods by labels; these matches are what determine routing.

Service selector.app = Pod label.app

Readiness ≠ liveness

Readiness avoids sending traffic to a Pod that is not ready; liveness triggers a restart on failure.

/ready → trafic ; /live → redémarrage

Request ≠ limit

Request is used for scheduling; limit caps usage at run time.

100m CPU de request, 500m de limit

Secret ≠ guaranteed encryption

A Secret separates sensitive information, but its base64 data can be readable without encryption at rest or suitable RBAC.

Protéger etcd + accès API + Git

Deployment ≠ StatefulSet

A Deployment suits interchangeable services; a StatefulSet provides stable identities, often useful for workloads with attached storage.

web → Deployment ; base distribuée → StatefulSet

08 · Complete manifests

These complete files match the appendices of the PDF guide and can be copied from the site's sheets.

deployment.yaml

Declares two Nginx replicas with reserved resources and an HTTP availability probe.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: dev
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:stable
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 256Mi
          readinessProbe:
            httpGet:
              path: /
              port: 80
            periodSeconds: 5
Remember :

To apply after creating the dev namespace.

service.yaml

Creates a stable internal access point to the Pods carrying the label app: web.

apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: dev
spec:
  type: ClusterIP
  selector:
    app: web
  ports:
    - name: http
      port: 80
      targetPort: 80
Remember :

The Service will only work if the selector matches the Pods' labels.

configmap.yaml

Creates two non-confidential application settings in the dev namespace.

apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
  namespace: dev
data:
  APP_MODE: "demo"
  LOG_LEVEL: "info"

pvc.yaml

Requests 2 Gi of persistent storage; provisioning depends on the cluster's configuration.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: donnees-pvc
  namespace: dev
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 2Gi
# La StorageClass disponible dépend du cluster.
Remember :

Check kubectl get storageclass, then kubectl get pvc -n dev.

job.yaml

Runs a one-off task then finishes; not meant to host an HTTP server.

apiVersion: batch/v1
kind: Job
metadata:
  name: essai
  namespace: dev
spec:
  backoffLimit: 2
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: test
          image: busybox:1.36
          command: ["sh", "-c", "echo TP Kubernetes"]