Roman Karpyshyn
Roman Karpyshyn

Reputation: 199

dockerize NestJS and TypeORM

i have this Dockerfile :

FROM node:12

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

CMD [ "npm", "start"]

and docker-compose.yml looks like that :

version: '3.1'

services:

      db:
        image: postgres
        restart: always
        volumes:
          - ./db-data:/var/lib/postgresql/data
        environment:
          POSTGRES_PASSWORD: root
        ports:
          - 5432:5432
      node:
        build: .
        volumes:
          - ./public/storage/files:/usr/app/public/storage/files
        env_file: .env
        restart: always
        ports:
          - '8080:8080'

When projects starts it uses ormconfig.json

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "database": "postgres",
  "password": "root",
  "synchronize": true,
  "logging": true,
  "entities": ["dist/**/*.entity.js"]
}

But i have error when run it in docker

[Nest] 30   - 08/19/2020, 5:49:39 PM   [TypeOrmModule] Unable to connect to the database. Retrying (4)... +3003ms
node_1  | Error: connect ECONNREFUSED 127.0.0.1:5432

Help pls to fix it. Without docker it works perfectly.

Upvotes: 2

Views: 6495

Answers (1)

Because when you use docker-compose they are not in each other localhost.

Actually they are in separate docker networks

so you have to set their network to a same network or calling them by their container_name

{
  "type": "postgres",
  "host": "db", // container name
  "port": 5432,
  "username": "postgres",
  "database": "postgres",
  "password": "root",
  "synchronize": true,
  "logging": true,
  "entities": ["dist/**/*.entity.js"]
}

A working example is shown below: Also mind that its not necessary to do networking manually as @Charles Desbiens said in comments

version: "3.5"

services:
  # Databases # #
  postgresql-test:
    container_name: postgresql-test
    image: postgres:11.2-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-admin}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
      POSTGRES_DB: ${POSTGRES_DB:-crud-node}
      PGDATA: /data/postgres
    ports:
      - 30001:5432
    networks:
      - test
...
  node:
    build:
      context: ./backend
      dockerfile: Dockerfile.dev
    image: backend:latest
    container_name: backend
    depends_on:
      - postgresql-test
    networks:
      - test
    ports:
      - 3000:3000
      - 9229:9229

...
networks:
  test:

Now you can use address: postgresql-test & port: 5432 to access your db inside your code

{
  "type": "postgres",
  "host": "postgresql-test",
  "port": 5432,
  "username": "admin",
  "database": "crud-node",
  "password": "changeme",
  "synchronize": true,
  "logging": true,
  "entities": ["dist/**/*.entity.js"]
}

ALSO you can take a look at this repo.

Upvotes: 4

Related Questions