连接到 localhost:6379 时出现错误 99。无法分配请求的地址。当 运行 应用程序连接到 redis

Error 99 connecting to localhost:6379. Cannot assign requested address. when running app connected to redis

我在 docker 容器中构建此 python 应用程序,但无法访问其中的 Redis 端口。

在我的 Dockerfile 中添加了以下行:

EXPOSE 6379

但 运行 应用引发错误 redis.exceptions.ConnectionError: Error 99 connecting to localhost:6379. Cannot assign requested address.

我不得不提一下,我的应用程序只从 redis 队列中弹出项目。

编辑: 我的 Dockerfile 看起来像这样:

FROM python:3.9

ARG DATABASE
ARG SSL_TOKEN_PATH

ENV DATABASE=$DATABASE
ENV SSL_TOKEN_PATH=$SSL_TOKEN_PATH

COPY config/db_config.yaml db_config.yaml
COPY app/requirements.txt requirements.txt

ENV DB_CONFIG=config/db_config.yaml

COPY app/pydb/requirements.txt pydb/requirements.txt

RUN pip3 install -r requirements.txt
RUN pip3 install -r pydb/requirements.txt

COPY app/ .

EXPOSE 6379

CMD ["python3", "-u", "process_file.py"]

此问题的解决方案是在 docker 中使用以下方法创建网络:

docker network create <name_of_network>

作为 host inside redis 您必须提供:host.docker.internal.

最后 运行 创建的网络中的容器使用:

docker run --network <name_of_network> -d <image_name>

这解决了问题,我不必仅为 redis 创建新容器。