django.db.utils.OperationalError: (1130, "192.168.1.66' is not allowed to connect to this MySQL server")
当我尝试从运行我的Django应用程序的docker容器连接到运行MySQL的容器时,我收到以下错误:
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.17.0.2' (111)")
这是我运行MySQL容器的方式:
$ 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
如果我没有指定MYSQL_ROOT_HOST
,当我尝试从容器与Django应用程序连接时出现此错误:
django.db.utils.OperationalError: (1130, "Host '172.17.0.3' is not allowed to connect to this MySQL server")
这是我的Django设置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdb',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '172.17.0.2',
'PORT': '',
}
}
我已经验证MySQL容器使用的是IP 172.17.0.2:
$ docker inspect mysql |grep -i ipaddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
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",
更新时间:2022-04-25 22:04
最满意答案
我必须授予Django容器权限的root用户访问数据库:
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;
其中172.17.0.3
是带有app的容器的IP。 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.