Persisting Data

Combine volumes and bind mounts correctly so important data survives container restarts, updates and removal.

Containers are meant to be disposable — you should be able to delete and recreate them freely. That only works if important data lives outside the container.

What to persist

  • Databases — mount a volume at the database's data directory.
  • Uploaded files — store user uploads in a volume, not the container.
  • Configuration — inject via bind mounts or environment variables.

Upgrading safely

Because the data is in a volume, you can pull a newer image, remove the old container, and start a fresh one pointed at the same volume — with no data loss.

Example

Example · bash
# Upgrade Postgres without losing data
# 1. The old container uses the pgdata volume
docker rm -f db

# 2. Start a new container on the SAME volume
docker run -d \
  -v pgdata:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=secret \
  --name db postgres:16
# Data is still there because it lives in the volume

When to use it

  • A web app stores user-uploaded images in a named volume so they survive when the app container is updated to a new image version.
  • A team discovers that writing to a container's writable layer causes all data to be lost on removal, and fixes it by moving writes to a volume.
  • An ops team uses tmpfs for session data so it is stored in RAM, never written to disk, for security-sensitive ephemeral state.

More examples

Verify data persists across restarts

Shows that data written to a named volume survives container removal and is accessible to a new container.

Example · bash
docker run -d --name db -v mydata:/data alpine sh -c 'echo hello > /data/test.txt'
docker rm db
# Data still exists in the volume
docker run --rm -v mydata:/data alpine cat /data/test.txt

Use tmpfs for ephemeral data

Mounts a RAM-backed tmpfs filesystem for session data that is fast, never hits disk, and is erased on container stop.

Example · bash
docker run -d \
  --name app \
  --mount type=tmpfs,destination=/tmp/sessions,tmpfs-size=64m \
  myapp:latest

Migrate data between volumes

Uses a temporary Alpine container to copy all data from one volume to another for migration or cloning.

Example · bash
# Copy data from old volume to new volume
docker run --rm \
  -v old-volume:/from \
  -v new-volume:/to \
  alpine cp -a /from/. /to/

Discussion

  • Be the first to comment on this lesson.