当我尝试连接到我的 dockerized postgres 数据库时,我不断通过 typeORM DataSource 连接收到此错误。
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'],
});
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'
}
到目前为止我尝试过的:
psql -h localhost --port 5432 -U postgres
=> 成功了!lsof -i :5432
=> com.docke 27212 sbagherzadeh 329u IPv6 0x81fea2c6d7e20ca9 0t0 TCP *:postgresql (LISTEN)
localhost
或 127.0.0.1
如果有人可以帮忙,我已经没有解决方案了:)!
postgres
位于 postgres-db-network
上,但 node_app
不在。所以他们没有联网。所以他们不能说话。因此,docker 不会将它们的容器名称作为可解析的主机名相互公开。