A volume is storage defined for a Kubernetes pod and mounted at a chosen path in a container’s filesystem. Without one, files changed inside a container are lost when that container is replaced during a restart. A volume can preserve those files across container restarts or let containers in the same pod exchange files. How long the data lasts depends on the volume type. section 9.1 section 9.7
Listing 9.2 The quiz pod with an emptyDir volume for the mongo container
apiVersion: v1
kind: Pod
metadata:
name: quiz
spec:
volumes: #1
- name: quiz-data #1
emptyDir: {} #1
containers:
- name: quiz-api
image: luksa/quiz-api:0.1
ports:
- name: http
containerPort: 8080
- name: mongo
image: mongo
volumeMounts: #2
- name: quiz-data #2
mountPath: /data/db #2
The pod manifest shows the two required steps: define the named emptyDir volume under spec.volumes, then reference that name in MongoDB’s volumeMounts at /data/db. section 9.2.1
Keep database files through a container restart
A Quiz API and MongoDB initially run in one pod without a volume. After a question is inserted, restarting the MongoDB container leaves the database empty. Mounting an emptyDir volume at MongoDB’s /data/db changes the result: the question remains after a container restart. The limit is important: emptyDir begins empty when the pod is created and is deleted when the pod terminates. section 9.1.1 section 9.2.1 section 9.7
The same mounting pattern supports other tasks:
- Prepare files before the main containers start: an init container copies a database initialization script into an emptyDir volume, which MongoDB then mounts read-only at its initialization-script path. section 9.2.2
- Share files between running containers: a writer mounts a volume at its output directory while Nginx mounts that volume, read-only, at the directory it serves. Mount paths need not match. section 9.2.3
Choose the volume type for the job. Besides emptyDir, an image volume supplies static files from an OCI image or artifact; hostPath exposes part of the host node’s filesystem and is dangerous; configMap, secret, downwardAPI, and projected volumes expose configuration, secrets, or pod metadata. Storage types intended for use beyond these pod-level examples are accessed through persistentVolumeClaim, ephemeral, or csi volumes. section 9.7







