服务容器无法通过docker-compose连接到MongoDB容器

k10s72fa  于 2022-12-03  发布在  Docker
关注(0)|答案(1)|浏览(146)

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 builddocker-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可能不正确?但是我不确定。有人能告诉我在我的情况下哪里可能是错误的吗?

8hhllhi2

8hhllhi21#

您可能需要对mongodb进行健康检查。

version: "3"
services:
  my-service:
    depends_on:
      mongodb:
        condition: service_healthy
    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
    healthcheck:
      test:  echo 'db.runCommand("ping").ok' | mongosh localhost:$DB_PORT/test --quiet
      interval: 10s
      timeout: 10s
      retries: 5
      start_period: 10s      

volumes:
  db_vol:

类似:mongodb and mongo-express not connecting with docker-compose

相关问题