Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to MySQL docker container from container with Django app

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",
like image 855
user2233706 Avatar asked Nov 27 '16 03:11

user2233706


2 Answers

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='%'

like image 129
max4ever Avatar answered Sep 30 '22 06:09

max4ever


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.

like image 36
user2233706 Avatar answered Sep 30 '22 07:09

user2233706