Skip to main content
When you run a Docker container, it gets its own isolated filesystem. Any files created or changed inside that container exist only for the lifetime of the container unless you explicitly persist them. This is important to understand when running stateful services like databases. Example: MySQL stores its data under /var/lib/mysql inside the container. If you create databases and then remove the container, all of that data disappears:
Because the container’s filesystem is ephemeral, deleting the container removes /var/lib/mysql and any databases created inside it. To persist data beyond the container lifecycle, mount storage from the Docker host into the container. Bind mount the host directory /opt/datadir into the container’s /var/lib/mysql using the short -v syntax:
With this bind mount, MySQL writes its files into /opt/datadir on the host. Removing the container (docker rm) does not remove data stored in /opt/datadir.
Bind mounts map a host directory (or file) into a container. The host path must be absolute when using --mount and is created automatically with -v if it does not exist.
A quick comparison: -v (or --volume) vs --mount
  • -v / --volume (short form) accepts a single colon-separated string (for example, /host/path:/container/path) and is concise.
  • --mount is more explicit and recommended for clarity, especially for complex mounts; it accepts key-value pairs and requires you to set type, source, and target.
Use the table below to compare these two forms and see sample usage: Equivalent --mount example to the earlier -v bind mount:
Best practices and operational notes
  • Always use absolute host paths with --mount type=bind.
  • Create host directories ahead of time when using --mount to avoid surprises.
  • Check file ownership and permissions: files created by the container may be owned by different UIDs/GIDs on the host. You may need to adjust permissions or use consistent UID/GID mappings.
  • For SELinux-enabled hosts, you might need :z or :Z mount options with -v to allow container access (e.g., -v /opt/datadir:/var/lib/mysql:Z).
  • For production deployments, prefer Docker named volumes, managed storage solutions, or networked storage backends and implement a regular backup strategy.
Persisting data with bind mounts exposes host files to the container. Misconfigured mounts can lead to data loss or security issues. Always back up important data and verify mount ownership/permissions before trusting a mount for production workloads.
Summary
  • Containers are ephemeral by default; files inside a removed container are removed with it.
  • Bind mounts let you map a host directory into a container so data persists independently of the container lifecycle.
  • -v is concise and convenient; --mount is more explicit and recommended for clarity and production use.
  • Consider file permissions, SELinux contexts, and backup strategies when persisting data.
Links and references

Watch Video