skip to Main Content

I want to use Redis with my express server in docker. I am using docker-compose to build my app with Redis. Here is my code for Dockerfile

FROM node:12-alpine
WORKDIR '/var/www/app'

Here is the code for the docker-compose.yml file:

redis:
  image: redis
  container_name: cache
  expose:
    - 6379
app:
  build: ./
  volumes:
    - ./:/var/www/app
  links:
    - redis
  ports:
    - 7000:7000
  environment:
    - REDIS_URL = redis
    - NODE_ENV=development
    - PORT=7000
  command:
    sh -c 'npm i && node server.js'

I am not able to debug why it is refusing to connect even if I expose port 6379 in the docker-compose.yml file.
Here is my code for the server.js file

const express = require("express");
const app = express();
const redis =require("redis")

let client=redis.createClient(process.env.REDIS_URL)

client.on('connect',()=>{
  console.log("redis connected")
});

client.on("error", function (err) {
  console.log("Error " + err);
});

var port = process.env.PORT || 7000;

app.listen(port, () => {
  console.log(`Server is listening in port: ${port}`);
});

I have used the below commands to build the app.

sudo docker-compose up --build

Any guidance would be helpful. Thanks

2

Answers


  1. Chosen as BEST ANSWER

    It has been solved by just removing the spaces in-between and changed the first line after the environment to REDIS_URL=redis://cache Thanks to @ozlevka


  2. redis:
      image: redis
      container_name: cache
      ports:
        - 6379:6379
    app:
      build: ./
      volumes:
        - ./:/var/www/app
      ports:
        - 7000:7000
      environment:
        - REDIS_URL=localhost
        - NODE_ENV=development
        - PORT=7000
      command:
        sh -c 'npm i && node server.js'
    

    I have added ports to redis and removed links. Please try this and update.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search