You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

connect-redis连接异常:指定IP却连127.0.0.1求助

Redis连接拒绝问题(ECONNREFUSED 127.0.0.1:6379)

错误信息

app    | Redis error: Error: connect ECONNREFUSED 127.0.0.1:6379
app    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
app    |   errno: -111,
app    |   code: 'ECONNREFUSED',
app    |   syscall: 'connect',
app    |   address: '127.0.0.1',
app    |   port: 6379
app    | }

问题场景

应用与Redis均部署在Docker容器中,已硬编码Redis容器的外部IP(172.19.0.3),但程序仍尝试连接127.0.0.1。

原因分析

  1. Redis@v4 API变更:原createClient的顶级host参数已废弃,需将地址配置放在socket对象内,否则客户端会默认使用127.0.0.1。
  2. Docker网络配置问题:使用容器外部IP易出现网络不通,Docker容器间应通过容器名或自定义网络别名通信。
  3. 代码冗余配置:connect-redis同时指定client和host/port可能导致冲突,且存在拼写错误影响配置生效。

解决方案

1. 修正Redis客户端配置

适配Redis@v4的API,将连接地址放在socket配置项中:

const redisClient = createClient({
  legacyMode: true,
  socket: {
    host: 'redis-server', // 替换为你的Redis容器名称
    port: 6379
  }
});

2. 统一Docker网络

确保应用与Redis容器在同一自定义网络中:

  • 创建自定义网络:
    docker network create app-network
    
  • 启动Redis容器时加入该网络:
    docker run --name redis-server --network app-network -d redis
    
  • 启动应用容器时同样加入该网络:
    docker run --name your-app --network app-network -d your-app-image
    

3. 清理冗余配置并修正拼写错误

去掉connect-redis中重复的host和port参数,修正session配置的拼写错误:

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    name: '_redisSessionId',
    resave: false,
    saveUninitialized: true, // 修正原拼写错误saveUnitialized
    cookie: {
      path: '/',
      httpOnly: true,
      secure: false,
      maxAge: 60000
    },
    store: new redisStore({
      client: redisClient,
      ttl: 86400
    })
  })
)

完整修正后代码

// Session / Redis
const session = require('express-session');
const redisStore = require('connect-redis')(session);
// redis@v4
const { createClient } = require("redis")
const redisClient = createClient({
  legacyMode: true,
  socket: {
    host: 'redis-server', // 使用Redis容器名称
    port: 6379
  }
});

redisClient.connect()
  .catch(console.error)
  .then(() => {
    console.log('Connected to Redis server successfully');
  });

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    name: '_redisSessionId',
    resave: false,
    saveUninitialized: true,
    cookie: {
      path: '/',
      httpOnly: true,
      secure: false,
      maxAge: 60000 // 30 minutes
    },
    store: new redisStore({
      client: redisClient,
      ttl: 86400
    })
  })
)

内容的提问来源于stack exchange,提问作者Timothy Pulliam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:40:49