简体   繁体   中英

Connecting postgres from typeorm docker container

I am trying to connect a postgres db to nodejs using typeorm.

I tried doing this with both postgres and nodejs in localhost and it worked fine. However I am having problems when I put postgres and nodejs into docker containers.

(The "IPAdress" field in docker inspect for postgres container is 172.19.0.3)

Error from Nodejs:

web_1    | error: TypeORM connection error:  Error: connect ECONNREFUSED 172.19.0.3:5433

docker-compose.yml

services:
  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "9001:9001"
    links:
      - pg_db

  pg_db:
    image: postgres
    ports:
      - "5433:5433"
    env_file: 
      - docker.env

ormconfig.json

[
  {
    "name": "default",
    "driver": {
      "type": "postgres",
      "host": "pg_db",
      "port": 5433,
      "username": "postgres",
      "password": "test",
      "database": "testDB"
    },
    "autoSchemaSync": true,
    "entities": [
      "src/controller/entity/*.js"
    ],
    "cli": {
      "entitiesDir": "src/controller/entity"
    }
  }
]

Thanks

The default port of PostgreSQL is 5432 . Change it in your nodejs config.

The port exposing is not necessary for your nodejs, that is only to link that port to your localhost (or other IPs):

    ports:
      - "5433:5433"

You can remove them.

But, if you need to postgres listen to 5433 anyway, you will need some customization:

  pg_db:
    ...
    environment:
    - PGPORT=5433
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM