Permissions error while using system MySQL folder and Docker

I recently had an issue where I had a whole-folder backup for a Percona MySQL server. I needed to do some local development work on this database, so I figured the easiest thing was to start up a Dockerized MySQL server (Percona MySQL Docker image works great!)

You can start the docker image and use a local volume on the host machine to store your MySQL data files (also known as datadir). The command for launching the docker image for an existing MySQL server is this:

$ docker run -d --name mysql-from-restore -v /path/to/local/datadir:/var/lib/mysql -p 3307:3306 percona/percona-server:8.0

Note that I am changing the MySQL port to 3307 since I already run a local host-based MySQL server on 3306, and you can select which version of MySQL to run – this should match the server that the restore came from.

However, all was not fine with this. docker logs shows that I was receiving the following error while starting up MySQL:

2020-04-08 15:02:42 0 [Warning] Can't create test file /var/lib/mysql/24cfb822749a.lower-test
2020-04-08 15:02:42 0 [Note] mysqld (mysqld 5.6.47-87.0) starting as process 1 ...
2020-04-08 15:02:42 1 [Warning] Can't create test file /var/lib/mysql/24cfb822749a.lower-test
2020-04-08 15:02:42 1 [Warning] Can't create test file /var/lib/mysql/24cfb822749a.lower-test
...
2020-04-08 15:02:42 7f095928a880  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2020-04-08 15:02:42 1 [ERROR] InnoDB: Cannot create ./ib_logfile101
2020-04-08 15:02:42 1 [ERROR] Plugin 'InnoDB' init function returned error.
2020-04-08 15:02:42 1 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2020-04-08 15:02:42 1 [ERROR] Unknown/unsupported storage engine: InnoDB
2020-04-08 15:02:42 1 [ERROR] Aborting

This is the classic “I don’t have permissions to write” error message from MySQL.

I had a difficult time determining what permissions I should set on this directory. Not even 777 would satisfy MySQL.

I saw a post which referenced that you can set the owner to be the number of the user that the docker host uses to run MySQL. But how do you find this out in a pre-built container? You check out the Dockerfile that is used to create that image. I found that the Dockerfile for Percona MySQL Docker Image is using ID 1001:

/bin/sh -c groupadd -g 1001
/bin/sh -c useradd -u 1001

It doesn’t matter that this user ID doesn’t exist on your host system. Simply set the owner to that user ID:

$ chown -R 1001 /path/to/local/datadir

MySQL should start right up with the correct permissions.