【问题标题】:Why does my NestJS app try to connect to localhost when it runs inside docker container?为什么我的 NestJS 应用程序在 docker 容器中运行时会尝试连接到 localhost?
【发布时间】:2022-02-22 15:41:27
【问题描述】:

我有一个 NestJS 项目 (monorepo),现在我正尝试将所有应用程序作为单独的 docker 容器运行。

我的 docker-compose.yml 如下所示:

version: '3.8'
services:  
  app-one:
    build:
      context: .
      dockerfile: ./apps/app-one/Dockerfile
    container_name: mono_app-one
    ports:
      - '3001:3001'
  app-two:
    build:
      context: .
      dockerfile: ./apps/app-two/Dockerfile
    container_name: mono_app-two
    ports:
      - '3002:3002'

Dockerfile 看起来像:

FROM node:12.19.0-alpine3.9 AS development
WORKDIR /usr/src
COPY package.json .
RUN npm install --only=development
COPY . .
RUN npm run build --app-one
CMD ["sh", "-c", "npm start --app-one"]

app.module.ts 文件看起来像:

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: 'development.env',
      isGlobal: true,
    }),
    TypeOrmModule.forRoot({
      type: 'mssql',
      host: process.env.HOST || 'localhost',
      port: parseInt(process.env.PORT, 10) || 1433,
      username: process.env.USER,
      password: process.env.PASSWORD,
      database: process.env.DB_NAME,
      entities: [SomeEntity],
      synchronize: false,
      options: { encrypt: false },
    }),    
  ],
  ...
})
export class AppModule {}

最后 development.env 是:

PORT=1433
HOST=12.34.56.78
USER=admin
PASSWORD=password
DB_NAME=MyDb

当我运行 docker-compose up --build 图像被正确创建,容器也是如此。但是当容器运行时,我看到了错误:

即使我直接传递端口、主机、用户、传递等(硬编码),我也会看到相同的错误。 问题是:为什么?在这种情况下,我必须查看连接 12.34.56.78 的尝试。

【问题讨论】:

    标签: docker docker-compose nestjs


    【解决方案1】:

    初始化TypeOrmModule时使用ConfigService而不是process.env

    参见以下文档:

    https://docs.nestjs.com/techniques/database#async-configuration https://docs.nestjs.com/techniques/configuration#using-the-configservice

    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('HOST'),
        port: +configService.get<number>('PORT'),
        username: configService.get('USERNAME'),
        password: configService.get('PASSWORD'),
        database: configService.get('DATABASE'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true,
      }),
      inject: [ConfigService],
    });
    

    【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多