Docker · Containers in practice

How do you handle persistent data in containers?

MediumpersistencestatefulvolumesUpdated Oct 2026
Quiz this track

Short answer

Keep state out of the container layer and use a volume or an external managed service. For databases, plan backup, restore, failover and storage performance before containerizing.

Containers are designed to be replaceable. Any data written to the writable layer disappears with the container, so persistent state needs a volume, a bind mount, or a service outside the container platform.

yaml
services:
  db:
    image: postgres:16
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
volumes:
  pgdata:
secrets:
  db_password:
    file: ./secrets/db_password.txt
State lives in a named volume; the password comes from a file, not an env literal.

Decisions to make

  • Use a managed database when backups and failover are not your core competency
  • If self-hosting, use a volume with a known backup and restore procedure
  • Do not run multiple database writers against the same volume
  • Account for storage IOPS and latency, not just capacity
  • Test restore, not only backup

Stateful workloads on a single Docker host have no failover. If the host dies, the volume is unavailable until the host or disk is recovered. A cluster with persistent volume claims changes the mechanics but not the need for backups.

A volume survives container removal but not docker volume prune, host loss or accidental deletion. Treat it as durable storage, not as a backup.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is the container layer unsuitable for database files?
  2. 2What happens to a stateful service if the Docker host fails?
  3. 3How do you run a consistent database backup?
  4. 4When should state live outside the container platform?

Say it in the interview

I keep persistent state out of the container layer and put it in a named volume or an external managed service. For a self-hosted database I plan the backup, restore and failover story before containerizing, because a volume on one host is not highly available. I also test restores, since an untested backup is only a hope.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.