我正在设置一个高度可用的 Redis 集群(使用 Sentinels),并且需要用 Python 向其中写入数据。但是,我不知道从 Python 连接时要使用哪个主机名,而且我还收到“连接被拒绝”消息。
我的 Dockerfile:
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"]
docker-compose.yml
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
我正在尝试运行的 Python 代码:
r = redis.StrictRedis(host='0.0.0.0', port=6379, db=0)
print ("set key1 123")
print (r.set('key1', '123'))
print ("get key1")
print(r.get('key1'))
错误:
Traceback (most recent call last):
File "app.py", line 7, in <module>
print (r.set('key1', '123'))
File "/usr/local/lib/python2.7/site-packages/redis/client.py", line 1519, in set
return self.execute_command('SET', *pieces)
File "/usr/local/lib/python2.7/site-packages/redis/client.py", line 836, in execute_command
conn = self.connection or pool.get_connection(command_name, **options)
File "/usr/local/lib/python2.7/site-packages/redis/connection.py", line 1071, in get_connection
connection.connect()
File "/usr/local/lib/python2.7/site-packages/redis/connection.py", line 543, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 111 connecting to 0.0.0.0:6379. Connection refused.
我已经尝试将主机更改为 redis、redis-master、实际的 Docker IP,有些地方找不到,有些仍然连接被拒绝。
我已经创建了一个网络,但是 Sentinels 无法相互通信。
我也试过用配置文件启动Redis master,但是报错是找不到。为此,我确实将 WORKDIR 和 COPY 添加到 Dockerfile。
如何从 Python(也在 Docker 中)连接到 Redis?
感谢您抽出宝贵时间,我们将不胜感激。
最佳答案
从同一 compose
文件中的 container
中的 python
进行连接:
r = redis.StrictRedis(host='redis-master', port=6379, db=0)
所以你需要使用服务
名称
如果 Python
Container
不是来自同一个 compose 文件
,您需要使用 网络
连接它> 来自 redis compose
并在你的 python compose 文件中将其声明为 external
docker run
示例:
docker run -itd --network=MyNetworkFromTheOtherCompose busybox
compose
示例:
networks:
default:
external:
name: my-pre-existing-network-FromTheOtherCompose
关于python - 使用 Python 连接到 Redis 集群(在 Docker 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57705157/