Node can't connect to Redis via Docker Compose

Viewed 9182

I'm running a React app on Node and Redis via docker compose:

version: "3"
services:
  webapp:
    build: ./
    ports:
      - "127.0.0.1:3000:9090"
    depends_on:
      - redis
    command:
      npm run start

  nginx:
    build: ./nginx
    ports:
      - "80:80"
    environment:
      - NGINX_HOST=127.0.0.1
      - NGINX_PORT=80
    command:
      service nginx start

  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - ./data:/data

Docker file:

FROM node:alpine

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install
COPY . .

EXPOSE 9090
RUN npm run build_prod

Server.js:

const redisClient = RedisClient.createClient(6379,'redis');

I get a Redis connection refused error when I run docker-compose up --build:

redis_1   | 1:M 15 Nov 13:55:19.865 * Ready to accept connections
webapp_1  |
webapp_1  | > web.globalmap.fatmap.com@0.0.1 start /usr/src/app
webapp_1  | > node ./build/server.js
webapp_1  |
webapp_1  | events.js:193
webapp_1  |       throw er; // Unhandled 'error' event
webapp_1  |       ^
webapp_1  |
webapp_1  | Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
webapp_1  |     at Object._errnoException (util.js:1031:13)
webapp_1  |     at _exceptionWithHostPort (util.js:1052:20)
webapp_1  |     at TCPConnectWrap.afterConnect [as oncomplete]

I would like to know how to get docker to link both containers correctly.

3 Answers

Looks like redis does not resolve to the correct IP address.

Try a redis URI when creating the client.

// [redis:]//[[user][:password@]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
const redisClient = RedisClient.createClient('redis://redis:6379');

Provide the username, password, and db number if appropriate.

This solved my issue with node not being able to connect to redis using docker-compose.yml

const redis_client = redis.createClient({host: 'redis'});

then inside of my docker-compose.yml file i have the following

version: '3'

services:
  redis:
    image: redis
  socket:
    container_name: socket
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - redis
    links:
      - redis

source: https://github.com/docker-library/redis/issues/45

I haven't found any issues using process.env. to access the environment variable of docker.

I have declared the variable in the docker-compose.yml file.

version: '3.7'

services:
  api:
    build: .
    container_name: api-framework
    depends_on:
        - redis
    ports:
      - 8080:6002
    networks:
      - fronted
      - backend
    environment:
      redis_server_addr: redis
  redis:
    container_name: my-redis
    image: "redis:5"
    ports:
      - 6379
    networks:
      - backend

Then, the configuration file has the following line.

redis_host: process.env.redis_server_addr

It works for me.

Related