Docker Data Persistence

Published on


Docker Data Persistence

1. The Core Concept: Ephemeral Containers

By default, containers are ephemeral. This means:

  • Files created inside a container are stored in a writable layer.
  • When the container is deleted (docker rm), that writable layer — and all your data — is destroyed.

Solution: We use Storage Mounts to persist data beyond the life of the container.


2. Docker Volumes (The Production Standard)

Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

  • Managed by: Docker
    (Location: /var/lib/docker/volumes/ on Linux)
  • Best for: Databases, application data, and production environments.
  • Behavior: Even if the container is removed, the Volume (and its data) remains until explicitly deleted.

Create a New Volume

docker volume create <volume_name>

List All Volumes

docker volume ls

Inspect a Volume

docker volume inspect <volume_name>

Look for the “Mountpoint” entry.

Usage Example

Mounting a volume named arch-data to /data inside the container:

docker run -v arch-data:/data alpine ...

3. Bind Mounts (The Developer Standard)

Bind mounts map a specific file or directory on the host machine to a file or directory inside the container.

  • Managed by: You (the user)
  • Best for: Local development, live code reloading, editing config files
  • Behavior: Changes on the host are instantly visible in the container — and vice versa.

Usage Example

Mounting the current directory ($(pwd)) on the host to the Nginx HTML folder:

docker run -v $(pwd):/usr/share/nginx/html nginx

4. Volumes vs Bind Mounts (Comparison)

FeatureVolumesBind Mounts
Host LocationManaged by Docker (/var/lib/...)Any path you specify
PortabilityHigh (Works on any OS)Low (Host dependent)
Use CaseDatabase storage, safetyLive coding, config injection

5. Critical CLI Flags & Concepts

The --rm Flag

Automatically removes the container when it exits.

docker run --rm alpine echo "I run, then I disappear"

Why use it?
Prevents your disk from filling up with stopped “zombie” containers during testing.


The sh -c Command

Used to pass a command string to a shell inside the container.

Scenario

You want to run:

echo "hello" > file.txt

Wrong

docker run alpine echo "hello" > file.txt

Result:
The > is interpreted by your host shell.
The file is created on your local machine.

docker run alpine sh -c "echo 'hello' > file.txt"

Result:
The entire command runs inside the container, and the file is created inside the container filesystem.

Thank you for reading. This article is part of the PaperAstro starter template.