Skip to content
LF Cert Trainer

Lesson 100 · Section 8: Storage

Lesson 100: Application Configuration: pointing an application at its storage

How to make an application really use its volume: find the directory it writes to, mount the claim there, use subPath when a whole-directory mount hides too much, and give a non-root process permission to write with fsGroup. · 17 min read · 3 min video

1/10Application Configuration
0:00 / 3:27

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Mounted is not the same as used

The previous lesson ended with a Pod that mounts a claim. For a web server that serves files from one well-known directory, that is the whole job. Most applications need a little more care, and the failures are quiet ones: the Pod is Running, the claim is Bound, and the data is still lost at the next restart, because the application was writing somewhere else all along.

Configuring an application for storage means making three things agree:

  1. The application's data path. Where the process writes: its data directory, its log directory, its upload folder.
  2. The mount path. Where the volume appears in the container's file system.
  3. Permissions. Whether the user the process runs as may write there.
The application's path and the mount path must be the sametellssamestored inany other pathApp settingflag, env or configApplicationwrites to /logvolumeMountmountPath: /logContainer layerlost with the PodPVC log-claimkept
The application's path and the mount path must be the same. A setting tells the application where to write. If that directory is the mountPath, the files land in the claim. If it is any other directory, they land in the container's own layer and are lost with the Pod.

Parts:

  • App setting (flag, env or config)
  • Application (writes to /log)
  • volumeMount (mountPath: /log)
  • Container layer (lost with the Pod)
  • PVC log-claim (kept)

Connections:

  • App setting to Application: tells
  • Application to volumeMount: same
  • volumeMount to PVC log-claim: stored in
  • Application to Container layer: any other path

Step 1: find where the application writes

An image is somebody else's packaging decision, so the path is something you look up, not something you choose. In order of reliability:

Where to lookWhat it tells you
The task or the application's documentationThe exam states the path ("the application stores logs at /log"). Image documentation lists data directories
The Pod's command, args and envFlags such as --data-dir=/data or variables such as PGDATA set the path explicitly
A mounted ConfigMapA config file with a line such as dir /data or datadir=/var/lib/mysql
The running containerkubectl logs often prints the data directory at start. kubectl exec and ls -lt show which directory is changing

Well-known images and their defaults, worth recognising:

ImageData directory
nginx/usr/share/nginx/html (content), /var/log/nginx (logs)
mysql, mariadb/var/lib/mysql
postgres (up to 17)/var/lib/postgresql/data
redis/data
mongo/data/db

If the application lets you choose the path, choose it with the same tools you met in the Application Lifecycle section: a command-line argument, an environment variable, or a config file from a ConfigMap. The value you set there and the mountPath must be the same string.

spec:
  containers:
    - name: app
      image: registry.example.com/shop:1.4
      env:
        - name: LOG_DIR            # the application writes its log here...
          value: /log
      volumeMounts:
        - name: logs
          mountPath: /log          # ...and the claim is mounted here
  volumes:
    - name: logs
      persistentVolumeClaim:
        claimName: log-claim

Step 2: mount it in the right place

A volumeMounts entry has more fields than the two you have used so far:

FieldMeaning
nameThe Pod volume to mount. Must match an entry in spec.volumes
mountPathAbsolute path in the container. Created if it does not exist
readOnlytrue makes this mount read-only in this container. Default false
subPathMount this file or directory inside the volume, instead of the volume's root
subPathExprLike subPath, but may use the container's environment variables, as in $(POD_NAME)
mountPropagationWhether mounts made later below this path are shared with the host. Rarely needed; default None

A mount covers what was there

Mounting replaces the view of a directory. Everything the image had at mountPath is hidden for as long as the volume is mounted, and a new volume is empty. This is how Linux mounts work, not a Kubernetes rule, and Kubernetes does not copy the image's files into the volume for you. (Docker does that for its named volumes, which is why habits from Docker mislead here.)

So three kinds of path are dangerous to mount over:

  • A directory that holds the program, such as /app or /usr/local/bin. The container fails with exec: "/app/server": no such file or directory.
  • A directory that holds configuration, such as /etc/nginx. The application starts with no config.
  • A directory where the application expects initial content. An empty volume at /usr/share/nginx/html gives a 403 Forbidden.

subPath: mount less than the whole volume

subPath names a directory or a file inside the volume. Only that part is mounted at mountPath.

subPath mounts one directory of a volumemountsmountsinsideinsidemysql/var/lib/mysqlwordpress/var/www/htmlmysql/subPath: mysqlhtml/subPath: htmlPVC site-dataone volume
subPath mounts one directory of a volume. Two containers share one claim without seeing each other's files. Each mounts a different directory inside the volume, named by subPath, at the path its application expects.

Parts:

  • mysql (/var/lib/mysql)
  • wordpress (/var/www/html)
  • mysql/ (subPath: mysql)
  • html/ (subPath: html)
  • PVC site-data (one volume)

