2

I am following this mongo's official docker page to configure mongodb to start with authorization enabled along with creating user, password and a database. However, when I spin up docker-compose my nodejs component, it isn't able to connect to mongodb because there are no users created in mongodb side.

docker-compose.yml

version: "3"
services:
  nodejs:
    container_name: nodejs # How the container will appear when listing containers from the CLI
    build:
      context: .
      dockerfile: Dockerfile-nodejs
    user: node # The user to run as in the container
    working_dir: "/app" # Where to container will assume it should run commands and where you will start out if you go inside the container
    networks:
      - app # Networking can get complex, but for all intents and purposes just know that containers on the same network can speak to each other
    ports:
      - "3000:3000" # <host-port>:<container-port> to listen to, so anything running on port 3000 of the container will map to port 3000 on our localhost
    volumes:
      - ./:/app # <host-directory>:<container-directory> this says map the current directory from your system to the /app directory in the docker container
    command: # The command docker will execute when starting the container, this command is not allowed to exit, if it does your container will stop
      - ./wait-for.sh
      - mongodb:27017
      - --
      - /bin/sh
      - -c
      - npm install && npm start
    env_file: .env
    environment: 
      - MONGO_USERNAME=$MONGO_USERNAME
      - MONGO_PASSWORD=$MONGO_PASSWORD
      - MONGO_HOSTNAME=mongodb
      - MONGO_PORT=$MONGO_PORT
      - MONGO_DB=$MONGO_DB
    depends_on:
      - mongodb

  mongodb:
    image: mongo:4.1.8-xenial
    container_name: mongodb
    restart: always
    env_file: .env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=$MONGO_USERNAME
      - MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASSWORD
      - MONGO_INITDB_DATABASE=$MONGO_DB
    networks: 
      - app

networks:
  app:
    driver: bridge

Dockerfile-nodejs

FROM node:10

RUN apt update && apt install -y netcat

.env

MONGO_USERNAME=simpleUser
MONGO_PASSWORD=123456
MONGO_PORT=27017
MONGO_DB=simpleDb

app.js

const express = require('express');
var server = express();
var bodyParser = require('body-parser');

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://simpleUser:123456@mongodb:27017/simpleDb', {useNewUrlParser: true});

server.use(passport.initialize());
server.use(bodyParser.urlencoded({ extended: true }));


passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (id, done) {
  done(null, id);
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    var user = { username: username };
    return done(null, user);
  }
));

server.get('/', function(req, res) {
  res.send('Hello World');
});

server.post('/login', passport.authenticate('local', { failureRedirect: 'failure' }), function (req, res) {
  res.send('access granted');
});

server.listen(3000, function() {
  console.log('Example app listening on port 3000');
});

> docker ps

CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                    NAMES
aad21da1ed48        biblio_nodejs        "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        0.0.0.0:3000->3000/tcp   nodejs
24c200f341ac        mongo:4.1.8-xenial   "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        27017/tcp                mongodb

> docker-compose logs -f mongodb

2019-06-13T13:37:11.104+0000 I NETWORK  [listener] connection accepted from 192.168.0.3:53942 #2 (1 connection now open)
2019-06-13T13:37:11.110+0000 I NETWORK  [conn2] received client metadata from 192.168.0.3:53942 conn2: { driver: { name: "nodejs", version: "3.2.7" }, os: { type: "Linux", name: "linux", architecture: "x64", version: "4.14.116-boot2docker" }, platform: "Node.js v10.16.0, LE, mongodb-core: 3.2.7" }
2019-06-13T13:37:11.111+0000 I SHARDING [conn2] Marking collection admin.system.users as collection version: <unsharded>
2019-06-13T13:37:11.112+0000 I ACCESS   [conn2] Supported SASL mechanisms requested for unknown user 'simpleUser@simpleDb'
2019-06-13T13:37:11.127+0000 I ACCESS   [conn2] SASL SCRAM-SHA-1 authentication failed for simpleUser on simpleDb from client 192.168.0.3:53942 ; UserNotFound: Could not find user "simpleUser" for db "simpleDb"
2019-06-13T13:37:11.133+0000 I NETWORK  [conn2] end connection 192.168.0.3:53942 (0 connections now open)
quartaela
  • 2,579
  • 16
  • 63
  • 99
  • Those environment variables (eg `$MONGO_USERNAME`) should be coming from the file `.env`. Can you show a bit of that file? Also, you should ideally be reading those credentials from the environment inside `app.js`, instead of hard coding that URL. Perhaps `.env` isn't matching up? – ford Jun 13 '19 at 14:02
  • @ford true you are right I should read them inside app.js but I don't think it is really important now. By the way, I added `.env` file as well sorry for forgetting that, – quartaela Jun 13 '19 at 15:36

1 Answers1

5

I think I found the problem. node application wasn't able to access to mongo because I need to add authSource=admin parameter which points the database keeps user's credentials. It also explained here

So, the final url will be;

mongodb://simpleUser:123456@mongodb:27017/simpleDb?authSource=admin

quartaela
  • 2,579
  • 16
  • 63
  • 99
  • 1
    after 11 hours of scratching my hair with debugging, you save me, thank you ! – amdev Mar 21 '20 at 18:53
  • 1
    First time I've seen it referenced in all of the examples I've waded through. Saying that, just noticed that I was able to connect using Compass and they have that param in the generated url there. Should have used that in the first place, probably. You live and you learn. Anyway - thanks again! – Matt Mar 18 '21 at 02:47