Learn Docker · 6/12

Managing Data: Volumes and Persistence

8 min read

When you first start using Docker, containers feel like magic. You pull an image, run it, and your application is instantly alive. But this magic comes with a catch: by default, containers suffer from amnesia. If you stop and remove a container, everything it learned, processed, or saved during its lifetime is permanently erased.

To build reliable applications, we need a way to ensure that critical data—like user databases, uploaded files, and application logs—survives even if the container is destroyed. This is where data management and persistence come in.


1. The Ephemeral Container: Why Data Disappears by Default

Definition

Ephemeral means temporary or short-lived. In the context of Docker, an ephemeral container means that any data written inside the container is strictly tied to the lifecycle of that specific container instance. When the container is deleted, the data is deleted with it.

The Problem

Imagine you start a PostgreSQL database container. Your application connects to it, and users spend all day creating accounts, uploading avatars, and generating 10,000 rows of critical business data. Tomorrow, you decide to update the database to a newer version. You stop the container, remove it, and start a new one.

Suddenly, your database is completely empty. All 10,000 rows are gone. Because the container was ephemeral, the data was discarded the moment the container was removed.

Under the Hood: Why Does This Happen?

When Docker runs a container from an image, it stacks a thin writable container layer on top of the underlying read-only image layers. Any file you create, modify, or delete during the container's operation is stored in this thin writable layer.

Because this layer is directly attached to the container instance, deleting the container destroys the writable layer.

