Docker Persistence

By default, all files created inside a container are stored on a writable container layer. This means the data is lost when the container is deleted. To persist data, Docker provides two main options: Volumes and Bind Mounts.

1. Volumes

Volumes are the preferred mechanism for persisting data. They are managed by Docker and stored in a part of the host filesystem that is managed by Docker (/var/lib/docker/volumes/ on Linux).

  • Managed by Docker: You don’t need to worry about the underlying host directory structure.
  • Portable: Easier to back up or migrate than bind mounts.
  • Performance: Better performance on Docker Desktop (Windows/Mac) compared to bind mounts.
  • Safety: New volumes can have their content pre-populated by a container.

2. Bind Mounts

Bind mounts have been available since the early days of Docker. They mount a specific file or directory on the host machine into a container.

  • Host Dependent: Relies on the host machine having a specific directory structure.
  • Direct Access: The host can read and modify the files directly. Useful for development (e.g., mounting source code into a container to see live changes).
  • Permissions: Can be tricky as the container might require specific UID/GIDs that don’t match the host user.

3. tmpfs Mounts

Stored only in the host system’s memory. When the container stops, the tmpfs mount is removed, and files written there are discarded. Useful for sensitive information or non-persistent state that needs high performance.