/var/lib/mysql inside the container. If you create databases and then remove the container, all of that data disappears:
/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:
/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.-v (or --volume) vs --mount
-v/--volume(short form) accepts a single colon-separated string (for example,/host/path:/container/path) and is concise.--mountis more explicit and recommended for clarity, especially for complex mounts; it accepts key-value pairs and requires you to settype,source, andtarget.
Equivalent
--mount example to the earlier -v bind mount:
- Always use absolute host paths with
--mount type=bind. - Create host directories ahead of time when using
--mountto 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
:zor:Zmount options with-vto 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.
- 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.
-vis concise and convenient;--mountis more explicit and recommended for clarity and production use.- Consider file permissions, SELinux contexts, and backup strategies when persisting data.