Imagine writing a brilliant novel on a café’s whiteboard (the container's writable layer). It works perfectly fine while you are sitting there working. But the moment you leave (the container stops/removes), the janitor (Docker) wipes the whiteboard clean for the next customer. If you want to keep your novel, you cannot rely on the whiteboard. You need a notebook that you can take with you.


2. Docker Volumes: The Recommended Way to Persist Data

Definition

A Docker Volume is a specialized, Docker-managed storage directory that lives outside the container's default writable layer. It is stored on the host machine (usually in /var/lib/docker/volumes/ on Linux) but is completely managed by Docker, isolated from the core functionality of the host machine.

The Problem

If we know data disappears inside the container, we need a safe place to put it. We could just arbitrarily dump files onto our host computer's hard drive, but that creates permission nightmares, OS-specific path issues, and security vulnerabilities.

How Volumes Solve It

Docker Volumes solve this by acting as a secure, dedicated storage locker that Docker manages for you. Because volumes sit outside the container's lifecycle, you can delete a container, and the volume remains perfectly intact. When you spin up a new container, you simply reattach the volume, and all your data is instantly available.

Industry Standard and Hands-On Practice

In the industry, named volumes are the absolute standard for persisting database files, application states, and production data.

Trying to manage database files without Docker volumes in production is like trying to carry hot soup in your bare hands. It might work for a few steps, but you will eventually get burned and make a disastrous mess.

Creating and Managing a Volume

First, you explicitly create a volume using the Docker CLI:

bash
# Create a named volume
docker volume create my_database_data

# List all volumes to verify it exists
docker volume ls

Attaching the Volume

When running a container, you attach the volume using the --mount flag.

Note: You will often see the -v (or --volume) flag used in older tutorials. While -v works, Docker officially recommends the --mount syntax for industry use because it is explicit, clearer, and throws a helpful error if something goes wrong, rather than silently creating unwanted folders.

bash
# Running a PostgreSQL container and mounting the volume
docker run -d \
  --name my_postgres \
  -e POSTGRES_PASSWORD=mysecretpassword \
  --mount type=volume,source=my_database_data,target=/var/lib/postgresql/data \
  postgres:15

Let's break down the --mount parameters:

  • type=volume: We are explicitly stating we want to use a Docker-managed volume.
  • source=my_database_data: The name of the volume we created.
  • target=/var/lib/postgresql/data: The exact directory inside the container where PostgreSQL expects to save its data.

Now, if you run docker rm -f my_postgres to destroy the container, your data remains safely stored in my_database_data.


3. Bind Mounts: Connecting Host Directories to Containers

Definition

A Bind Mount is a direct link between a specific, user-defined file or directory on your host machine (your laptop or server) and a directory inside the container. Unlike volumes, bind mounts rely entirely on the directory structure and operating system of your host machine.

The Problem

When you are a developer writing code, you need to test your changes immediately. If you rely solely on Docker images, you would have to rebuild your image and restart your container every single time you edit a line of code. Rebuilding an image 500 times a day is a guaranteed way to lose your sanity.

How Bind Mounts Solve It

Bind mounts solve this by bridging the gap between your host machine and the container. If you bind mount your local source code folder into the container's working directory, the container reads your local files in real-time. You hit Ctrl+S (Save) in your code editor on your laptop, and the container instantly registers the updated code without a rebuild.

Industry Practice

Bind mounts are heavily used for local development, but are generally avoided in production.
In production, you want your containers to be portable and isolated. If you use a bind mount, your container expects a very specific folder (like /Users/john/projects/app) to exist on the server. If that folder doesn't exist, the container crashes. Furthermore, bind mounts give the container direct access to your host's filesystem, which can be a severe security risk if the container is compromised.

Using a Bind Mount

To use a bind mount, you specify the absolute path on your host machine and map it to the container.

bash
# Running a Node.js app with a bind mount for live-reloading
docker run -d \
  --name my_node_app \
  --mount type=bind,source="$(pwd)"/src,target=/app/src \
  node:20 npm run dev
  • type=bind: We are telling Docker to bypass its internal volume management and look directly at our host's hard drive.
  • source="$(pwd)"/src: The absolute path on your host machine (using $(pwd) grabs your current working directory).
  • target=/app/src: The path inside the container where the code should appear.

Fun Fact: The container literally bypasses its own isolated filesystem to read your disk. If your application contains a bug that deletes everything in /app/src, it will permanently delete the files on your actual laptop. Proceed with caution! 😅


4. Sharing Data Seamlessly Between Multiple Containers

Definition

Data sharing in Docker refers to the practice of attaching the exact same volume or bind mount to two or more containers simultaneously. This allows multiple isolated containers to read from or write to the exact same pool of data.

The Problem

Microservice architectures are built on the idea of single-responsibility. You might have one container whose only job is to run a web application, and another container whose only job is to collect error logs and send them to a monitoring dashboard. Because containers are securely isolated from each other by default, the log-collector container has no way of seeing the web application's logs.

How Sharing Solves It

By mounting the same volume to both containers, you create a shared bridge.

Imagine you are running a busy restaurant kitchen. You have a Chef (Container A) cooking food, and a Waiter (Container B) delivering food. They operate in completely different areas. If the Chef doesn't have a place to put the finished food, the Waiter can't pick it up. A shared volume acts exactly like the kitchen's pass-through window. The Chef places the plate on the counter (writes to the volume), and the Waiter picks it up from that exact same counter (reads from the volume).

Hands-On Example

Let's simulate an application that generates logs, and a secondary container that reads them.

1. Create the shared volume:

bash
docker volume create shared_logs

2. Start the Application Container (The Writer):

bash
docker run -d \
  --name web_app \
  --mount type=volume,source=shared_logs,target=/var/log/app \
  ubuntu bash -c "while true; do echo 'App Error at $(date)' >> /var/log/app/errors.log; sleep 5; done"

(This container writes a new error line to the volume every 5 seconds).

3. Start the Log Reader Container (The Reader):

bash
docker run -it \
  --name log_monitor \
  --mount type=volume,source=shared_logs,target=/app/logs,readonly \
  ubuntu tail -f /app/logs/errors.log

Notice the readonly flag in the second command? This is an industry best practice. If a container only needs to read shared data, you should mount the volume as read-only. This prevents the log-monitoring container from accidentally modifying or deleting the web application's files.


References & Further Reading

Challenge

You are tasked with setting up a multi-container application environment using Docker. Your goal is to correctly configure data persistence and sharing using volumes and bind mounts. Write the necessary Docker commands to accomplish the following four tasks in order:

  1. Create a Docker-managed volume named app-data to persist critical application state.

  2. Run a detached container named database from the mysql:8.0 image. Attach the app-data volume you created to the /var/lib/mysql directory inside this container to persist the database files.

  3. For local development, run a second, interactive container named dev-server from the python:3.9-slim image. This container needs to access source code from your host machine. Bind mount the host directory /path/to/my/project to the /app directory inside the container.

  4. Run a third, detached container named backup-agent from the alpine image. This container's job is to read data from the application for backups. Mount the app-data volume to /mnt/data inside this container, but ensure the data cannot be accidentally modified by granting read-only access.

Expected result

Your solution should consist of four distinct Docker commands that correctly perform the requested actions.

  1. A docker volume create command that specifies the name app-data.
  2. A docker run command that includes the -d flag for detached mode, the --name database flag, the mysql:8.0 image, and the --mount flag. The mount must be of type=volume, with source=app-data and target=/var/lib/mysql.
  3. A docker run command that includes the -it flag for interactive mode, the --name dev-server flag, the python:3.9-slim image, and the --mount flag. The mount must be of type=bind, with source=/path/to/my/project and target=/app.
  4. A docker run command that includes the -d flag, the --name backup-agent flag, the alpine image, and the --mount flag. The mount must be of type=volume, with source=app-data, target=/mnt/data, and the readonly option.
shell

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.