Django Каналы, как установить redis docker ip контейнера в качестве хоста - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь следовать руководству по адресу https://channels.readthedocs.io/en/latest/tutorial/part_2.htm

Я использую docker -compose для запуска сервера redis, необходимого для Django каналов, в отличие от простого docker команда. Однако я не уверен, как установить IP-адрес в:

    CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.2', 6379)],
        },
    },
}

на адрес контейнера redis.

в моем docker-compose.yml:

   redis:
    image: "redis:alpine"

    command: redis-server --requirepass letmein

    ports:
     - "6379:6379"

    volumes:
      - ./redis.conf:/usr/local/etc/redis/redis.conf


    environment:
     - REDIS_REPLICATION_MODE=master

    networks:
      node_net:
        ipv4_address: 127.0.0.2

networks:
  node_net:
    ipam:
      driver: default
      config:
        - subnet: 127.0.0.0/16

Когда я пытаюсь проверить соединение с:

async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})

, я получаю следующее:

    Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 120, in __call__
    return call_result.result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 425, in result
    return self.__get_result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 180, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 299, in send
    async with self.connection(index) as connection:
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 835, in __aenter__
    self.conn = await self.pool.pop()
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 73, in pop
    conns.append(await aioredis.create_redis(**self.host, loop=loop))
  File "/usr/local/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 175, in create_redis
    loop=loop)
  File "/usr/local/lib/python3.6/site-packages/aioredis/connection.py", line 113, in create_connection
    timeout)
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for
    return (yield from fut)
  File "/usr/local/lib/python3.6/site-packages/aioredis/stream.py", line 24, in open_connection
    lambda: protocol, host, port, **kwds)
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 794, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 781, in create_connection
    yield from self.sock_connect(sock, address)
  File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 439, in sock_connect
    return (yield from fut)
  File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 469, in _sock_connect_cb
    raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.2', 6379)

Я понимаю, что пространства имен IP-адресов различаются между контейнерами, поэтому как мне получить доступ к 127.0.0.2:6379 в контейнере redis?

Совет доступен по адресу: Docker [Errno 111] Ошибка вызова Connect ('127.0.0.1', 6379)

предлагает изменить 127.0.0.1:6379 на redis:6379, но это довольно неоднозначно, и изменить его непосредственно в settings.py т.е.:

    CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('redis', 6379)],
        },
    },
}

приводит к: `

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 120, in __call__
    return call_result.result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 425, in result
    return self.__get_result()
  File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 180, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 299, in send
    async with self.connection(index) as connection:
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 835, in __aenter__
    self.conn = await self.pool.pop()
  File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 73, in pop
    conns.append(await aioredis.create_redis(**self.host, loop=loop))
  File "/usr/local/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 175, in create_redis
    loop=loop)
  File "/usr/local/lib/python3.6/site-packages/aioredis/connection.py", line 113, in create_connection
    timeout)
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for
    return (yield from fut)
  File "/usr/local/lib/python3.6/site-packages/aioredis/stream.py", line 24, in open_connection
    lambda: protocol, host, port, **kwds)
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 750, in create_connection
    infos = f1.result()
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known`

Итак, я прошу вас о помощи, любых предложениях, заранее спасибо :)

...