Django +docker-compose + Celery + redis - 如何使用部署在自己远程服务器上的Redis?

Django +docker-compose + Celery + redis - How to use Redis deployed in my own remote server?

我在 Docker 个容器中部署了一个 Django 应用程序。

我有 3 个配置环境:dev、preprod 和 prod。 dev 是我的本地环境 (localhost),preprod/prod 是远程 linux 环境。 它在使用“public”Redis 服务器和标准配置时有效。

但我需要使用我们自己的 Redis 部署在远程服务器 (192.168.xx.xx) 的 Docker 容器中,名称为容器 redis_cont.

而且我真的不知道如何配置。不知可否? 我将不胜感激。

docker-撰写

version: '3.7'

services:
    web:
        restart: always
        build: 
            context: ./app
            dockerfile: Dockerfile.dev
        restart: always
        command: python manage.py runserver 0.0.0.0:8000
        volumes:
            - ./app:/usr/src/app
        ports:
            - 8000:8000
        env_file:
            - ./.env.dev
        entrypoint: [ "/usr/src/app/entrypoint.dev.sh" ]
        depends_on: 
            - redis
        healthcheck:
            test: ["CMD", "curl", "-f", "http://localhost:8000/"]
            interval: 30s
            timeout: 10s
            retries: 50
    redis:
        container_name: redis_cont          <= container running in remote linux server
        image: "redis:alpine"
    celery:
        build: 
            context: ./app
            dockerfile: Dockerfile.dev
        command: celery -A core worker -l info
        volumes:
            - ./app:/usr/src/app
        env_file:
            - ./.env.dev
        depends_on:
            - web
            - redis
    celery-beat:
        build: 
            context: ./app
            dockerfile: Dockerfile.dev
        command: celery -A core beat -l info
        volumes:
            - ./app:/usr/src/app
        env_file:
            - ./.env.dev
        depends_on:
            - web
            - redis

settings.py

CELERY_BROKER_URL = 'redis://redis:6379'
CELERY_RESULT_BACKEND = 'redis://redis:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_BEAT_SCHEDULE = {
    'hello': {
        'task': 'project.tasks.hello',
        'schedule': crontab()  # execute every minute
    },
}

由于容器不是通过相同的 docker-compose 创建的,因此它们不会共享相同的网络。 redis_cont docker-compose.

的隔离网络中内置的服务不存在

如果 Redis 容器在远程发布并且可以使用 ip:port 访问,您应该可以直接在 settings.py 中使用它。无需在撰写文件中添加新服务。


备注

要在同一个 docker-compose 中的服务之间建立通信,您应该使用 service 名称(webcelery-beat 等你的情况)而不是容器名称。