本文介绍了MySQL未连接Docker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在实时服务器上连接mysql docker容器,但无法正常工作
I am trying to connect mysql docker container on live server but Its not working
我的docker-compose文件为
db:
image: mysql:5.7
restart: always
env_file:
- ./app/app/.env
volumes:
- ./mysql-data:/var/lib/mysql
ports:
- "3302:3306"
,我的环境文件就像
MYSQL_PORT=3306
MYSQL_DATABASE=mydb
MYSQL_USER=root
MYSQL_PASSWORD=root
MYSQL_ROOT_PASSWORD=root
和我的Django settings.py是
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': mydb,
'USER': root,
'PASSWORD': root,
'HOST': db,
'PORT': 3306,
}
}
和 gitlab CI上的错误日志是
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
self.connect()
File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection
return Database.connect(**conn_params)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 130, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
推荐答案
在docker-compose文件中,您将端口3306映射到了3302。
In your docker-compose file, you mapped the port 3306 to 3302.
这意味着您的数据库正在3306(在环境文件中配置)中进行侦听,但是从容器外部,此端口重定向到端口3302。
您的Django应该连接到您的d数据库在端口 3302 上,例如 setting.py如下:
Your Django should connect to your database on port 3302, example "setting.py" is below:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': mydb,
'USER': root,
'PASSWORD': root,
'HOST': db,
'PORT': 3302,
}
}
这篇关于MySQL未连接Docker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!