Home > Mobile >  Redis connection refused with nodejs/docker and docker networks
Redis connection refused with nodejs/docker and docker networks

Time:01-31

I've been trying to run my nodejs container and get it to connect to my Redis docker container with no avail. Even placing them in the same network does not work, I keep receiving Error: connect ECONNREFUSED 127.0.0.1:6379.

docker-compose.yaml:

version: '3.8'

services:
  redis:
    image: 'redis:alpine'
    ports:
      - '6379:6379'
    networks:
      - redis-net
  nodejs:
    build:
      context: ./
    container_name: nodejs
    restart: unless-stopped
    ports:
      - "3000:3000"
    networks:
      - redis-net

  nginx:
    container_name: webserver
    restart: unless-stopped
    build:
      context: ./nginx-conf
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./ssl:/etc/nginx/ssl
    networks:
      - redis-net

networks:
  redis-net:
    driver: bridge

nodejs server code:

const host = 'redis-net'
const port = 6379
const redisClient = redis.createClient({port:port, host:host})

Am I missing something here?

CodePudding user response:

You are not calling createClient correctly and it is defaulting to, well, defaults. The host and port need to be specified inside of a socket property. Like this:

const redisClient = redis.createClient({
  socket: {
    port: port,
    host: host
  }
})

Details on the various options for createClient can be found in the Client Configuration Guide that is linked off the README for Node Redis.

Also, after creating the client you will need to connect. Be sure to handle any errors before you do so. Like this:

redisClient.on('error', err => console.log('Redis Client Error', err))
await redisClient.connect()

Hope that helps!

  • Related