NestJS TypeOrmModule在Docker环境下E2E测试无法连接PostgreSQL
E2E测试中PostgreSQL连接失败排查
我在NestJS的E2E测试中尝试连接PostgreSQL数据库,但连接失败。PostgreSQL日志显示数据库已就绪,但问题仍未解决,推测问题出在配置环节。
相关文件
app.e2e-spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { AppModule } from '../src/app.module'; import * as request from 'supertest'; import { INestApplication } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { configValidationSchema } from '../src/config.schema'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { EventEntity } from '../src/event/event.entity'; describe('NestJS App E2E Tests', () => { let app: INestApplication; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ AppModule, ConfigModule.forRoot({ envFilePath: [`.env.stage.${process.env.STAGE}`], validationSchema: configValidationSchema, }), TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ type: 'postgres', host: configService.get('DATABASE_HOST'), port: configService.get('POSTGRES_PORT'), username: configService.get('POSTGRES_USER'), password: configService.get('POSTGRES_PASSWORD'), database: configService.get('POSTGRES_DB'), entities: [EventEntity] }), }) ], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); it('/ (GET)', () => { return request(app.getHttpServer()) .get('/') .expect(200) .expect('Hello!'); }); afterAll(async () => { await app.close(); }); });
Dockerfile.test
FROM node:16 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . CMD ["npm", "run", "test:e2e"]
docker-compose.e2e.yml
version: "3.8" services: test: build: dockerfile: Dockerfile.test context: . environment: NODE_ENV: test PORT: 3000 depends_on: - postgres postgres: image: postgres:10.4 ports: - "5432:5432" environment: POSTGRES_USER: user POSTGRES_PASSWORD: password POSTGRES_DB: db DATABASE_HOST: postgres POSTGRES_PORT: 5432
PostgreSQL启动日志
2023-11-04 17:52:14.521 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
scheduler-postgres-1 | 2023-11-04 17:52:14.521 UTC [1] LOG: listening on IPv6 address "::", port 5432
scheduler-postgres-1 | 2023-11-04 17:52:14.524 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
scheduler-postgres-1 | 2023-11-04 17:52:14.534 UTC [69] LOG: database system was shut down at 2023-11-04 17:52:14 UTC
scheduler-postgres-1 | 2023-11-04 17:52:14.538 UTC [1] LOG: database system is ready to accept connections
内容的提问来源于stack exchange,提问作者Juliak
相关产品推荐
相关产品推荐

