Back
4/5

Volumes & Persistent Data

+15 XP on completion

#Volumes & Persistent Data

After this lesson you'll know:

  • why container data is ephemeral
  • the three types of volumes
  • how to share data between host and container

#The Problem

Containers are ephemeral — everything a container stores is gone when you delete it.

docker run alpine sh -c "echo 'hello' > /data.txt"
docker rm $(docker ps -aq)
# Data gone!

#The Solution: Volumes

# 1. Named Volume (recommended for production)
docker volume create app-data
docker run -v app-data:/app/data nginx

# 2. Bind Mount (recommended for development)
docker run -v $(pwd):/app -p 3000:3000 node npm run dev

# 3. Tmpfs Mount (ephemeral, RAM only)
docker run --tmpfs /app/cache nginx

#Bind Mount for Development

The bind mount is a game-changer for daily work:

# Your code stays live in the container
docker run -v $(pwd):/app -p 3000:3000 node:20 node /app/server.js
# Edits in your editor → immediately reflected in the container

#Pitfall: Permissions

Containers run as root by default. Writing to mounted directories creates root-owned files on your host.

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

#✋ Try it out

  • docker run -v $(pwd)/test:/data alpine touch /data/test.txt — creates a file on your host
  • docker volume create demo && docker run -v demo:/data alpine sh -c "echo 'persists' > /data/file.txt" — then docker volume inspect demo to see the path

#📌 Summary

  • Without volumes, all data is lost when the container is deleted
  • Named Volumes for production, Bind Mounts for development
  • Watch out for user permissions — set USER in your Dockerfile
← → to navigate