I have a project with this directory structure:
- other-service/
- my-service/
src/
Dockerfile
.env
docker-compose
.env
I have defined my mongoDB container & service container in a docker-compose.yml file like below:
version: "3"
services:
my-service:
depends_on:
- mongodb
env_file: ./my-service/.env
container_name: my-service
build: ./my-service
environment:
- DB_HOST=$DB_HOST
- DB_USER=$DB_USER
- DB_PASSWORD=$DB_PASSWORD
- DB_NAME=$DB_NAME
- DB_PORT=$DB_PORT
ports:
- "3002:3002"
mongodb:
image: mongo:latest
container_name: my-mongodb
env_file: ./.env
environment:
MONGO_INITDB_ROOT_USERNAME: $DB_USER
MONGO_INITDB_ROOT_PASSWORD: $DB_PASSWORD
ports:
- $DB_PORT:$DB_PORT
volumes:
- db_vol:/data/db
volumes:
db_vol:
The my-service/.env
file looks like this:
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
...
The root level .env
looks like this (basically the same content as my-service/.env
for the DB part):
#used by compose
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
my-service
tries to connect to mongoDB with this code:
const dbUri=`mongodb://${process.env['DB_USER']}:${process.env['DB_PASSWORD']}@${process.env['DB_HOST']}:${process.env['DB_PORT']}/${process.env['DB_NAME']}`
console.log(`DB connect to: ${dbUri}`);
await mongoose.connect(dbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
After I run docker-compose build
& docker-compose up -d
. The my-mongodb
container is up and running. But my-service
is not. I checked the container log, it shows:
DB connect to: mongodb://root:pass123@mongodb:27017/my_db
...
DatabaseConnError: Database connection failure. undefined
...
statusCode: 500,
msg: 'Database connection failure'
}
Node.js v19.2.0
I feel it is because both containers are on the same Docker bridge network, the database URI I defined might not correct? But I am not sure. Could someone please guide me where could be wrong in my case?
=== UPDATE on 8th of December2022 ===
I dug deeper of my problem, it turned out the problem is actually an AuthenticationError
, full error log is below:
Database connection failure. {"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
It is the same issue @jeeves' answer below has mentioned, then I tried adding ?authSource=admin
like @jeeves suggested:
DB connect to: mongodb://root:pass123@mongodb:27017/my_db?authSource=admin
but I still get the authentication error. Why?