Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs server cannot link Redis and MongoDB in the same Docker-Compose yml file

I built up a express server and link to mongo db and redis db.
I have used docker run server / mongo / redis separately and server works fine.
However, when I used docker-compose , it show errors

redisdb error: { Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 ....
MongoError: failed to connect to server [localhost:27017] on first connect ....

I use docker ps to check and all three containers are running.

Here is my docker-compose.yml

version: "2"
services:
  mongo:
    image: mongo:latest
    ports:
        - "27017:27017"
  redis:
    image: redis:latest
    ports:
        - "6379:6379"
  web:
    build: .
    links:
      - mongo
      - redis
    depends_on:
      - mongo
      - redis
    ports:
      - "3000:3000"

Here is how I set db connection

client = redis.createClient({ "host": process.env.REDIS_PORT_6379_TCP_ADDR || 'localhost', "port": "6379" });
mongoose.connect(`mongodb://${process.env.MONGO_PORT_27017_TCP_ADDR || 'mongodb://localhost:27017/chichat'}`);

I have also try docker-compose stop && docker-compose rm && docker-compose up but still fail.

like image 287
鄭元傑 Avatar asked Oct 27 '25 15:10

鄭元傑


1 Answers

You try to connect to localhost instead of connecting to redis or mongo container. It happens because environment variables REDIS_PORT_6379_TCP_ADDR and MONGO_PORT_27017_TCP_ADDR does not set.

You have 2 ways to fix this issue:

1) define redis and mongo host names in your application.

client = redis.createClient({ "host":'redis', "port": "6379" });
mongoose.connect('mongodb://mongo:27017/chichat'});

2) define environment variables REDIS_PORT_6379_TCP_ADDR and MONGO_PORT_27017_TCP_ADDR in docker-compose.yml file

version: "2"
services:
  mongo:
    image: mongo:latest
    ports:
        - "27017:27017"
  redis:
    image: redis:latest
    ports:
        - "6379:6379"
  web:
    build: .
    links:
      - mongo
      - redis
    depends_on:
      - mongo
      - redis
    ports:
      - "3000:3000"
    environment:
      - REDIS_PORT_6379_TCP_ADDR:"redis:6379"
      - MONGO_PORT_27017_TCP_ADDR:"mongodb://mongo:27017"

The second way can contains some errors. I don`t think how exactly ULRs must be presents in nodejs.

like image 172
Bukharov Sergey Avatar answered Oct 30 '25 07:10

Bukharov Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!