django Redis主机名的Python问题未在Docker中解决

c3frrgcw  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(127)

我似乎在尝试通过python/django设置redis示例时遇到了问题。我有很多容器在docker-compose中运行,而其他容器能够正确连接,当尝试使用Django时,我得到:

Step 11/16 : RUN python3 /home/allianceserver/myauth/manage.py collectstatic
 ---> Running in 749d9931dadb
[30/Oct/2023 08:59:47] INFO [allianceauth.eveonline.providers:181] ESI client will be loaded on-demand
[30/Oct/2023 08:59:47] ERROR [allianceauth.authentication.task_statistics.helpers:44] Failed to establish a connection with Redis. This EventSeries object is disabled.
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 264, in connect
    sock = self.retry.call_with_retry(
  File "/usr/local/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry
    return do()
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 265, in <lambda>
    lambda: self._connect(), lambda error: self.disconnect(error)
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 595, in _connect
    for res in socket.getaddrinfo(
  File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 41, in get_redis_client_or_stub
    if not redis.ping():
  File "/usr/local/lib/python3.9/site-packages/redis/commands/core.py", line 1216, in ping
    return self.execute_command("PING", **kwargs)
  File "/usr/local/lib/python3.9/site-packages/redis/client.py", line 533, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 1086, in get_connection
    connection.connect()
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 270, in connect
    raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error -2 connecting to cache:6379. Name or service not known.
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 264, in connect
    sock = self.retry.call_with_retry(
  File "/usr/local/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry
    return do()
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 265, in <lambda>
    lambda: self._connect(), lambda error: self.disconnect(error)
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 595, in _connect
    for res in socket.getaddrinfo(
  File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 41, in get_redis_client_or_stub
    if not redis.ping():
  File "/usr/local/lib/python3.9/site-packages/redis/commands/core.py", line 1216, in ping
    return self.execute_command("PING", **kwargs)
  File "/usr/local/lib/python3.9/site-packages/redis/client.py", line 533, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 1086, in get_connection
    connection.connect()
  File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 270, in connect
    raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error -2 connecting to cache:6379. Name or service not known.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/allianceserver/myauth/manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute
    django.setup()
  File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 124, in populate
    app_config.ready()
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/apps.py", line 11, in ready
    from allianceauth.authentication.task_statistics import (
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/signals.py", line 9, in <module>
    from .counters import failed_tasks, retried_tasks, succeeded_tasks
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/counters.py", line 9, in <module>
    succeeded_tasks = EventSeries("SUCCEEDED_TASKS")
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/event_series.py", line 21, in __init__
    self._redis = get_redis_client_or_stub() if not redis else redis
  File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 44, in get_redis_client_or_stub
    logger.exception(
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1481, in exception
    self.error(msg, *args, exc_info=exc_info, **kwargs)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1475, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1589, in _log
    self.handle(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1599, in handle
    self.callHandlers(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1661, in callHandlers
    hdlr.handle(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 952, in handle
    self.emit(record)
  File "/usr/local/lib/python3.9/site-packages/allianceauth/notifications/handlers.py", line 14, in emit
    perm = Permission.objects.get(codename="logging_notifications")
  File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 492, in get
    num = len(clone)
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 302, in __len__
    self._fetch_all()
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1507, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(
  File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1359, in execute_sql
    cursor = self.connection.cursor()
  File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 284, in cursor
    return self._cursor()
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in _cursor
    self.ensure_connection()
  File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 224, in connect
    conn_params = self.get_connection_params()
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 215, in get_connection_params
    if settings_dict["HOST"].startswith("/"):
AttributeError: 'NoneType' object has no attribute 'startswith'

字符串
所以我试着改变redis容器的名称,看看它是否有帮助,我已经检查了网络存在,其他容器也可以连接没有任何问题。

redis:
    image: redis:6
    hostname: redis
    networks:
      - redis
    ports:
      - 6379:6379
    expose:
      - "6379"
    container_name: redis
    restart: always
    command: ["--databases", "1"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    volumes:
      - '$USERDIR/docker/owncloud/redis:/data'
allianceauth:
    hostname: "allianceauth"
    env_file:
      - .env
    container_name: allianceuath
    build: allianceauth/.
    ports:
      - '$ALLIANCE_AUTH_PORT:5555'
    volumes:
      - '$USERDIR/docker/allianceauth/conf/local.py:/home/allianceserver/myauth/myauth/settings/local.py'
      - '$USERDIR/docker/allianceauth/templates:/home/allianceserver/myauth/myauth/templates/'
      - '$USERDIR/docker/allianceauth/static-volume:/var/www/myauth/static'
    depends_on:
      - redis
    networks:
      - t2_proxy
      - redis
      - database
    restart: always

的数据
网络:

redis:
    driver: bridge


配置文件:

## Every setting in base.py can be overloaded by redefining it here.
from .base import *

import os
from dotenv import load_dotenv

load_dotenv()

# Django App Secretkey change if you want
SECRET_KEY = 'secret'

# Change this to change the name of the auth site
SITE_NAME = 'Alliance Auth'

DEBUG = False
# Add any additional apps to this list. Pre-Populated with some Apps
#INSTALLED_APPS += [
#'allianceauth.services.modules.discord',
#'allianceauth.services.modules.teamspeak3',
#]
# Teamspeak3 Configuration
TEAMSPEAK3_SERVER_IP = '127.0.0.1'
TEAMSPEAK3_SERVER_PORT = 10011
TEAMSPEAK3_SERVERQUERY_USER = 'serveradmin'
TEAMSPEAK3_SERVERQUERY_PASSWORD = ''
TEAMSPEAK3_VIRTUAL_SERVER = 1
TEAMSPEAK3_PUBLIC_URL = ''

CELERYBEAT_SCHEDULE['run_ts3_group_update'] = {
    'task': 'allianceauth.services.modules.teamspeak3.tasks.run_ts3_group_update',
    'schedule': crontab(minute='*/30'),
}
# Discourse Configuration
DISCOURSE_URL = ''
DISCOURSE_API_USERNAME = ''
DISCOURSE_API_KEY = ''
DISCOURSE_SSO_SECRET = ''

# SMF Configuration
SMF_URL = ''
DATABASES['smf'] = {Auth
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'alliance_smf',
    'USER':  os.getenv('ALLIANCE_AUTH_USER'),
    'PASSWORD':  os.getenv('ALLIANCE_AUTH_PASSWORD'),
    'HOST':  os.getenv('MYSQL_HOST'),
    'PORT': '3306',
}
#### ADD YOUR OWN LOCAL DATABASE DETAILS HERE
DATABASES['default'] = {
    'ENGINE': 'django.db.backends.mysql',
    'NAME':  os.getenv('ALLIANCE_AUTH_DATABASE'),
    'USER':  os.getenv('ALLIANCE_AUTH_USER'),
    'PASSWORD':  os.getenv('ALLIANCE_AUTH_PASSWORD'),
    'HOST':  os.getenv('MYSQL_HOST'),
    'PORT': '3306',
}

ESI_SSO_CLIENT_ID =  os.getenv('CCP_SSO_CLIENT_ID')
ESI_SSO_CLIENT_SECRET =  os.getenv('CCP_SSO_SECRET_KEY')
ESI_SSO_CALLBACK_URL = ''

VERIFY_EMAIL = False
EMAIL_HOST =  os.getenv('SMTP_HOST')
EMAIL_PORT =  os.getenv('SMTP_PORT')
EMAIL_HOST_USER =  os.getenv('SMTP_USER')
EMAIL_HOST_PASSWORD =  os.getenv('SMTP_PASSWORD')
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL =  os.getenv('SMTP_FROM')
#######################################
# Add any custom settings below here. #
#######################################

ROOT_URLCONF = ''
WSGI_APPLICATION = 'myauth.wsgi.application'
STATIC_ROOT = "/var/www/myauth/static/"
BROKER_URL = 'redis://redis:6379/0'
CELERY_RESULT_BACKEND = 'redis://redis:6379/0'
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://redis:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
docker network inspect docker_redis
[
    {
        "Name": "docker_redis",
        "Id": "7102a8377a62cdd6f976d8ffa74b32bf4c24b7466591e48afef921d1bb8b4f23",
        "Created": "2023-10-28T19:29:31.165029181Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.23.0.0/16",
                    "Gateway": "172.23.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "ac4128ce849b8cf3f95aeb4d355ef1d6f54df8f3af5670722869472ec8b33ff4": {
                "Name": "redis",
                "EndpointID": "7248959b6f37bd1e94378d333f6e0ac06cf63485716456d43c11506f01c21742",
                "MacAddress": "02:42:ac:17:00:02",
                "IPv4Address": "172.23.0.2/16",
                "IPv6Address": ""
            },
            "dc1202a1f426f9fb0d6be979c95ec208b6f34948a95c123e0d61f57593916768": {
                "Name": "owncloud_server",
                "EndpointID": "71b290e54f6fb04d14413b63d4f0dc629d34a38c3cf79b005b3602460da9635f",
                "MacAddress": "02:42:ac:17:00:03",
                "IPv4Address": "172.23.0.3/16",
                "IPv6Address": ""
            },
            "f5609ead697fccc6c5a640445165f2d2bc8885f41211f227d7a0c80b5bee5b25": {
                "Name": "pathfinder_web",
                "EndpointID": "736c5927343c80677f3b1c669eb3b62c068742e60a62281f671c45904bb434c5",
                "MacAddress": "02:42:ac:17:00:04",
                "IPv4Address": "172.23.0.4/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "redis",
            "com.docker.compose.project": "docker",
            "com.docker.compose.version": "1.25.5"
        }
    }
]
vohkndzv

vohkndzv1#

经过研究,我意识到在构建镜像时,由于Docker创建了一个临时容器来执行构建管道,因此无法建立到另一个网络的连接。解决此问题的一种方法是使用主机的IP地址连接到Redis。
尽管如此,正如大卫迷宫所指出的,探索collectstatics试图与Redis建立连接的潜在原因是很有趣的。

相关问题