Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node can't connect to Redis via Docker Compose

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  | > [email protected] 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.

like image 434
Adam Bishti Avatar asked Dec 02 '22 12:12

Adam Bishti


1 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.

like image 98
Joshua Barnett Avatar answered Dec 25 '22 08:12

Joshua Barnett