Я пытаюсь запустить контейнер Docker, используя проект Django в том же каталоге.

Следуя этому руководству, https://docs.docker.com/compose/django/#create-a-django-project, можно использовать

docker-compose run web django-admin startproject newproject .

запустить проект из контейнера докера, определенного в docker-compose.yml

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    #command: python3 manage.py runserver 0.0.0.0:8000
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn things.wsgi -b 0.0.0.0:8000"
    volumes:
      - .:/code
    expose:
      - "8000"
    depends_on:
      - db
  nginx:
    image: nginx:latest
    container_name: NGINXDOCKERNAME
    ports:
      - "8000:8000"
    volumes:
      - .:/code
      - ./config/nginx:/etc/nginx/conf.d
    ports:
      - "8000:8000"
    depends_on:
      - web

и докерфайл

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
VOLUME /code

Как вы используете django-admin startproject newproject. извне контейнера (т.е. из командной строки docker-machine), а затем скопировать проект в контейнер?

Теперь, если я запускаю проект внутри контейнера, сервер запускается, и я вижу свой проект на правильном порту, но если я запускаю проект за пределами контейнера (но в том же каталоге локально), контейнеры web и nginx запускаются некорректно.

Я использую докер-машину на Windows 10 версии 1709.

Ниже приведен вывод при запуске веб-контейнера, за которым следует вывод сервера по запросу.

Cheers Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/init.py", line 130, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.19.0.2) and accepting web_1 | TCP/IP connections on port 5432? web_1 | 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 22, in web_1 | execute_from_command_line(sys.argv) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 364, in execute_from_command_line web_1 | utility.execute() web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 356, in execute web_1 | self.fetch_command(subcommand).run_from_argv(self.argv) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv web_1 | self.execute(*args, **cmd_options) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute web_1 | output = self.handle(*args, **options) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle web_1 | loader.check_consistent_history(connection) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history web_1 | applied = recorder.applied_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations web_1 | self.ensure_schema() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor web_1 | return self._cursor() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor web_1 | self.ensure_connection() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in exit web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback) web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise web_1 | raise value.with_traceback(tb) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/init.py", line 130, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.19.0.2) and accepting web_1 | TCP/IP connections on port 5432?

Выход сервера

NGINXDOCKERNAME | 2017/11/21 19:56:28 [error] 5#5: *1 connect() failed (113: No route to host) while connecting to upstream, client: 192.168.99.1, server: localhost, request: "GET /polls/ HTTP/1.1", upstream: "http://172.19.0.3:8000/polls/", host: "192.168.99.100:8000"

1 ответ1

0

Ответ на ваш вопрос можно найти в https://docs.docker.com/compose/django/#connect-the-database. Если вы на самом деле настроили свою базу данных, как описано в ссылке, так, чтобы ваша конфигурация DATABASE стала:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

Я уверен, что у вас не будет никаких проблем.

Еще вы можете установить listen_addresses = '*' используя vim. Попробуйте эту ссылку http://www.mozmorris.com/2011/11/15/configure-postgresql-to-accept-tcpip-connections.html для получения дополнительной информации об этом

Всё ещё ищете ответ? Посмотрите другие вопросы с метками .