DevOps Engineering Containers06 / 21

SECTION 03 · 30 MIN READ & EXPLORE

Container Volumes

Compare ephemeral writable layers, host bind mounts, and Docker-managed named volumes.

How Does Container Storage Work?

Data written inside a container’s default writable layer disappears the moment that container is removed. To persist state across restarts and upgrades, Docker offers bind mounts (mapping an explicit host folder for development) and named volumes (storage managed by Docker, recommended for databases and persistent application data).

EXPLORE THE DIAGRAM

Container storage: writable layer, bind mounts, and named volumes

Experiment freely. Changes disappear when you reset or refresh.

Preview of Container storage: writable layer, bind mounts, and named volumes

Why and When to Use Volumes?

Named volumes decouple data from container lifecycles: you can delete, upgrade, or recreate a database container without losing a single row.

SCENARIOS

Proving database persistence with named volumes

Create a Named Volume & Mount It in MySQL

volume create-v mysql-data:/var/lib/mysql
SITUATION

In the networking exercise, removing the MySQL container erased all inserted rows. You need database files to outlive the container.

TASK

Create a network and a named volume, then start MySQL with the volume mounted at /var/lib/mysql.

# 1. Create the network and named volume
docker network create can-network
docker volume create mysql-data

# 2. Start MySQL mounting mysql-data to MySQL's data directory
docker run -d \
  --name mysql-dev \
  --network can-network \
  -p 127.0.0.1:3306:3306 \
  -v mysql-data:/var/lib/mysql \
  -e MYSQL_ROOT_PASSWORD=root \
  -e MYSQL_DATABASE=can2025 \
  mysql:8.0

# 3. Start phpMyAdmin on the same network
docker run -d \
  --name pma \
  --network can-network \
  -p 127.0.0.1:8080:80 \
  -e PMA_HOST=mysql-dev \
  phpmyadmin

WHAT TO OBSERVE

docker volume ls lists mysql-data, and docker volume inspect mysql-data shows the Docker-managed mountpoint on the host.

Populate & Inspect the Data

volume inspectuv run
SITUATION

MySQL is now writing its tables into the named volume rather than the container's disposable writable layer.

TASK

Seed the database with the squad list and confirm the rows appear in phpMyAdmin.

# 1. Wait until MySQL accepts connections, then seed the database
uv run --with mysql-connector-python seed_can_2025.py

# 2. Inspect the volume metadata
docker volume inspect mysql-data

Open http://localhost:8080 (root / root) and verify the squad table is populated.

WHAT TO OBSERVE

The can2025 database contains the seeded players, stored safely inside mysql-data.

Replace the Container & Verify Persistence

rm -f-v mysql-data:/var/lib/mysqlvolume rm
SITUATION

You need to prove that destroying the database container does not destroy the underlying named volume.

TASK

Delete mysql-dev, start a brand-new MySQL container attached to the same volume, and confirm the players remain.

# 1. Destroy the running MySQL container
docker rm -f mysql-dev

# 2. Start a fresh MySQL container using the exact same named volume
docker run -d \
  --name mysql-dev \
  --network can-network \
  -p 127.0.0.1:3306:3306 \
  -v mysql-data:/var/lib/mysql \
  -e MYSQL_ROOT_PASSWORD=root \
  -e MYSQL_DATABASE=can2025 \
  mysql:8.0

# 3. Refresh phpMyAdmin to confirm all data survived, then clean up
docker rm -f mysql-dev pma
docker network rm can-network
# Remove the volume only when you intentionally want to discard data:
docker volume rm mysql-data

WHAT TO OBSERVE

After refreshing phpMyAdmin, every previously inserted player is still present—proving the named volume survived container replacement.

Optional Extension: Analyze a Local Dataset

The lesson archive also includes movies.csv and import_movies.py. Inspect the importer below if you want to create a local SQLite database and practice mounting a read-only or writable dataset into an analytics container.

Explore the files

import_movies.py

import csv
import sqlite3
import os

def import_csv_to_sqlite(csv_file, db_file, table_name):
    if not os.path.exists(csv_file):
        print(f"Error: {csv_file} not found.")
        return

    # Connect to SQLite database
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()

    with open(csv_file, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        headers = next(reader)
        
        # Clean headers: replace spaces with underscores, lower case
        headers = [h.strip().replace(' ', '_').lower() for h in headers]
        
        # Create table
        # Assuming all columns are TEXT for simplicity, or we could infer types.
        # For a simple import, TEXT is usually safe.
        columns = ', '.join([f'"{h}" TEXT' for h in headers])
        create_table_sql = f'CREATE TABLE IF NOT EXISTS {table_name} ({columns})'
        cursor.execute(create_table_sql)
        
        # Prepare insert statement
        placeholders = ', '.join(['?' for _ in headers])
        insert_sql = f'INSERT INTO {table_name} VALUES ({placeholders})'
        
        # Insert data
        rows = []
        for row in reader:
            rows.append(row)
            
        cursor.executemany(insert_sql, rows)
        conn.commit()
        print(f"✅ Imported {len(rows)} rows into table '{table_name}' in {db_file}")

    conn.close()

if __name__ == "__main__":
    import_csv_to_sqlite('movies.csv', 'movies.db', 'movies')

Quick Reference

CHEAT SHEET

Docker volume commands & storage types

Core volume lifecycle operations and when to pick each storage mechanism.

Volume Lifecycle (CRUD)

docker volume create
Create a Docker-managed named volume
CREATE
docker volume ls
List all named volumes
READ
docker volume inspect
Inspect volume mountpoint and driver
READ
docker volume rm
Delete an unused named volume
DELETE

Mounting & Maintenance

-v vol:/path
Mount a named volume into a container
VOLUME
-v "$PWD":/path
Bind-mount the current host directory
BIND
-v vol:/path:ro
Mount a volume or bind mount read-only
FLAG
docker volume prune
Remove all unused local volumes
DELETE

Storage Mechanisms Compared

Writable layer
Default ephemeral R/W layer; deleted with container
EPHEMERAL
Named volume
Docker-managed storage; best for databases and persistent state
PERSISTENT
Bind mount
Maps a host path directly; ideal for live local development
HOST SYNC
tmpfs mount
Stored in host memory only; never written to disk
MEMORY
A LITTLE CLEARER?

Take a moment to explain the idea in your own words.

Progress is saved in this browser.

DevOps Engineering

Course overview ↗

01Introduction to DevOps

  1. What is DevOps?20m
  2. DevOps Roles20m