使用Python连接到Redis集群(在Docker中)

时间:2019-08-29 07:28:57

标签: python docker docker-compose redis-cluster

我正在设置一个高度可用的Redis集群(带有Sentinels),并且需要用Python向其中写入数据。但是,我不知道从Python连接时要使用哪个主机名,而且我还会收到“连接被拒绝”的信息。

我的Dockerfile:

05/24/2019  04:33 PM               582

docker-compose.yml

public enum Car {
    SWIFT(Company.MARUTI),
    DZIRE(Company.MARUTI),
    CIAZ(Company.MARUTI),
    I10(Company.HYUNDAI),
    CRETA(Company.HYUNDAI);

    Company company;

    Cars(Company company) {
        this.company = company;
    }
}

public enum Company {
    HYUNDAI("Hyundai"),
    MARUTI("Maruti");

    String name;

    Company(String name) {
        this.name = name;
    }
}

我要运行的Python代码:

FROM redis:latest
ADD sentinel.conf /etc/redis/sentinel.conf
RUN chown redis:redis /etc/redis/sentinel.conf
ENV SENTINEL_QUORUM 2
RUN mkdir app
WORKDIR /app
ENV SENTINEL_DOWN_AFTER 5000
ENV SENTINEL_FAILOVER 10000
ENV SENTINEL_PORT 26000
ADD entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 26379 6379

FROM python:2.7-slim
WORKDIR /app
COPY . /app
RUN pip install --trusted-host pypi.python.org -r requirements.txt
CMD ["python", "app.py"]

错误:

ervices:

  redis-master:
    container_name: redis-master
    image: redis:latest
    command: redis-server --port 6379
    ports:
      - "6379:6379"
    volumes:
      - .:/app

  redis-slave:
    container_name: redis-slave
    image: redis:latest
    command: redis-server --slaveof redis-master 6379 --protected-mode no
    volumes:
       - .:/app

  sentinel-1:
    container_name: sentinel-1
    build: sentinel
    environment:
      - SENTINEL_DOWN_AFTER=5000
      - SENTINEL_FAILOVER=5000

  sentinel-2:
    container_name: sentinel-2
    build: sentinel
    environment:
      - SENTINEL_DOWN_AFTER=5000
      - SENTINEL_FAILOVER=5000

  sentinel-3:
    container_name: sentinel-3
    build: sentinel
    environment:
      - SENTINEL_DOWN_AFTER=5000
      - SENTINEL_FAILOVER=5000

我尝试将主机更改为redis,redis-master,实际的Docker IP,其中一些未找到,但仍然拒绝连接。

我已经创建了一个网络,但随后Sentinels无法相互通信。

我也尝试过使用配置文件启动Redis master,但是错误是找不到它。为此,我确实将WORKDIR和COPY添加到Dockerfile中。

如何从Python(也在Docker内部)连接到Redis?

感谢您的宝贵时间,我们将为您提供任何建议。

1 个答案:

答案 0 :(得分:1)

从同一文件pythoncontainer中的compose连接:

r = redis.StrictRedis(host='redis-master', port=6379, db=0)

所以您需要使用service名称

如果Python Container不是来自同一compose file,则您需要使用来自Redis network的{​​{1}}进行连接,并将其声明为compose在您的python撰写文件中

external的示例:

docker run

docker run -itd --network=MyNetworkFromTheOtherCompose busybox 的示例:

compose