bounty将在7天后过期。回答此问题可获得+50的声望奖励。user842225正在寻找来自知名来源的答案。
我有一个具有以下目录结构的项目:
- other-service/
- my-service/
src/
Dockerfile
.env
docker-compose
.env
我已经在一个docker-compose.yml文件中定义了我的mongoDB容器和服务容器,如下所示:
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:
my-service/.env
文件如下所示:
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
...
根级别.env
如下所示(基本上与DB部分的my-service/.env
内容相同):
#used by compose
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
my-service
尝试使用以下代码连接到mongoDB:
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
});
在我运行docker-compose build
和docker-compose up -d
之后。my-mongodb
容器已经启动并运行。但是my-service
没有。我检查了容器日志,它显示:
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
我觉得是因为两个容器都在同一个Docker网桥网络上,我定义的数据库URI可能不正确?但是我不确定。有人能告诉我在我的情况下哪里可能是错误的吗?
1条答案
按热度按时间8hhllhi21#
您可能需要对mongodb进行健康检查。
类似:mongodb and mongo-express not connecting with docker-compose