Ошибка Docker-Compose при создании файла Dockerfile Django: Ошибка -2 при подключении к redis:6379. Имя или служба неизвестны
Я пытаюсь настроить приложение status page с открытым исходным кодом, используя репозиторий из Status-Page/Status-Page с помощью Docker Compose. Когда я запускаю docker-compose up -d, я сталкиваюсь с ошибкой в процессе сборки файла Dockerfile службы Django. Похоже, ошибка возникает при обновлении и инициализации приложения, но я не уверен, как ее отладить или устранить. Вот мои настройки:
Файл настройки:
# Use the official Python runtime image
FROM python:3.12.3
# Create the app directory
RUN mkdir -p /opt/status-page/
# Set the working directory inside the container
WORKDIR /opt/status-page/
# Set environment variables
# Prevents Python from writing pyc files to disk
ENV PYTHONDONTWRITEBYTECODE=1
# Prevents Python from buffering stdout and stderr
ENV PYTHONUNBUFFERED=1
# Install system dependencies
RUN apt-get update && apt install -y libpq-dev gcc
# Create a system user and group
RUN adduser --system --group status-page
# Set ownership of the app directory
RUN chown -R status-page:status-page /opt/status-page/
# Upgrade pip
RUN pip install --upgrade pip
# Copy the Django project to the container
ADD status-page /opt/status-page/
# Grant execute permissions to upgrade.sh
RUN chmod +x /opt/status-page/upgrade.sh
# Install Python dependencies
RUN python -m venv /opt/status-page/venv \
&& /opt/status-page/venv/bin/pip install --no-cache-dir -r requirements.txt
# Upgrade and initialize application
RUN /opt/status-page/upgrade.sh
RUN /opt/status-page/venv/bin/python /opt/status-page/statuspage/manage.py migrate
RUN /opt/status-page/venv/bin/python /opt/status-page/statuspage/manage.py createsuperuser --noinput
# Copy Gunicorn and systemd service files
RUN cp /opt/status-page/contrib/gunicorn.py /opt/status-page/gunicorn.py \
&& cp -v /opt/status-page/contrib/*.service /etc/systemd/system/ \
&& systemctl daemon-reload
# Expose the Django port
EXPOSE 8000
# Start Gunicorn
CMD ["/opt/status-page/venv/bin/gunicorn", "-c", "/opt/status-page/gunicorn.py", "statuspage.wsgi:application"]
docker-compose.yml:
version: '3.9'
services:
# PostgreSQL service
db:
image: postgres:15
container_name: status-page-db
environment:
POSTGRES_USER: status-page
POSTGRES_PASSWORD: abcdefgh123456
POSTGRES_DB: status-page
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U status-page -d status-page"]
interval: 10s
timeout: 5s
retries: 5
networks:
- status_page_network
# Redis service
redis:
image: redis:6
container_name: status-page-redis
ports:
- "6379:6379"
hostname: redis_host
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
networks:
- status_page_network
# Django (Status-Page) service
django:
build: ./statuspage
container_name: status-page-django
environment:
DATABASE_NAME: status-page
DATABASE_USER: status-page
DATABASE_PASSWORD: abcdefgh123456
DATABASE_HOST: db
REDIS_HOST: redis_host
REDIS_PORT: 6379
SECRET_KEY: Pv)hkWbYxkpaD_dh$ULGa6MF#ADn6&=MU&#v5cjRyViuTbPHuG
volumes:
- ./status-page:/opt/status-page
- status-page-venv:/opt/status-page/venv
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
expose:
- "8000"
command: /opt/status-page/venv/bin/gunicorn -c /opt/status-page/gunicorn.py statuspage.wsgi:application
networks:
- status_page_network
# Nginx service
nginx:
image: nginx:latest
container_name: status-page-nginx
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./status-page/static:/usr/share/nginx/html/static
ports:
- "80:80"
- "443:443"
depends_on:
- django
networks:
- status_page_network
environment:
- NGINX_HOST=status-page.example.com
- NGINX_PORT=80
volumes:
postgres_data:
status-page-venv:
networks:
status_page_network:
driver: bridge
Конфигурация (фрагмент):
ALLOWED_HOSTS = ['*']
# PostgreSQL database configuration. See the Django documentation for a complete list of available parameters:
# https://docs.djangoproject.com/en/stable/ref/settings/#databases
DATABASE = {
'NAME': 'status-page', # Database name
'USER': 'status-page', # PostgreSQL username
'PASSWORD': 'abcdefgh123456', # PostgreSQL password
'HOST': 'db', # Database server
'PORT': '5432', # Database port (leave blank for default)
'CONN_MAX_AGE': 300, # Max database connection age
}
# Redis database settings. Redis is used for caching and for queuing background tasks. A separate configuration exists
# for each. Full connection details are required.
REDIS = {
'tasks': {
'HOST': 'redis_host',
'PORT': 6379,
# Comment out `HOST` and `PORT` lines and uncomment the following if using Redis Sentinel
# 'SENTINELS': [('mysentinel.redis.example.com', 6379)],
# 'SENTINEL_SERVICE': 'status-page',
'PASSWORD': '',
'DATABASE': 0,
'SSL': False,
# Set this to True to skip TLS certificate verification
# This can expose the connection to attacks, be careful
# 'INSECURE_SKIP_TLS_VERIFY': False,
},
'caching': {
'HOST': 'redis_host',
'PORT': 6379,
# Comment out `HOST` and `PORT` lines and uncomment the following if using Redis Sentinel
# 'SENTINELS': [('mysentinel.redis.example.com', 6379)],
# 'SENTINEL_SERVICE': 'netbox',
'PASSWORD': '',
'DATABASE': 1,
'SSL': False,
# Set this to True to skip TLS certificate verification
# This can expose the connection to attacks, be careful
# 'INSECURE_SKIP_TLS_VERIFY': False,
}
}
Проблема: redis.исключения.Ошибка подключения: Ошибка -2 при подключении к redis:6379. Имя или служба неизвестны.
Что я пробовал:
- Я обновил DATABASE_HOST до db в переменных среды docker-compose.yml, чтобы они соответствовали имени службы.
- Я подтвердил, что условия depends_on с service_healthy установлены для db и redis, но они применяются только во время выполнения, а не во время сборки.
Как это решить?