Data Management in Docker

Data Management in Docker

Introduction

Docker containers are temporary and ephemeral, meaning any data stored inside a running container disappears when the container stops. To persist data across container restarts, Docker provides two primary storage options:

   1.  Volumes (Recommended) – Managed by Docker.
   2.  Bind Mounts – Directly link a folder from the host machine to a container.

1️. Using Docker Volumes (Recommended for Persistence)

What are Volumes?

•  Stored in Docker’s managed directory (/var/lib/docker/volumes/).
•  Can be shared between multiple containers.
•  Persist even after a container is removed.

Basic Volume Commands

✅ Create a volume:

docker volume create my_volume

✅ Run a container with a volume:

docker run -d -v my_volume:/app/data ubuntu

✅ List all volumes:

docker volume ls

✅ Inspect a volume:

docker volume inspect my_volume

✅ Remove a volume:

docker volume rm my_volume

✅ Remove all unused volumes:

docker volume prune

2️⃣ Using Bind Mounts (Direct Host Folder Access)

What are Bind Mounts?

•  Mounts a specific host machine directory inside the container.
  Changes inside the container also reflect on the host.
•  Requires an absolute path on the host.

✅ Run a container with a bind mount:

docker run -d -v /home/user/data:/app/data ubuntu

Example:

If a file is added to /home/user/data on the host, it appears inside /app/data in the container.

3️⃣ Anonymous Volumes (Temporary Storage)

  Used for short-lived storage.
  Automatically created without a name.

Example:

docker run -d -v /app/data ubuntu

4️⃣ Managing Data in Docker Compose

Docker Compose allows defining persistent storage in docker-compose.yml:

aml

version: ‘3’
servicyes:

app:
image: ubuntu
volumes:
– my_volume:/app/data

volumes:
my_volume:

✅ Run Docker Compose:

docker-compose up -d

5️. Backing Up and Restoring Data

✅ Backup a volume:

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

✅ Restore a volume:

docker run –rm -v my_volume:/data -v $(pwd):/backup ubuntu tar xzf /backup/backup.tar.gz -C /data

Conclusion

•  Use Volumes for persistent storage across containers.
  Use Bind Mounts for direct access to host machine files.
•  Always backup important container data to prevent loss.

Chatbot