MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017 -- docker-compose

Hello,

I’m trying to create a single node replicaset in a docker-compose image, but I can’t resolve the ECONNREFUSED error returned after running docker-compose up .

  • docker-compose.yaml
version: '3.8'

services:
  mongodb:
    image: mongo:latest
    container_name: mongodb
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - "27017:27017"
    expose:
      - 27017
    volumes:
      - ./data:/data/mongoDb
      - ./keys/mongodb-keyfile:/keys/mongodb-keyfile:ro
      - ./scripts/init-replica-set.sh:/scripts/init-replica-set.sh:ro
    entrypoint: [ "/scripts/init-replica-set.sh" ]
    command: mongod --port 27017 --ipv6 --replSet rs0 --bind_ip_all --auth --keyFile /keys/mongodb-keyfile
    networks:
      - mongo-network
networks:
  mongo-network:
    driver: bridge
  • init-replica-set.sh
mongosh -u root -p root --authenticationDatabase admin -quiet --eval <<EOF
rs.initiate({
  _id: 'rs0',
  members: [
    { _id: 0, host: 'localhost:27017' }
  ]
})
EOF

I’ve been already tried to use mongodb, 127.0.0.0, 127.0.0.1 and pass the $(hostname -I | awk ‘{print $1}’) as hostname, but none of them doesn’t work.

I gave to mongodb-keyfile and init-replica-set.sh files the following permissions:

chmod 400 ./keys/mongodb-keyfile

chown 999 ./keys/mongodb-keyfile

chmod +x ./scripts/init-replica-set.sh

Unfortunately, nothing that I try to implement works, and the error that is returned is like this:

mongodb    | MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
mongodb    | MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
mongodb exited with code 1
mongodb    | MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
mongodb exited with code 1

Can someone give me a tip about what I need to do to resolve this error?

Thanks a lot!