can't connect to redis through node app, both in dockers

こ雲淡風輕ζ 提交于 2019-12-24 01:15:09

问题


I'm trying to connect my app to redis, but i get:

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

when i do:

docker exec -it ed02b7e19810 ping test_redis_1 i've received all packets.

also the redis container declares:

* Running mode=standalone, port=6379

* Ready to accept connections

( i get the WARNINGS but i don't think its related:

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

this is my docker-compose.yaml:

version: '3'

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

DockerFile

 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);
});

i've also tried with redis package but still can't connect:

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

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

getting:

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

回答1:


For that specific docker-compose.yml there is no redis on 127.0.0.1, you should use redis as host, since services on the same Docker network are able to find each other using the service names as DNS.

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

Furthermore, depends_on does not wait for redis container to be ready before starting, it will only launch it first, so it is your job to wait before starting app.js or just handle that inside app.js

io-redis comes with a reconnection strategy, so you may want to try that first.

You can see my answer here regarding that issue:

Wait node.js until Logstash is ready using containers



来源:https://stackoverflow.com/questions/50730279/cant-connect-to-redis-through-node-app-both-in-dockers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!