如何将我的 docker Django 实例连接到我的 docker mysql 实例?

Posted

技术标签:

【中文标题】如何将我的 docker Django 实例连接到我的 docker mysql 实例?【英文标题】:How do I connect my docker Django instance to my docker mysql instance? 【发布时间】:2020-06-02 17:51:40 【问题描述】:

我在 Mac High Sierra 上运行 Docker。我想运行 Docker 容器来容纳我的 Django 实例和 mysql 实例。我有以下 docker-compose.yml 文件...

version: '3'

services:
  web:
    restart: always
    build: ./web
    ports:           # to access the container from outside
      - "8000:8000"
    env_file: .env
    environment:
      DEBUG: 'true'
    command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000

  apache:
    restart: always
    build: ./apache/
    ports:
      - "80:80"
    #volumes:
    #  - web-static:/www/static
    links:
      - web:web

  mysql:
    restart: always
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: 'maps_data'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'chicommons'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3406:3406"
    volumes:
      - my-db:/var/lib/mysql

volumes:
  my-db:

我设置的“.env”文件是这样的……

DB_NAME=maps_data
DB_USER=chicommons
DB_PASS=password
DB_SERVICE=mysql
DB_PORT=3406

在我的 web (Django) 实例中,我已经设置了我的 settings.py db ...

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_SERVICE'],
        'PORT': os.environ['DB_PORT']
    

但是,当我运行“docker-compose up”时,我收到以下错误,抱怨无法连接到数据库...

web_1     | Traceback (most recent call last):
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")
web_1     | 
web_1     | The above exception was the direct cause of the following exception:
web_1     | 
web_1     | Traceback (most recent call last):
web_1     |   File "manage.py", line 21, in <module>
web_1     |     main()
web_1     |   File "manage.py", line 17, in main
web_1     |     execute_from_command_line(sys.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
web_1     |     utility.execute()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
web_1     |     self.fetch_command(subcommand).run_from_argv(self.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
web_1     |     self.execute(*args, **cmd_options)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 332, in execute
web_1     |     self.check()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check
web_1     |     include_deployment_checks=include_deployment_checks,
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks
web_1     |     return checks.run_checks(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks
web_1     |     new_errors = check(app_configs=app_configs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
web_1     |     errors.extend(model.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1200, in check
web_1     |     errors.extend(cls._check_fields(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1272, in _check_fields
web_1     |     errors.extend(field.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 894, in check
web_1     |     errors = super().check(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 206, in check
web_1     |     errors.extend(self._check_backend_specific_checks(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 303, in _check_backend_specific_checks
web_1     |     return connections[db].validation.check_field(self, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/validation.py", line 21, in check_field
web_1     |     field_type = field.db_type(self.connection)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 648, in db_type
web_1     |     return connection.data_types[self.get_internal_type()] % data
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 133, in data_types
web_1     |     if self.features.supports_microsecond_precision:
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/features.py", line 65, in supports_microsecond_precision
web_1     |     return self.connection.mysql_version >= (5, 6, 4)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 345, in mysql_version
web_1     |     with self.temporary_connection() as cursor:
web_1     |   File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
web_1     |     return next(self.gen)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 576, in temporary_connection
web_1     |     cursor = self.cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 255, in cursor
web_1     |     return self._cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 232, in _cursor
web_1     |     self.ensure_connection()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
web_1     |     raise dj_exc_value.with_traceback(traceback) from exc_value
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")

发生了什么事?如何让我的 Django web docker 实例连接到我的 MySql docker 实例?

【问题讨论】:

你找到解决办法了吗? 【参考方案1】:

要使用数据库和其他服务,容器到容器,请参阅links。

您弄错了:“3406:3406”。第一个端口是主机端口,第二个端口是容器内运行的服务,所以mysql运行在3306上,所以你要改成“3406:3306”。

如果你有不同的服务运行,比如后端/前端,你应该在容器之间创建networks。

【讨论】:

【参考方案2】:

可能是端口错误

version: '3'

services:
  web:
    ...
    links:  # <-- add this
      - mysql # <-- add this

  apache:
    ...

  mysql:
    ...
    ports:  # <-- add this
      - "3406:3306" # <-- change myslq port inside is 3306 not 3406


volumes:
  my-db:

【讨论】:

有趣的是,我将端口保留为“3406:3406”,但将我的 settings.py 连接器代码中的端口更改为 3306,一切正常。我还使用了“depends_on”而不是“链接”,不知道它贡献了多少。

以上是关于如何将我的 docker Django 实例连接到我的 docker mysql 实例?的主要内容,如果未能解决你的问题,请参考以下文章

Django 不会连接到 Redis Docker 容器

如何使用 Windows 将我的 Django 项目连接到 MySql?

如何将我的 docker 连接到远程数据库?

如何将我的 Django 项目中的 jupyter-lab 连接到 Django 的模型?

如何将我的 Spring Boot 应用程序连接到 Docker 上的 Redis 容器?

如何将Django ORM连接到mongo atlas?