How to fix "Host '172.18.0.1' is not allowed to connect" with MySQL Docker

Using the official MySQL Docker image from Docker Hub, I recently ran into the error:

Host '172.18.0.1' is not allowed to connect to this MySQL server

The only change I had made to my docker-compose.yml file was:

mysql:
  image: mysql:5.6
  ports:
    - '3306'
  volumes:
    # Use this option to persist the MySQL DBs in a shared volume.
    - ./mysqldata:/var/lib/mysql:rw,delegated
    # Use this option to persist the MySQL DBs in a data volume.
    # - db_data:/var/lib/mysql

I switched from using a data volume (db_data) to mounting a volume from my host (mysqldata in the current directory), and after the next time I did a docker-compose down and docker-compose up, I started seeing the error about my host not being allowed to connect to the MySQL server.

I'm not 100% sure why a data volume works, while a shared volume doesn't, but the fix is to make sure you clear out the contents of the shared directory between rebuilds of the Docker environment. See this comment in the MySQL image's GitHub issue queue for more details.

Comments

Thanks for posting this, you just saved my sanity! Spent a few hours trying to understand why mounting with an canonical path wasn't working. As soon as I hooked up using ~ with a linked directory pointing to the exact same location it worked!

You are a life saver, Do you know how much time I wasted to find what is wrong with my docker-compose file. It worked yesterday but wasn't working today. Then I see your comment and fixed it.

Thank you so much, after 2 hours struggling with this issue I finally fixed it by your suggestion. You saved me.

You saved me countless hours. I'm very grateful to you.

The problem comes from default configuration of newer mysql versions.

Using ./mysqldata hosted as directory on your "host" for sure works but making a mysql in general much slower. (it may be not issue depends on case)

Solution to this problem is to setup proper environment values:
environment:
MYSQL_ROOT_HOST: '%'

To make those changes working you first has to remove you existing volume `db_data` you have commented:

easiest way to detect it real name would be to run:

docker volume ls | grep db_data
docke volume rm full_name_db_data

And now fresh mysql should be able accept connections from any host