首页 > 解决方案 > node.js docker容器与本地redis服务器的连接(127.0.0.1)

问题描述

我在 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

标签: dockerredis

解决方案


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

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


推荐阅读