Home > Back-end >  Node.js app not connect to docker redis container
Node.js app not connect to docker redis container

Time:05-09

I connected with docker redis container.The redis working in the docker.If I execute the docker file with docker exec -it 96e199a8badf sh, I connected to redis server.

My node.js application like this.I use redis 4.1.0 version.

I don't know, what's going on.How can I fix this?

docker-compose.yml

version: '3'
services:
  app:
    container_name: delivery-app
    build:
      dockerfile: 'Dockerfile'
      context: .
    ports:
      - "3000:3000"
    volumes:
      - .:/app,
      - '/app/node_modules'
    networks:
      - redis
  redis:
    image: "redis"
    ports:
      - "6379:6379"
    networks:
      - redis
networks:
  redis:
    driver: bridge

Dockerfile

FROM node:16-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD ["node","server.js"]

code:

 const redisClient = redis.createClient({
            socket: {
                port: 6379,
                host: "redis"
            }
        });
        await redisClient.connect();
        redisClient.on('connect',function(){
            return res.status(200).json({
                success: true
            })
        }).on('error',function(error){
            return res.status(400).json({
                success: false
            })
        });

package.json

"redis": "^4.1.0"

CodePudding user response:

I had the same issue and solved it by passing the host parameter as a socket object in createClient like this

{ 
  socket: {
    host: "redis"
  }
}

This seems to be new because before you didn't have to use the socket object

Here's the documentation for node-redis createClient

https://github.com/redis/node-redis/blob/HEAD/docs/client-configuration.md

CodePudding user response:

It seems that the container is not being setup correctly in your docker compose try adding the command option as well so the container knows what to do when it starts up:

redis:
    image: redis:6.2-alpine
    ports:
      - "6379:6379"
    command: redis-server

I have also added an appropriate tag to the redis image

  • Related