Using Docker Volumes for Persistent Storage

Using Docker Volumes for Persistent Storage

By default, data inside a container is lost when the container is removed. Volumes solve this by storing data outside the container lifecycle.

Types of Storage Mounts

  • Named volumes: Managed by Docker, stored in /var/lib/docker/volumes/. Recommended for most use cases.
  • Bind mounts: Map a specific host directory into the container. Useful for development or config files.

Named Volumes

# Create a volume:
docker volume create mydata

# List volumes:
docker volume ls

# Use a volume in a container:
docker run -d -v mydata:/var/lib/mysql mysql:8

# Inspect a volume (see where it is on disk):
docker volume inspect mydata

Bind Mounts

# Mount a host directory into a container:
docker run -d -v /home/user/html:/usr/share/nginx/html nginx

# Mount a config file:
docker run -d -v /etc/nginx/nginx.conf:/etc/nginx/nginx.conf:ro nginx

In Docker Compose

services:
  db:
    image: mysql:8
    volumes:
      - db_data:/var/lib/mysql       # Named volume
      - ./my.cnf:/etc/mysql/my.cnf  # Bind mount

volumes:
  db_data:

Backup a Volume

docker run --rm -v mydata:/data -v $(pwd):/backup ubuntu tar czf /backup/mydata-backup.tar.gz /data

Remove Volumes

docker volume rm mydata
docker volume prune    # Remove all unused volumes
  • 0 Kunder som kunne bruge dette svar
Hjalp dette svar dig?

Relaterede artikler

Installing Docker

Installing Docker on Your Dedicated Server Docker allows you to run applications in isolated...

Getting Started with Docker Compose

Getting Started with Docker Compose Docker Compose lets you define and run multi-container...

Managing Docker Containers

Managing Docker Containers A practical reference for day-to-day Docker container management. Run...

Docker Networking Explained

Docker Networking Explained Understanding Docker networking lets you connect containers together,...

Building Custom Docker Images with a Dockerfile

Building Custom Docker Images A Dockerfile defines the steps to build a custom Docker image for...