我正在尝试运行一个依赖于 postgresql 数据库的服务,但我不知道如何将两者链接在一起/连接。
我“依赖”数据库,这似乎意味着我应该能够使用服务名称作为数据库主机名(即due_database
)但每当我这样做时,我都会收到错误:
could not translate host name "due_database" to address: Name or service not known
这是怎么回事?
version: '3'
services:
due:
restart: always
build:
context: ./
dockerfile: ./docker/bot/Dockerfile
command: ./due
depends_on:
- due_database
due_database:
build:
context: ./
dockerfile: ./docker/database/Dockerfile
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD="docker"
entrypoint: /entry.sh
volumes:
- ./.dueutil_db:/dueutil_data
Update:
version: '2.1'
services:
due:
restart: always
build:
context: ./
dockerfile: ./docker/bot/Dockerfile
entrypoint: /entry.sh
command: ./due
depends_on:
due_database:
condition: service_healthy
environment:
- PGPASSWORD="docker"
due_database:
image: postgres:11
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD="docker"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
volumes:
- ./.dueutil_db:/var/lib/postgresql/data
我通过将创建数据库脚本移到 postgres 映像之外解决了第一个问题,因为这与 postgres 入口点冲突。
但是我仍然不知道如何从应用程序的容器连接到数据库。
我目前正在尝试psql -U postgres -h due_database postgres -f <sql script>
但我刚刚得到:
psql: could not connect to server: Connection refused
Is the server running on host "due_database" (172.18.0.2) and accepting
TCP/IP connections on port 5432?
注意我确实看到了:psql:无法将主机名“somePostgres”转换为地址:名称或服务未知但这个问题似乎已经过时并且没有得到任何好的答案。