Skip to main content

Securing MongoDB With Docker Compose

I had a little bit of an issue authenticating with docker compose. To add an admin user with docker compose you use the provided environments: MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD, and MONGO_INITDB_ROOT_PASSWORD.

version: '3.3'

services:
  example-db:
    image: mongo
    restart: always
    container_name: example-db
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=password
      - MONGO_INITDB_DATABASE=admin
    ports:
      - 27017:27017

Then in your db connector you specify the authSource (admin or whatever you want to use), and pass in user and password in an auth object:

const pino = require('pino')();
const mongoose = require('mongoose');
const db = mongoose.connection;
const options = {
  autoReconnect: true,
  authSource: 'admin',
  auth: {
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
  },
};

db.on('connecting', () => {
  pino.info('connecting to MongoDB...');
});

db.on('error', (error) => {
  pino.error(error);
  mongoose.disconnect();
});

db.on('connected', () => {
  pino.info('MongoDB connected!');
});

db.once('open', () => {
  pino.info('MongoDB connection opened!');
});

db.on('reconnected', () => {
  pino.info('MongoDB reconnected!');
});

db.on('disconnected', () => {
  pino.info('MongoDB disconnected!');
  mongoose.connect(process.env.DB_HOST, options);
});

mongoose.connect(process.env.DB_HOST, options);