Connections:

  • mysql to mysql/: mounts
  • wordpress to html/: mounts
  • mysql/ to PVC site-data: inside
  • html/ to PVC site-data: inside

It solves four everyday problems:

  • Several applications in one claim. Each mounts its own directory, as in the diagram.
  • A database that refuses a non-empty directory. A freshly formatted disk has a lost+found directory at its root. MySQL and PostgreSQL refuse to initialise in a directory that already contains anything. With subPath: mysql the database gets a clean directory one level down.
  • One file into an existing directory. Mounting a ConfigMap at /etc/nginx/conf.d hides the files already there. With subPath: site.conf and mountPath: /etc/nginx/conf.d/site.conf, only that one file is added.
  • One directory per Pod in a shared volume. subPathExpr: $(POD_NAME) gives every replica its own directory inside one ReadWriteMany volume, so their log files do not collide.

The kubelet creates a subPath directory that does not exist yet.

Step 3: let the application write

Images increasingly run as a non-root user, and a hardened cluster may require it. A new volume, however, starts out owned by root. The result is a container that starts, tries to create its first file and exits with Permission denied, often into CrashLoopBackOff.

Why a non-root process cannot write, and how fsGroup fixes itdeniedread bychgrpwritesProcessUID 1000Volumeroot:root, 755securityContextfsGroup: 2000ProcessUID 1000, group 2000Volumegroup 2000, writableKubeletat mount time
Why a non-root process cannot write, and how fsGroup fixes it. A new volume belongs to root. A process running as user 1000 is denied. With fsGroup in the Pod's securityContext, the kubelet gives the volume to that group before the container starts, and the process is a member of it.

Parts:

  • Process (UID 1000)
  • Volume (root:root, 755)
  • securityContext (fsGroup: 2000)
  • Process (UID 1000, group 2000)
  • Volume (group 2000, writable)
  • Kubelet (at mount time)

Connections:

  • Process to Volume: denied
  • securityContext to Kubelet: read by
  • Kubelet to Volume: chgrp
  • Process to Volume: writes

The fix is in the Pod's security context, which you met in the Security section:

spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "sleep 3600"]
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: data-claim

fsGroup does three things when the kubelet mounts the volume:

  1. It changes the group of the volume's files and directories to that ID, and makes them group-writable.
  2. It sets the setgid bit on directories, so files created later inherit the group.
  3. It adds the ID to the supplementary groups of every container process.

The process still runs as user 1000, but it now belongs to group 2000, and group 2000 may write.

Under the hood · Slow starts on large volumes: fsGroupChangePolicy

By default the kubelet walks the entire volume on every mount and fixes the group and mode of each file. On a volume with millions of files that can take minutes, and the Pod sits in ContainerCreating with no error. The Pod-level field securityContext.fsGroupChangePolicy controls it:

  • Always (default): change everything on every mount.
  • OnRootMismatch: check only the volume's top directory, and skip the walk if it already has the right group and mode.
securityContext:
  fsGroup: 2000
  fsGroupChangePolicy: OnRootMismatch

Use OnRootMismatch for large volumes whose content is only ever written by this application.

Under the hood · An init container that prepares the volume

When fsGroup cannot help, for example on NFS, or when the volume needs initial content, do the preparation in an init container. It mounts the same volume, runs to completion before the application starts, and may run as root even if the application does not:

initContainers:
  - name: prepare
    image: busybox:1.36
    command: ["sh", "-c", "mkdir -p /data/uploads && chown -R 1000:1000 /data"]
    securityContext:
      runAsUser: 0
    volumeMounts:
      - name: data
        mountPath: /data

The same pattern copies default files from the image into an empty volume: mount the volume at a temporary path in the init container and cp -a the image's directory into it.

Using it

Example · Keep an application's logs in a claim

The task: "The Pod logger writes to /log/app.log. The log is lost whenever the Pod is recreated. Store it in the claim log-claim." Look at how the Pod writes:

kubectl get pod logger -o jsonpath='{.spec.containers[0].command}{"\n"}'
["sh","-c","while true; do date >> /log/app.log; sleep 5; done"]

The path is /log. Check that the claim is bound, then add the volume and replace the Pod:

kubectl get pvc log-claim
kubectl get pod logger -o yaml > logger.yaml
apiVersion: v1
kind: Pod
metadata:
  name: logger
spec:
  containers:
    - name: logger
      image: busybox:1.36
      command: ["sh", "-c", "while true; do date >> /log/app.log; sleep 5; done"]
      volumeMounts:
        - name: logs
          mountPath: /log
  volumes:
    - name: logs
      persistentVolumeClaim:
        claimName: log-claim
kubectl replace --force -f logger.yaml
sleep 12
kubectl replace --force -f logger.yaml
kubectl exec logger -- wc -l /log/app.log
4 /log/app.log

The Pod was recreated and the file still has the lines from its first life. Without the volume the count would start again at one.

Example · A database on a fresh disk: environment variable or subPath

PostgreSQL on a new block volume fails at once:

