Skip to content

Latest commit

 

History

History
47 lines (37 loc) · 2.6 KB

File metadata and controls

47 lines (37 loc) · 2.6 KB

Day 3: Docker Volumes - Persistent Data

Concepts:

  • Ephemeral Nature of Containers: By default, data written inside a container is lost when the container is removed.
  • Volumes: The preferred mechanism for persisting data generated by and used by Docker containers. They are managed by Docker and are more efficient than bind mounts for many use cases.
    • Named Volumes: Managed by Docker, created and referenced by name. Ideal for general-purpose persistence.
    • Anonymous Volumes: Also managed by Docker, but not given an explicit name. Less common.
  • Bind Mounts: You can mount a host machine's directory or file directly into a container. This is useful for development when you want to quickly see changes without rebuilding the image.

Examples:

  1. Create a named volume:
docker volume create my-app-data
  1. Inspect a volume:
docker volume inspect my-app-data
  1. Run a container and attach the named volume:
docker run -d --name data-writer -v my-app-data:/app/logs alpine:latest sh -c "while true; do echo 'Current time: $(date)' >> /app/logs/access.log; sleep 1; done"

(This runs an Alpine container in detached mode, names it data-writer, mounts my-app-data volume to /app/logs, and continuously writes to access.log.)

  1. Inspect the volume data (from within a temporary container):
docker run --rm -v my-app-data:/data alpine:latest cat /data/access.log

You can stop and remove data-writer, then re-run it, and the access.log content will persist because it's stored in the my-app-data volume.

  1. Using a bind mount for development (live code changes): Navigate to your my-node-app directory from Day 2.
docker run -p 8000:3000 -v "$(pwd):/usr/src/app" my-node-app:1.0

(Now, if you change app.js on your host, the changes will be reflected inside the running container instantly. For Node.js, you'd typically use nodemon inside the container for auto-restarts on file changes, but for this example, a manual restart of the container would show the change.)

Challenge 3: Persistent Database

  • Run a PostgreSQL or MySQL database in a Docker container.
  • Use a named Docker volume to ensure that your database data persists even if the container is removed or restarted.
  • Connect to the database from your host (e.g., using psql or mysql client within the container, or a GUI tool if you expose the port). Create a simple table and insert some data.
  • Remove the database container and then re-create it using the same volume. Verify that your data is still present.