DEV Community

Cover image for Demystifying Data Persistence: Where Docker Stores Your MySQL data?
Arisa Shinozuka
Arisa Shinozuka

Posted on

Demystifying Data Persistence: Where Docker Stores Your MySQL data?

The cover image by Ian Taylor on Unsplash

Can we persistence data on the database when running it on Docker? The answer is absolutely yes. Except this function, Docker cannot be used widely as currently used.

But where is the data saved? Or precisely, when/where we configure the location of the saved data?

Short answer is: we can specify the location when we create a container for a database, with -v option.

I'd like to note that the location of the volume is in the container, not in your host system like Mac or Windows system. I misunderstood there is the data in a directory under my Mac system (that's why I write this article not to forget this fact). I hope you won't waste your time as I did!

The following is the recap of docker run command to create a container.
When create a container, you will use, for example, the following command to run a MySQL container in Docker, after you pull the image for the database.

docker run -d 
--name my-mysql-db 
-p 3306:3306 
-e MYSQL_ROOT_PASSWORD=your_password
-e MYSQL_DATABASE=your_database_name
-v mysql-data:/var/lib/mysql 
mysql:latest
Enter fullscreen mode Exit fullscreen mode
options used in the docker run above meaning
-d in detached mode: the container run in the background
--name my-sql-db assigns a custom name to the container (it's named "my-sql-db")
-p 3306:3306 maps the container's port 3306 (the default MySQL port) to port 3306 on your host system
-e MYSQL_ROOT_PASSWORD=your_password sets an environment variable named MYSQL_ROOT_PASSWORD within the container
-v mysql-data:/var/lib/mysql defines a volume mapping: it creates a named volume called mysql-data on your host system, which is mounted at the path /var/lib/mysql inside the container
mysql:latest specifies the Docker image to use

Top comments (0)