Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 254
user2212726 Avatar asked Jan 28 '23 23:01

user2212726


1 Answers

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

like image 151
Marcos Casagrande Avatar answered Jan 31 '23 09:01

Marcos Casagrande