docker-compose UserNotFound: Could not find user

  docker, mongodb, mongoose, node.js

I have been trying to get my express app to deploy with docker and docker compose but I am running into this error from the database logs:
UserNotFound: Could not find user "admin" for db "admin""
and the other from mongoose:
Mongoose Error Authentication failed.

My docker compose is the following:


services:
  nodejs:
    build:
      context: .
      dockerfile: Dockerfile
    image: nodejs
    container_name: nodejs
    restart: unless-stopped
    env_file: .env
    environment:
      - MONGO_USERNAME=$MONGO_USERNAME
      - MONGO_PASSWORD=$MONGO_PASSWORD
      - MONGO_HOSTNAME=db
      - MONGO_PORT=$MONGO_PORT
      - MONGO_DB=$MONGO_DB
    ports:
      - '8080:3000'
    volumes:
      - .:/home/backend
      - node_modules:/home/backend/node_modules
    networks:
      - app-network
    command: ./wait-for.sh db:27017 -- npm run start:dev

  db:
    image: mongo
    container_name: db
    restart: unless-stopped
    env_file: .env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=$MONGO_USERNAME
      - MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASSWORD
      - MONGO_INITDB_DATABASE=$MONGO_DB
    volumes:
      - dbdata:/data/db
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  dbdata:
  node_modules:

and my .env file looks like this:

MONGO_USERNAME=admin
MONGO_PASSWORD=pass
MONGO_PORT=27017
MONGO_DB=projectc

my mongoose connector looks like:


    const {
        MONGO_USERNAME,
        MONGO_PASSWORD,
        MONGO_HOSTNAME,
        MONGO_PORT,
        MONGO_DB,
    } = process.env;

    const url = `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOSTNAME}:${MONGO_PORT}/${MONGO_DB}?authSource=admin`;
    const options = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true,
    };
    mongoose.connect(url, options);

Thanks for your help.

Source: Docker Questions

LEAVE A COMMENT