连接Node js时Redis连接错误

问题描述 投票:0回答:1

我正在尝试将 Node js 容器与 Redis 容器连接,当我运行 Node-js 容器并尝试连接 Redis 时遇到问题。我尝试了网上的大部分解决方案,仍然无法修复连接被拒绝的问题。


> Node js creating the Redis client: below code works locally good, without the container.

const redis = require('redis')
const redisClient = redis.createClient({
  host: "127.0.0.1",
  port: "6379"
})


> running Redis from the latest image.

docker run -d --name redis -p 6379:6379 redis

> Error:

[nodemon] starting `node index.js`

events.js:377

      throw er; // Unhandled 'error' event

      ^


Error: connect ECONNREFUSED 127.0.0.1:6379

    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16)

Emitted 'error' event on RedisClient instance at:

    at RedisClient.on_error (/usr/src/app/node_modules/redis/index.js:342:14)

    at Socket.<anonymous> (/usr/src/app/node_modules/redis/index.js:223:14)

    at Socket.emit (events.js:400:28)

    at emitErrorNT (internal/streams/destroy.js:106:8)

    at emitErrorCloseNT (internal/streams/destroy.js:74:3)

    at processTicksAndRejections (internal/process/task_queues.js:82:21) {

  errno: -111,

  code: 'ECONNREFUSED',

  syscall: 'connect',

  address: '127.0.0.1',

  port: 6379

}
node.js docker redis
1个回答
0
投票

试试这个

const Redis = require('redis');
const url = `redis://${redis.host}:${redis.port}`;
const usePassword = true;
const client = Redis.createClient({
url,
...(usePassword && { password: "password" })
})
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.