When I try to connect from a docker container running my Django app to a container running MySQL, I get the following error:
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.17.0.2' (111)")
Here's how I'm running the MySQL container:
$ docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=testdb -e MYSQL_ROOT_HOST=172.17.0.2 -d mysql/mysql-server:5.7
If I don't specify MYSQL_ROOT_HOST
, I get this error when I try to connect from the container with the Django app:
django.db.utils.OperationalError: (1130, "Host '172.17.0.3' is not allowed to connect to this MySQL server")
Here are my Django settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdb',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '172.17.0.2',
'PORT': '',
}
}
I've verified the MySQL container is using IP 172.17.0.2:
$ docker inspect mysql |grep -i ipaddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
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='%'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With