/var/lib/mysql), those files live inside the container’s ephemeral filesystem. Removing the container removes those files:
When using the official MySQL Docker image you typically need to provide initialization environment variables (for example
MYSQL_ROOT_PASSWORD) or other supported options (such as MYSQL_ALLOW_EMPTY_PASSWORD for testing). Without appropriate environment variables the container may exit during startup. Also, if you bind-mount an empty host directory into /var/lib/mysql, the image’s entrypoint will attempt to initialize the database there, which requires correct permissions and ownership.- Bind mount a host directory into the container (host-managed).
- Use a Docker named volume (Docker-managed).
/opt/datadir on the Docker host. Removing the container leaves the host files intact.
Using a host bind mount such as
/opt/datadir:/var/lib/mysql keeps the data on the host filesystem, so container removal does not delete your data. This also allows you to inspect host files directly for debugging.--mount. The same bind mount can be written as:
-v (or --volume) and --mount can create bind mounts or attach named volumes, but they differ in form and clarity:
Named volume example (Docker-managed volume):
/var/lib/docker/volumes/) and are convenient when you want Docker to manage the lifecycle and permissions of the volume.
Read-only mounts
- With
-v:
- With
--mount:
Mounting MySQL’s data directory read-only (
ro or readonly) prevents the server from writing data and typically causes MySQL to fail to start. Use read-only mounts only for directories that the container is expected to access but not modify.- Change ownership on the host to match the container UID expected by the image:
999:999 with the UID:GID required by the image.)
- Use a Docker-managed named volume to avoid manual host permission tweaks:
Be careful with permissions: when you bind-mount a host directory into a container, file ownership and permissions on the host affect the container process. Some images expect specific ownership or permissions for their data directory. If MySQL fails to start due to permission issues, consider adjusting ownership (for example
chown to the appropriate UID) or using a Docker-managed named volume instead.- To persist container data across container removal, use host bind mounts or Docker named volumes.
-vis concise and widely used;--mountis explicit and preferred for complex setups.- Prefer named volumes when you want Docker to manage permissions and lifecycle.
- When using bind mounts, ensure correct ownership and permissions on the host.
- Do not mount writable application data directories as read-only unless the application is designed for read-only access.