【发布时间】:2021-10-31 02:22:16
【问题描述】:
我有一个在节点容器和 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 都在我在 docker compose 文件中指定的同一网络上运行。
Docker 编写 sn-p
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.
【问题讨论】:
-
localhost在您的 api 容器中指的是容器本身,而不是您的开发/运行主机。 Redis 服务器没有在里面运行,但是在另一个容器中. So it will never connect usinglocalhost. You need to use the redis container name in the url connection. Usingredis` 应该没问题,但它不适合你。我相信在传递环境变量时可能会出现一些问题。并且它们是已解析的属性,总是无法localhost。我在您的撰写文件中看不到任何环境内容。你是如何初始化它们的? -
抱歉代码有误导性。没有为 REDIS_HOST 设置环境变量。所以它故意回退到本地主机。如果将 redis 作为主机,则会出现这种情况:prnt.sc/1qym8kv
-
等我修好了。放置redis确实有效。我假设因为 REDIS_HOST 没有价值,它会退回到我在三元运算符 else 子句中输入的内容。这解决了问题。
标签: node.js docker docker-compose redis containers