issue redis and docker

Viewed 45

I currently have a very strange error with docker more precisely with redis.

My backend runs with nodejs and typescript:

code

const redisPubSubOptions: any = {
  host: process.env.REDIS_HOST || "127.0.0.1",
  port: process.env.REDIS_PORT || 6379,
  connectTimeout: 10000,
  retryStrategy: (times: any) => Math.min(times * 50, 2000),
};

export const pubsub: RedisPubSub = new RedisPubSub({
  publisher: new Redis(redisPubSubOptions),
  subscriber: new Redis(redisPubSubOptions),
});

Dockerfile

FROM node:14-alpine as tsc-builder

WORKDIR /usr/src/app

COPY . .
RUN yarn install

EXPOSE 4000

CMD yarn run dev

docker-compose

version: "3.8"

services:
  
  backend:
    build: .
    container_name: backend
    ports:
      - 4242:4242
    depends_on:
      - redis
    env_file:
      - ./docker/env/.env.dev
    environment:
      - ENVIRONMENT=development
      - REDIS_PORT=6379
      - REDIS_HOST=redis

  redis:
    image: redis:6.0.12-alpine
    command: redis-server --maxclients 100000 --appendonly yes
    hostname: redis
    ports:
      - "6379:6379"
    restart: always

when I start my server the backend works and then the redis error comes after:

Error: connect ECONNREFUSED 127.0.0.1:6379

1 Answers

Both Redis and your backend run on different containers, so they have different IP addresses in the docker network. You are trying to connect to 127.0.0.1, which is the local address of the backend container.

Method 1:

Since you are using docker-compose (and of course it creates a network between services), you can use the service name instead of 127.0.0.1. For example:

const redisPubSubOptions: any = {
  host: process.env.REDIS_HOST || "redis",
  port: process.env.REDIS_PORT || 6379,
  connectTimeout: 10000,
  retryStrategy: (times: any) => Math.min(times * 50, 2000),
};

export const pubsub: RedisPubSub = new RedisPubSub({
  publisher: new Redis(redisPubSubOptions),
  subscriber: new Redis(redisPubSubOptions),
});

Method 2:

The other method is to expose the Redis port to the IP address of the Docker interface in the Host machine. Most of the time that is 172.17.0.1, but with ip -o a (If you are using Linux) you can see the Docker interface and its IP address. so you need to do this for that:

  redis:
    image: redis:6.0.12-alpine
    command: redis-server --maxclients 100000 --appendonly yes
    hostname: redis
    ports:
      - "172.17.0.1:6379:6379"
    restart: always

This address 172.17.0.1:6379 (Or any Docker interface IP address on the Host) should be exposed for Redis. Easily you can use this address in the application.

Note: You can handle these values using environment variable which is a better and more standard solution. You can take a look at this.

Related