【问题标题】:Connection between node.js docker container and local redis server(127.0.0.1) [duplicate]node.js docker容器和本地redis服务器之间的连接(127.0.0.1)[重复]
【发布时间】:2020-08-07 00:44:08
【问题描述】:

我正在 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 主机

【问题讨论】:

    标签: docker redis


    【解决方案1】:

    您可以使用network_mode: "host" 在主机网络上运行您的notification-app 服务

    更新了 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

    【讨论】:

    • (这通常会完全禁用 Docker 的网络设置。您不会与主机进程或外部网络隔离,并且使用容器名称作为 DNS 名称的“正常”容器间通信将不起作用。)
    【解决方案2】:

    如果您使用 Docker for Mac 或 Docker for Windows,您的容器不会在您的主机上运行,​​而是在一个小虚拟机中运行。 如果你想让一个容器连接到你的主机服务之一,你可以使用这个地址而不是 localhost:host.docker.internal

    在您的主机上,您需要将您的服务绑定到 0.0.0.0 或其他 IP 但不是 127.0.0.1。

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2023-03-21
      • 2019-11-27
      • 2017-05-09
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多