[Solved]-Cannot connect to MySQL docker container from container with Django app

7๐Ÿ‘

โœ…

I had to grant the root user at the Django container permissions to access the DB:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'172.17.0.3' IDENTIFIED BY 'password' WITH GRANT OPTION;
SET PASSWORD FOR root@'172.17.0.3' = PASSWORD('root');
FLUSH PRIVILEGES;

Where 172.17.0.3 is the IP of the container with the app. MYSQL_ROOT_HOST is not needed.

๐Ÿ‘คuser2233706

5๐Ÿ‘

docker run --rm -d -p 9999:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_ROOT_HOST='%' mysql/mysql-server:5.7

The important part is MYSQL_ROOT_HOST='%'

๐Ÿ‘คmax4ever

1๐Ÿ‘

This behaviour is fully documented here: (https://github.com/mysql/mysql-docker#mysql_root_host) and works as expected.
Iโ€™ll quote it:

By default, MySQL creates the โ€˜rootโ€™@โ€™localhostโ€™ command. This account
can only be connected to from inside the container, requiring the use
of the docker exec command as noted under Connect to MySQL from the
MySQL Command Line Client. To allow connections from other hosts, set
this environment variable. As an example, the value โ€œ172.17.0.1โ€,
which is the default Docker gateway IP, will allow connections from
the Docker host machine.

You can see actual .sh script which set allowed host from this env variable: https://github.com/mysql/mysql-docker/blob/mysql-server/5.7/docker-entrypoint.sh#L63-L68

๐Ÿ‘คvalignatev

1๐Ÿ‘

As @valignatev suggested, using this env variable solves an issue.

I did create container this way:

 docker run --rm -dit -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_ROOT_HOST=172.17.0.1 --name mysql_container -p 3306:3306 mysql-mysql-server

172.17.0.1 is my default docker gateway

Once container gets started I can connect from my host like this:

 mysql -h localhost -P 3306 --protocol=tcp -u root -p
๐Ÿ‘คLukasz

1๐Ÿ‘

Not sure if this will be helpful but I had a similar issue and got it to work by adding MYSQL_ROOT_HOST=%
This is what my docker-compose looks like for the db:

mysql:
  platform: linux/x86_64
  image: mysql
  environment:
    - MYSQL_ROOT_HOST=%
    - MYSQL_ROOT_PASSWORD=foobar123
    - MYSQL_USER=test_user
    - MYSQL_PASSWORD=foobar123
  volumes:
    - ./init:/docker-entrypoint-initdb.d
  ports:
    - 3306:3306
  container_name: "mysql"

Source documentation: https://dev.mysql.com/doc/refman/8.0/en/docker-mysql-more-topics.html#docker_var_mysql-root-host

๐Ÿ‘คMuizz Zafar

Leave a comment