When attempting to import a SQL dump into a MySQL container and subsequently commit the container as a new image, users may encounter the issue of the database not retaining the newly created data upon starting a container with the new image. This article investigates the root cause and provides a solution to resolve this issue.
The official MySQL Docker image stores data in a volume. This is a desirable setup to ensure data persistence beyond the container's lifespan. However, data volumes bypass the Union File System and are not included in the image commit process. Consequently, data added to the database during container runtime will not be reflected in the committed image.
To overcome this limitation and commit the newly added data, users can create their own MySQL base image without data volumes. This involves building a custom image that includes the necessary software and configuration but excludes any volume mount points.
FROM mysql:latest RUN apt-get update && apt-get install -y mysql-client
mysql -uroot -psecret -e 'create database <database_name>;' mysql -uroot -psecret <database_name> < /mnt/<sql_dump_file>.sql
docker commit -m "Imported <database_name> SQL dump" <container_id> <new_image_name>:<version>
By creating a custom MySQL base image without volumes, users gain the ability to:
It is important to note that data added to a running container after the commit will be lost when the container ceases to exist. This is because data is no longer stored in a persistent volume but rather in the container's ephemeral file system.
The above is the detailed content of How to Preserve MySQL Database Data When Committing a Container as Image?. For more information, please follow other related articles on the PHP Chinese website!