Use one of the below options to keep MySQL data persistent even after recreating or deleting docker containers.

Option 1 – Storing MySQL Data on Docker Volumes

The Docker volumes are preferred mechanism by the Docker for storing persistent data of Docker containers. You can easily create a Docker volume on your host machine and attach to a Docker containers. Let’s create a docker-compose file on your system with the following content.


The above configuration defined one data volume named “dbdata”, which is attached to MySQL container and mounted on /var/lib/mysql directory. This is the default directory used by MySQL to store all data files. Next, run below command to launch Docker container. Output: You can view the docker volumes by running commnad:

Option 2 – Storing MySQL Data on Host Machine

We recommend to use data volume instead of putting files on host machine. But, If you like, you can keep database files on the host machine. In any case docker container get terminated, you can relaunch container using the existing data files. Create a directory to keep your MySQL data files. I am creating below directory structure under the current directory. Then configure docker-compose.yml to use ./data/db as volume to store all files created by the MySQL server. Next create compose file in current directory.


After creating file, just run the below command to launch container. Output: In this case the MySQL container creats all files on host machine under ./data/db directory. To view these files, just run below command.