Persist data

3 snippets in Docker

DKDocker

Volume Mounts (-v)

DK · Run Options
Syntax
docker run -v <host_path>:<container_path>[:<options>] <image>
docker run -v <volume_name>:<container_path> <image>
Example
docker run -v ./src:/app/src myapp:1.0
docker run -v pgdata:/var/lib/postgresql/data postgres:16
docker run -v ./config.json:/app/config.json:ro myapp:1.0

Note Host paths starting with ./ or / create bind mounts. A plain name like pgdata creates or reuses a named volume. Append :ro for read-only. If the host path does not exist, Docker creates it as a directory (not a file), which often causes surprises.

Volumes in Compose

DK · Docker Compose
Syntax
services:
  db:
    volumes:
      - <name>:<container_path>
volumes:
  <name>:
Example
services:
  db:
    image: postgres:16
    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
volumes:
  pgdata:

Note Named volumes declared in the top-level volumes: key persist across restarts and compose down. Bind mounts (host paths) are useful for development but should not be used for database storage in production.

Named Volumes

DK · Volumes & Storage
Syntax
docker volume create <name>
docker run -v <name>:<container_path> <image>
Example
docker volume create pgdata
docker run -d -v pgdata:/var/lib/postgresql/data postgres:16
Output
pgdata

Note Named volumes are managed by Docker and stored under /var/lib/docker/volumes/ on Linux. They persist independently of containers and survive docker rm. This is the recommended way to persist database data.

Frequently asked questions

How does Docker handle persist data?
Docker covers this with 3 copy-ready snippets on this page. The "Volume Mounts (-v)" snippet in Docker uses `docker run -v <host_path>:<container_path>[:<options>] <image>`.
Which command does the Docker example use?
The "Volume Mounts (-v)" snippet uses `docker run -v <host_path>:<container_path>[:<options>] <image>`, from the Run Options section of the Docker cheat sheet.
What other Docker snippets are shown for "persist data"?
Besides "Volume Mounts (-v)", this page also shows "Volumes in Compose", "Named Volumes".
Is there anything to watch out for?
Yes. For "Volume Mounts (-v)": Host paths starting with ./ or / create bind mounts. A plain name like pgdata creates or reuses a named volume. Append :ro for read-only. If the host path does not exist, Docker creates it as a directory (not a file), which often causes surprises.