Skip to content

Replica set with Auth #179

@kalpakrg

Description

@kalpakrg

I am having issues setting up replicaset with auth using image mongo:3.4. If --replSet switch is passed to the process, entrypoint starts the mongod in replica set mode upfront which prevents from adding default users.

Here's what I want to do,

  1. Add root user on first boot.
  2. Add a new database and user for that database on first boot.
  3. Boot mongod in replica set mode.
  4. rs.initialize() the node on first boot.
  5. Boot to replica set mode automatically thereafter.

1, is taken care by MONGO_INITDB_ROOT_USERNAME & MONGO_INITDB_ROOT_PASSWORD variables, although this fails with --replSet switch passed.
2, 3 & 4 I am taking care through 01-init-db.sh under /docker-entrypoint-initdb.d directory

Here's my Dockerfile

FROM mongo:3.4

ARG MONGO_GID=1000
ARG MONGO_UID=1000

RUN groupmod -g $MONGO_GID mongodb && usermod -u $MONGO_UID -g $MONGO_GID mongodb

RUN mkdir -p /docker-entrypoint-initdb.d
ADD docker-entrypoint-initdb.d/* /docker-entrypoint-initdb.d/
RUN chmod +x /docker-entrypoint-initdb.d/*.sh

and 01-init-db.sh present in docker-entrypoint-initdb.d directory

#!/bin/bash

if ! [[ -a /data/db/mydb-initialized ]]; then
	mongo <<-EOF
		use admin;
		db.auth("$MONGO_INITDB_ROOT_USERNAME", "$MONGO_INITDB_ROOT_PASSWORD");
		use MYDB;
		db.createUser({ 
			user: "myuser", p
			wd: "password", 
			roles: [ "readWrite" ] 
		});
	EOF
	
	mongod --shutdown \
		&& mongod --fork --logpath=/var/log/mongod.log --replSet replica0 \
		&& mongo <<-EOF
			use admin;
			db.auth("$MONGO_INITDB_ROOT_USERNAME", "$MONGO_INITDB_ROOT_PASSWORD");
			rs.initiate({
				_id: "replica0",
				members: [
					{ _id: 0, host: "localhost:27017" }
				]
			});
		EOF

	touch /data/db/mydb-initialized
fi

I tried overriding the CMD with -f <config file> or --replSet option, but figured that my --replSet switch gets passed to ENTRYPOINT which again breaks the thing (new to Docker still don't understand this well)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions