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).
Container storage: writable layer, bind mounts, and named volumes
Experiment freely. Changes disappear when you reset or refresh.
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.
Proving database persistence with named volumes
Create a Named Volume & Mount It in MySQL
volume create-v mysql-data:/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 \
phpmyadminWHAT 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# 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-dataOpen 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# 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-dataWHAT 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
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
docker volume ls- List all named volumes
docker volume inspect- Inspect volume mountpoint and driver
docker volume rm- Delete an unused named volume
Mounting & Maintenance
-v vol:/path- Mount a named volume into a container
-v "$PWD":/path- Bind-mount the current host directory
-v vol:/path:ro- Mount a volume or bind mount read-only
docker volume prune- Remove all unused local volumes
Storage Mechanisms Compared
Writable layer- Default ephemeral R/W layer; deleted with container
Named volume- Docker-managed storage; best for databases and persistent state
Bind mount- Maps a host path directly; ideal for live local development
tmpfs mount- Stored in host memory only; never written to disk
Take a moment to explain the idea in your own words.