无法使用 typeorm 连接到 postgres

Ale*_*ide 1 javascript postgresql docker typeorm nestjs

我有这个docker-compose.infra.yaml配置:

version: '3.1'

services:
  db:
    image: postgres
    restart: always
    ports: 
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USERNAME: postgres

networks:
    default:
        external:
            name: learning
Run Code Online (Sandbox Code Playgroud)

连同这个docke-compose.yaml配置:

version: '3.1'

services:
  web_app:
    container_name: web_app
    image: node:14
    entrypoint:
      ["/bin/sh", "-c", "yarn start:dev --preserveWatchOutput"]
    working_dir: /app
    volumes:
      - ./:/app
    ports:
      - 3001:3000

networks:
  default:
      external:
          name: learning
Run Code Online (Sandbox Code Playgroud)

我将其开始为:

start.infra.sh

#!/bin/bash

docker network create learning

docker-compose -f docker-compose.infra.yaml start
Run Code Online (Sandbox Code Playgroud)

start.sh

#!/bin/bash

docker network create learning

docker-compose up
Run Code Online (Sandbox Code Playgroud)

make start

.PHONY: start
start:
    @./start-infra.sh
    @./start.sh
Run Code Online (Sandbox Code Playgroud)

我的数据库已启动并正在运行,我可以使用 pgAdmin 使用如下凭据连接到它:

在此输入图像描述

密码是postgres。这是我的 Nest.js 代码:

@Module({
  imports: [
    TasksModule,
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'postgres',
      autoLoadEntities: true,
      synchronize: true,
    }),
    AuthModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

虽然在我看来我所做的一切都是正确的,但我一定错过了一些事情,因为我无法从代码连接到数据库。我缺少什么?

BMi*_*tch 5

host: 'localhost',
Run Code Online (Sandbox Code Playgroud)

应该:

host: 'db',
Run Code Online (Sandbox Code Playgroud)

在容器内,postgres DNS 名称与服务名称相同,db而不是localhost。默认情况下,每个容器都有自己独立的网络命名空间,包括一个localhost仅与容器通信的专用网络命名空间,不与其他容器通信,也不与外部主机通信。