nodejs 容器不会连接到 redis 容器 docker-compose

nodejs container won't connect to redis container docker-compose

我在节点容器和redis容器中有一个express API 运行。 尝试将节点容器连接到 redis 时,出现以下错误。

api_1    | events.js:291
api_1    |       throw er; // Unhandled 'error' event
api_1    |       ^
api_1    |
api_1    | Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
api_1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
api_1    | Emitted 'error' event on RedisAdapter instance at:
api_1    |     at RedisClient.onError (/usr/src/api/node_modules/socket.io-redis/dist/index.js:65:22)
api_1    |     at RedisClient.emit (events.js:314:20)
api_1    |     at RedisClient.on_error (/usr/src/api/node_modules/redis/index.js:342:14)
api_1    |     at Socket.<anonymous> (/usr/src/api/node_modules/redis/index.js:223:14)
api_1    |     at Socket.emit (events.js:314:20)
api_1    |     at emitErrorNT (internal/streams/destroy.js:92:8)
api_1    |     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
api_1    |     at processTicksAndRejections (internal/process/task_queues.js:84:21) {
api_1    |   errno: 'ECONNREFUSED',
api_1    |   code: 'ECONNREFUSED',
api_1    |   syscall: 'connect',
api_1    |   address: '127.0.0.1',
api_1    |   port: 6379
api_1    | }

这里是建立连接的代码:

const redisClient = require("redis").createClient({host: process.env.REDIS_HOST ? process.env.REDIS_HOST : 'localhost'});

我试过将 'localhost' 更改为“redis”到“redis://redis:6379”。没有任何效果。

据我所知,容器上下文中的“localhost”指的是它自己的内部网络,但是 nodejs 和 redis 都在 运行 我在 [=26] 中指定的同一网络上=] 编写文件。

Docker 撰写摘要

    api: 
        build: ./api
        ports: 
            - "3004:3004"
        volumes:
            - type: bind
              source: ./api
              target: /usr/src/api
        working_dir: /usr/src/api
        depends_on: 
            - redis
        networks:
            - backend

    redis: 
        image: "redis:latest"
        ports: 
            - "6379:6379"
        hostname: redis
        networks:
            - backend
    ```

What could this be. All the "solutions" that I've managed to find through research don't work for me.

只是为了结束这个问题,当尝试连接到容器内的本地主机时,它假定容器本身并且因为 node.js 容器没有在 redis 端口上发布连接被拒绝。另一方面,因为使用 docker-compose,您会得到一个默认的 docker 网络将它们绑定在一起,因此可以使用 container\service 名称作为内部安全 DNS 记录。

有关 docker 网络内部工作的更详细说明,请参阅 this thread