Just as Thomas Edison made 999 attempts in inventing the the lightbulb and then said He discovered 999 ways a lightbulb could not be made. This post is about how I discovered how not to configure MongoDB on Docker.
I was working on my portfolio website, and I decided to use MongoDB on docker to just test out my knowledge on Docker since I have used PostgreSQL on Docker and it worked without any hassle.
this is the content of my initial docker-compose.yml file
version: '3.7'
services:
mongo:
image: "mongo:4.0.4"
container_name: "mongo"
env_file:
- .env
environment:
- MONGO_INITDB_ROOT_USERNAME:${USER}
- MONGO_INITDB_ROOT_PASSWORD:${PASS}
- MONGO_INITDB_DATABASE:${DB}
volumes:
- ./db/:/data/db/
ports:
- "27017:27017"
Then I fired up my terminal into the directory where my docker-compose.yml file was saved and did this:
docker-compose up -d
I waited for it to pull the mongo image and then build and start MongoDB as a service.
Then I did the following to see if I could connect,
docker exec -it mongodb bash
mongo -u admin -p
I enter the password on the password prompt, lo and behold I was denied access, for about 8 hours I battle with this issue, I went to stackoverflow, github and other website seeking for solution and I didn't find any.
Then I decided to do what I normally do when I install mongodb on my local machine. In order to do that, I stopped the containers on my terminal and ran this command:
docker-compose stop && docker-compose down
Then I edited my configuration to this:
version: '3.7'
services:
mongo:
image: "mongo:4.0.4"
container_name: "mongo"
volumes:
- ./db/:/data/db/
ports:
- "27017:27017"
I ran the following commands on my terminal:
docker-compose up -d
docker exec -it mongodb bash
mongo
and then, I was greeted with an interactive shell for mongodb and then I ran the following commands
use admin
db.createUser(
{
user: 'admin',
pwd: 'yourpassword',
roles: [{ role: 'userAdminAnyDatabase', db: 'admin' }, 'readWriteAnyDatabase']
}
)
followed by this other command too
use your_db_name
db.createUser(
{
user: 'your_username',
pwd: 'your_password',
roles: [{ role: 'readWrite', db: 'your_db_name' }]
}
)
viola! that's what solved the problem I was encountering.
Please drop a comment if you've encountered this kind of problem, and tell us what you did that solved it, and also drop a comment if this post has been helpful in one way or the other.
Cheers!
Top comments (0)