Back to course

Lesson 12: Using Volumes for Managed Data Persistence

Docker Zero to Hero: The Complete Containerization Course for Beginners

Lesson 12: Using Volumes for Managed Data Persistence

Volumes are Docker's recommended way to manage persistent data. Docker handles the creation, mounting, and management of the volume on the host system.

1. Creating a Volume

First, explicitly create a named volume using the CLI:

bash docker volume create pg_data

List your existing volumes:

bash docker volume ls

2. Running a Container with a Volume

We map the named volume to a directory inside the container using the -v flag.

Let's run a PostgreSQL database, which expects its data to be stored in /var/lib/postgresql/data.

bash docker run -d \n --name my_postgres \n -e POSTGRES_PASSWORD=secretpassword \n -v pg_data:/var/lib/postgresql/data \n postgres:15

Explanation of -v:

  • -v pg_data: The name of the Docker volume (host side).
  • :: Separator.
  • /var/lib/postgresql/data: The path inside the container where PostgreSQL stores its data.

3. Data Persistence Test

  1. Start the container (as above).

  2. Stop the container: bash docker stop my_postgres

  3. Remove the container (but not the volume!): bash docker rm my_postgres

  4. Rerun the container using the same volume name (pg_data). The database will load its previously stored data, proving persistence.

4. Cleaning Up Volumes

Volumes consume disk space and must be cleaned up manually when no longer needed.

bash docker volume rm pg_data

Warning: Removing a volume permanently deletes all data stored within it!