- 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.
- Create a named volume:
docker volume create my-app-data- Inspect a volume:
docker volume inspect my-app-data- 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.)
- Inspect the volume data (from within a temporary container):
docker run --rm -v my-app-data:/data alpine:latest cat /data/access.logYou 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.
- Using a bind mount for development (live code changes):
Navigate to your
my-node-appdirectory 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.)
- 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
psqlormysqlclient 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.