【问题标题】:can't connect to redis through node app, both in dockers无法通过节点应用程序连接到redis,都在dockers中
【发布时间】:2018-06-07 07:44:51
【问题描述】:

我正在尝试将我的应用连接到 redis,但我得到了:

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379

当我这样做时:

docker exec -it ed02b7e19810 ping test_redis_1 我已收到所有数据包。

redis 容器也声明:

* Running mode=standalone, port=6379

* Ready to accept connections

(我收到了警告,但我不认为它相关:

Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf

WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128

这是我的 docker-compose.yaml:

version: '3'

services:
  test-service:
      build: .
      volumes:
        - ./:/usr/test-service/
      ports:
        - 5001:3000
      depends_on:
        - redis
  redis:
    image: "redis:alpine"

Docker 文件

 FROM node:8.11.2-alpine

 WORKDIR /usr/test-service/

 COPY . /usr/test-service/

 RUN yarn install

 EXPOSE 3000

 CMD ["yarn", "run", "start"]

app.js

const Redis = require('ioredis');
const redis = new Redis();

redis.set('foo', 'bar');
redis.get('foo').then(function (result) {
    console.log(result);
});

我也尝试过使用redis 包,但仍然无法连接:

 var redis = require("redis"),
     client = redis.createClient();

 client.on("error", function (err) {
     console.log("Error " + err);
 });

得到:

 Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

【问题讨论】:

    标签: node.js docker redis docker-compose ioredis


    【解决方案1】:

    对于特定的docker-compose.yml127.0.0.1 上没有redis,您应该使用redis 作为主机,因为同一 Docker 网络上的服务能够使用服务名称作为 DNS 找到彼此。

    const Redis = require('ioredis');
    const redis = new Redis({ host: 'redis' });
    

    此外,depends_on 不会等待redis 容器在启动前准备好,它只会先启动它,所以你的工作是在启动app.js 之前等待或者只是在app.js 中处理它

    io-redis 带有reconnection 策略,因此您可能想先尝试一下。

    你可以在这里看到我对这个问题的回答:

    Wait node.js until Logstash is ready using containers

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 1970-01-01
      • 2021-05-03
      • 2019-02-08
      • 2021-04-18
      • 2014-05-08
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多