Alex Ironside
Alex Ironside

Reputation: 5059

Unable to connect to postgres with typeorm

I have this docker-compose.infra.yaml config:

version: '3.1'

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

networks:
    default:
        external:
            name: learning

along with this docke-compose.yaml config:

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

I am starting it as:

start.infra.sh

#!/bin/bash

docker network create learning

docker-compose -f docker-compose.infra.yaml start

start.sh

#!/bin/bash

docker network create learning

docker-compose up

make start:

.PHONY: start
start:
    @./start-infra.sh
    @./start.sh

My db is up and running, I can connect to it using pgAdmin using credentials like these:

enter image description here

The password is postgres. And here's my nest.js code:

@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 {}

And while it looks to me like I'm doing everything correctly, I must be missing smth, since I am unable to connect to the db from the code. What am I missing?

Upvotes: 1

Views: 1245

Answers (1)

BMitch
BMitch

Reputation: 264811

host: 'localhost',

should be:

host: 'db',

From within the container, the postgres DNS name is the same as the service name, db, not localhost. By default, each container has it's own isolated networking namespace, including a private localhost that only talks the container, not to other containers, and not to your external host.

Upvotes: 5

Related Questions