I keep getting this error through my typeORM DataSource connection when I'm trying to connect to my dockerized postgres database.
docker-compose.yml:
node_app:
build: ./node
container_name: node
environment:
- PGHOST=postgres
- NODE_ENV=development
- PORT=4000
depends_on:
postgres:
condition: service_healthy
command: sh -c "npm start"
volumes:
- ./node:/home/node/app:cached
ports:
- '4000:4000'
postgres:
image: postgres
container_name: postgres
restart: always
environment:
POSTGRES_DB: job_matching
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- 5432:5432
volumes:
- ./pgdata:/var/lib/postgresql/data
- ./db/init.sql:/docker-entrypoint-initdb.d/create_tables.sql
networks:
- postgres-db-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
interval: 1s
timeout: 5s
retries: 10
app.ts:
const dataSource = new DataSource({
type: 'postgres',
host: process.env.PGHOST || 'localhost',
port: 5432,
username: 'postgres',
password: 'password',
database: 'job_matching',
entities: ['src/models/**/*.ts'],
});
Error in docker:
Error during Data Source initialization Error: getaddrinfo ENOTFOUND postgres
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'postgres'
}
What I have tried so far:
psql -h localhost --port 5432 -U postgres
=> worked !lsof -i :5432
=> com.docke 27212 sbagherzadeh 329u IPv6 0x81fea2c6d7e20ca9 0t0 TCP *:postgresql (LISTEN)
localhost
or 127.0.0.1
I'm running out of solutions if someone can help please :) !
postgres
is on the postgres-db-network
but node_app
is not. so they're not networked together. So they can't talk. Thus, docker does not expose their container names to each other as resolvable hostnames.