kubectl logs db
initdb: error: directory "/var/lib/postgresql/data" exists but is not empty
initdb: detail: It contains a lost+found directory, perhaps due to it being a mount point.
initdb: hint: Using a mount point directly as the data directory is not recommended.
Create a subdirectory under the mount point.

The message tells you the fix. There are two ways to give the database a clean subdirectory. Either move the application's path one level down with its own setting:

containers:
  - name: postgres
    image: postgres:17
    env:
      - name: POSTGRES_PASSWORD
        valueFrom:
          secretKeyRef:
            name: db-secret
            key: password
      - name: PGDATA
        value: /var/lib/postgresql/data/pgdata
    volumeMounts:
      - name: data
        mountPath: /var/lib/postgresql/data

or leave the application alone and mount a subdirectory of the volume:

    volumeMounts:
      - name: data
        mountPath: /var/lib/postgresql/data
        subPath: pgdata

Both end with the database files in pgdata/ on the disk. The first changes the application's path, the second changes what is mounted; pick one, not both.

Example · Add one config file without hiding the directory

An nginx Pod should get an extra site configuration from the ConfigMap site-config (key site.conf), and keep serving content from the claim data-claim:

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - name: content
          mountPath: /usr/share/nginx/html
        - name: config
          mountPath: /etc/nginx/conf.d/site.conf
          subPath: site.conf
          readOnly: true
  volumes:
    - name: content
      persistentVolumeClaim:
        claimName: data-claim
    - name: config
      configMap:
        name: site-config
kubectl apply -f web.yaml
kubectl exec web -- ls /etc/nginx/conf.d
default.conf
site.conf

default.conf comes from the image and is still there. Without subPath, mounting the ConfigMap at /etc/nginx/conf.d would leave only site.conf.

Example · Permission denied on a volume

kubectl get pod uploader
kubectl logs uploader
NAME       READY   STATUS             RESTARTS      AGE
uploader   0/1     CrashLoopBackOff   3 (20s ago)   70s

mkdir: can't create directory '/data/uploads': Permission denied

The container runs as a non-root user and the volume belongs to root. Confirm the user:

kubectl get pod uploader -o jsonpath='{.spec.securityContext}{"\n"}'
{"runAsUser":1000}

Add fsGroup at Pod level and recreate the Pod:

spec:
  securityContext:
    runAsUser: 1000
    fsGroup: 2000
kubectl replace --force -f uploader.yaml
kubectl exec uploader -- sh -c 'id; ls -ld /data'
uid=1000 gid=0(root) groups=0(root),2000
drwxrwsr-x 3 root 2000 4096 Dec  2 14:41 /data

The directory now belongs to group 2000 with the setgid bit (s), and the process lists 2000 among its groups. If the output of ls -ld is unchanged, the volume type does not support ownership changes; see the note on hostPath and NFS above.

Example · Check that the application really uses the volume

Three quick checks from inside the container:

kubectl exec app -- df -h /log                        # is /log its own mount, and how big?
kubectl exec app -- sh -c 'mount | grep " /log "'     # from which device or server?
kubectl exec app -- sh -c 'ls -lt /log | head -n 3'   # is the application writing here right now?
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb        974M   24K  907M   1% /log

/dev/sdb on /log type ext4 (rw,relatime)

-rw-r--r--    1 1000     2000         1.2K Dec  2 14:30 app.log

If df reports overlay as the file system, the path is not a mount: it is part of the container's writable layer, and the volume is mounted somewhere else or not at all.

Tricks

Common mistakes

  • Mounting at a path the application does not use. The Pod runs and the data is still stored in the container layer. Verify with df and by recreating the Pod.
  • Mounting over the image's program or config directory. The files are hidden and the container cannot start. Mount on a data directory, or use subPath for a single file.
  • Expecting an empty volume to contain the image's files. Kubernetes does not copy them. Use an init container if you need initial content.
  • Setting PGDATA (or a similar setting) and subPath to solve the same problem. The data ends up two levels down, and a later Pod that uses only one of them finds an empty directory.
  • Putting fsGroup in a container's securityContext. It exists only at Pod level, under spec.securityContext. In a container the API server rejects it as an unknown field.
  • Expecting fsGroup to fix hostPath or NFS permissions. It is ignored for those. Fix ownership at the source.
  • Relying on a subPath ConfigMap mount to update. It never does; the Pod must be recreated.

Recap

  • A volume stores only what the application writes under the mountPath. Find the application's data path first, from the task, its flags, its environment or its config file.
  • The application's setting and the mountPath must be the same path.
  • A mount hides whatever the image had at that path, and a new volume is empty.
  • subPath mounts one directory or file of a volume: several applications in one claim, a clean directory for a database, a single config file in an existing directory.
  • A non-root process needs spec.securityContext.fsGroup to write to a volume. It does not apply to hostPath and NFS.
  • Verify from inside the container with df -h, a test file, and a recreated Pod.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Section capstone. Put existing data on the node behind a volume and a claim, move a running app onto it, give a second app its own corner of the same volume, and get a third one its storage on demand.

    Build · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.