node.js - 连接 redis 时在 docker-compose 中出现错误 : conne

我收到连接错误:连接 ECONNREFUSED 127.0.0.1:6379,同时使用 docker-compose 将 Redisnode js 一起使用。 我在 Redis 中使用了相同的主机名和服务名,但仍然出现错误。

我的 Node js代码是:

const express = require('express');
const redis = require('redis');

const client = redis.createClient({
    port: 6379,
    host: 'redis'
});
client.connect();
client.on('connect', (err)=>{
    if(err) throw err;
    else console.log('Redis Connected..!');
});

const app = express();
app.get('/',async (req,res)=>{
    let key = req.query['name'];
    if(key){
        let value = await client.get(key);
        if(value){
            value++;
            client.set(key,value);
            res.send(`Hello ${key}, ${value}!`);
            console.log(`${key}, ${value}`);
        }
        else{
            value = 1;
            client.set(key,value); 
            res.send(`Hello ${key}, ${value}!`);
            console.log(`${key}, ${value}`);
        }
    }
    else{
        console.log("Name not passed!");
        res.send("Hello World!");
    }
});
const port = 3000;
app.listen(port,()=>{
    console.log(`App is listening at http://localhost:${port}`);
});

我的 docker-compose.yml 文件是:

version: "3"
services:
  redis: 
    image: redis:latest
    container_name: client
    restart: unless-stopped
    expose:
      - 6379
  app:
    depends_on:
      - redis
    build:
      context: .
      dockerfile: Dockerfile
    container_name: app
    restart: on-failure
    ports:
      - "3000:3000"
    volumes:
      - .:/app

我在控制台上得到的是

C:\Users\ashok\Desktop\Practice>docker-compose up
[+] Running 3/3
 - Network practice_default  Created                                                                                                        0.1s
 - Container client          Created                                                                                                        1.1s
 - Container app             Created                                                                                                        0.3s
Attaching to app, client
client  | 1:C 02 Apr 2022 11:08:28.885 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
client  | 1:C 02 Apr 2022 11:08:28.886 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
client  | 1:C 02 Apr 2022 11:08:28.886 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
client  | 1:M 02 Apr 2022 11:08:28.889 * monotonic clock: POSIX clock_gettime
client  | 1:M 02 Apr 2022 11:08:28.890 * Running mode=standalone, port=6379.
client  | 1:M 02 Apr 2022 11:08:28.891 # Server initialized
client  | 1:M 02 Apr 2022 11:08:28.891 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
client  | 1:M 02 Apr 2022 11:08:28.893 * Ready to accept connections
app     |
app     | > practice@1.0.0 start
app     | > node app.js
app     |
app     | Server is live at port: 3000
app     | node:internal/process/promises:279
app exited with code 1
app     |             triggerUncaughtException(err, true /* fromPromise */);
app     |             ^
app     |
app     | Error: connect ECONNREFUSED 127.0.0.1:6379
app     |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)
app     | Emitted 'error' event on Commander instance at:
app     |     at RedisSocket.<anonymous> (/app/node_modules/@node-redis/client/dist/lib/client/index.js:339:14)
app     |     at RedisSocket.emit (node:events:527:28)
app     |     at RedisSocket._RedisSocket_connect (/app/node_modules/@node-redis/client/dist/lib/client/socket.js:117:14)
app     |     at processTicksAndRejections (node:internal/process/task_queues:96:5)
app     |     at async Commander.connect (/app/node_modules/@node-redis/client/dist/lib/client/index.js:162:9) {
app     |   errno: -111,
app     |   code: 'ECONNREFUSED',
app     |   syscall: 'connect',
app     |   address: '127.0.0.1',
app     |   port: 6379
app     | }

我能做些什么来解决它?

最佳答案

我也曾尝试在客户端创建中指定主机和端口,但没有成功。 我发现使用

const client = redis.createClient({
url: 'redis://redis:6379'
});

为我解决了这个问题。

关于node.js - 连接 redis 时在 docker-compose 中出现错误 : connect ECONNREFUSED 127. 0.0.1:6379,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71717395/

相关文章:

html - Font-Awesome 版本 6 图标未显示

r - 将一列拆分为两列 : dataframes within a list

json - 在 Rust 中使用可选的 JSON 字段,避免在 JSON 中使用 None/nul

css - TailwindCSS : is it possible to remove a box

rust - 为什么不可变结构在移入向量时会变为可变结构?

r - 通过匹配列和值 R 对数据帧进行子集和分组

css - 在 RMarkdown 中,如何以 block 的形式获取 css 文件?

python - 如何将变量插入文件路径?

python - 列表的字典变成元组的元组的字典

ruby-on-rails-7 - 如何在Rails7中使用importmap固定npm、yarn包