📝 Docker

Docker Volumes: Persisting Data

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
08.05.2026
⏱️
Reading time
1 min
👁️
Views
51
🌱
Level
Beginner

By default, data inside a container is not persisted — delete the container and the data is gone. Volumes solve this problem.

Three Ways to Mount

Docker manages the storage. Data survives container removal.

docker run -v postgres_data:/var/lib/postgresql/data postgres

In docker-compose.yml:

services:
  db:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:  # declare the volume

You mount a directory from the host into the container. Changes in either direction are immediately visible.

docker run -v /path/on/host:/path/in/container myapp
docker run -v $(pwd):/app myapp           # current directory
docker run -v ./src:/app/src myapp        # relative path

In docker-compose.yml:

services:
  web:
    volumes:
      - ./src:/app/src     # for live reload in development
      - ./static:/app/static

3. tmpfs (Linux only)

Data lives in memory, not on disk. For temporary data.

docker run --tmpfs /tmp myapp

Managing Volumes

docker volume ls                    # list volumes
docker volume inspect postgres_data # volume details
docker volume rm postgres_data      # remove a volume
docker volume prune                 # remove unused volumes

When to Use What

Type When to use
Named volume Database data, uploads, persistent data
Bind mount Development — hot reload, config files
tmpfs Cache, sessions, sensitive data

Development Pattern

Mount your code as a bind mount, dependencies as a named volume:

services:
  web:
    build: .
    volumes:
      - .:/app                      # code — bind mount for hot reload
      - /app/.venv                  # isolate .venv in a volume

Without the second line, the host .venv would shadow the .venv from the image.

Backing Up a Volume

# Create a backup of a volume as a tar archive
docker run --rm -v postgres_data:/data -v $(pwd):/backup \
  ubuntu tar czf /backup/backup.tar.gz /data

# Restore
docker run --rm -v postgres_data:/data -v $(pwd):/backup \
  ubuntu tar xzf /backup/backup.tar.gz -C /

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Layers and Caching in Docker

Every instruction in a Dockerfile creates a layer — an intermediate image. Docker caches layers...

📅 08.05.2026 👁️ 62
📝

Docker Hub — Image Registry

Docker Hub is the public Docker image registry. Think of it as npm for Node.js...

📅 08.05.2026 👁️ 50
📝

Docker Compose: Multi-Container Applications

Docker Compose is a tool for running multiple related containers as a single application. The...

📅 08.05.2026 👁️ 50

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!