Как мне подключить мой экземпляр docker Django к моему экземпляру docker mysql? - PullRequest
1 голос
/ 18 февраля 2020

Я бегу Docker на Ма c Высокая Сьерра. Я хочу запустить контейнер 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 экземпляру?

Ответы [ 2 ]

1 голос
/ 19 февраля 2020

Возможно ошибка порта

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:
0 голосов
/ 19 февраля 2020

Чтобы использовать базы данных и другие службы, от контейнера к контейнеру, см. ссылки .

Вы допустили ошибку: «3406: 3406». Первый порт является портом хоста, а второй порт является службой, которая работает внутри контейнера, поэтому mysql работает на 3306, поэтому вам нужно изменить на «3406: 3306».

Если у вас есть различные сервисы, работающие как backend / frontend, должны создавать сетей между контейнерами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...