Mysql with persistent storage

I am running MySQL in a docker container and I want to have the databases persistent across container restarts. When I google this everything I see talks about having the databases in another container and mounting that. I would prefer not to do it that way. Why cannot I not just have an area outside of the container that I mount as /var/lib/mysql? I tried that but it’s not working.

I have this in my Dockerfile:

ADD mysql /var/lib/mysql
VOLUME [“/var/lib/mysql”]

I run it with this:

-v /projects/mysql:/var/lib/mysql

and it does create the files and mysql owns them and they are mode 660:

ls -l /var/lib/mysql/

total 28672
-rw-rw----. 1 mysql mysql 5242880 Jun 28 16:48 ib_logfile0
-rw-rw----. 1 mysql mysql 5242880 Jun 28 16:29 ib_logfile1
-rw-rw----. 1 mysql mysql 18874368 Jun 28 16:41 ibdata1

but then mysql fails with:

160628 16:48:10 [ERROR] Fatal error: Can’t open and lock privilege tables: Table ‘mysql.host’ doesn’t exist

1 Like

I’m pretty sure the standard mysql container is configured this way. It stores its data in a Docker volume. So you should be able to

docker run -d -p 3306:3306 --name mysql mysql
...
docker stop mysql
docker rm mysql
...
docker run -d -p 3306:3306 --name mysql mysql

and it should find the same volumes from the previous time it ran. Volumes | Docker Docs has a lot of details.

I am mounting a volume and it does find it from previous runs, but mysql will not start. That is my issues.

I solved my problem. I had to add this to my run file:

mysql_install_db --user=mysql --ldata=/var/lib/mysql/

Do you have any idea how to do it with docker-compose?