node.js docker容器与本地redis服务器之间的连接(127.0.0.1)[重复]

问题描述 投票:0回答:2
我正在docker容器中运行node.js应用程序。这是我的docker-compose文件-

version: '3.7' services: notification-app: container_name: ${CONTAINER_NAME} build: context: ./ dockerfile: ./Dockerfile args: - APP_ENV=${APP_ENV} ports: - ${EXPORTED_PORT}:${APP_PORT} environment: - REDIS_HOST=${REDIS_HOST} - REDIS_PORT=${REDIS_PORT}

这是我的.env文件-

CONTAINER_NAME=sheba_socket APP_ENV=development APP_PORT=3000 EXPORTED_PORT=3000 REDIS_HOST=localhost REDIS_PORT=6379

我正在本地运行REDIS SERVER(没有容器,直接在机器上)。当我构建并运行此容器时,发现此错误。

[ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND redis at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)

我认为,问题出在这里[[REDIS_HOST = localhost。我不确定如何定义

redis host。

docker redis
2个回答
1
投票
更新的docker-compose.yml:

version: '3.7' services: notification-app: container_name: ${CONTAINER_NAME} build: context: ./ dockerfile: ./Dockerfile args: - APP_ENV=${APP_ENV} environment: - REDIS_HOST=${REDIS_HOST} - REDIS_PORT=${REDIS_PORT} network_mode: "host" //Here is the change

[您可能已经注意到我已经从原始的docker-compose文件中删除了ports。这是因为当我们在主机网络上运行服务时,该服务直接绑定到Docker主机上的端口。因此,无需在主机网络中公开端口。

有了此更改,您不需要更新.env文件。

REDIS_HOST=localhost可以正常工作。

了解有关Docker主机网络here的更多信息>

如果您使用Mac的Docker或Windows的Docker,则您的容器不在主机上运行,​​而是在小型VM中运行。如果要使容器连接到您的主机服务之一,则可以使用此地址代替localhost:host.docker.internal
在主机上,您需要将服务绑定到0.0.0.0或其他IP上,而不是127.0.0.1。

1
投票
© www.soinside.com 2019 - 2024. All rights reserved.