【发布时间】:2017-10-15 12:30:55
【问题描述】:
我正在尝试关注tutorial 并设置一个 postgresql 容器。
我有以下脚本:
#!/bin/bash
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$@"
until psql -h "$host" -U "postgres" -c '\l'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
还有以下docker-compose.yml:
version: '2'
services:
server:
build: .
ports:
- 3030:3030
depends_on:
- database
command: ["./setup/wait-for-postgres.sh", "localhost:5432", "--", "node", "src"]
database:
image: postgres
environment:
- "POSTGRES_USER=postgres"
- "POSTGRES_PASSWORD=postgres"
- "POSTGRES_DB=tide_server"
ports:
- 5432:5432
问题是当我运行docker-compose up 时出现以下错误:
server_1 | Postgres is unavailable - sleeping
server_1 | psql: could not translate host name "192.168.64.2:5432" to address: Name or servi
ce not known
server_1 | Postgres is unavailable - sleeping
server_1 | psql: could not translate host name "192.168.64.2:5432" to address: Name or servi
ce not known
server_1 | Postgres is unavailable - sleeping
server_1 | psql: could not translate host name "192.168.64.2:5432" to address: Name or servi
ce not known
现在我尝试将主机设置为database、localhost、0.0.0.0,甚至是容器 IP 但没有任何效果,我不知道它应该是什么或如何调试它,我不是 100 % 确定 docker-compose 如何链接容器。
【问题讨论】:
-
像
host:port这样的命令参数传递是wait-for-it.sh 脚本的一个特性:github.com/vishnubob/wait-for-it/blob/master/wait-for-it.sh#L74 这不是 psql 为你拆分出来的,psql 希望你通过-p选项的端口。也就是说,5432 是默认值,因此不是强制性的。在您的示例中,您使用database作为主机,因此在 docker compose 网络中,该名称应该解析。上面发布的错误都显示了“192.168.64.2:5432”的用法,如果您使用“数据库”会发生什么?我怀疑 psql 在等待密码时会失败。 -
是的,
psql: fe_sendauth: no password supplied会失败,我在答案中提供了完整的解决方案。 -
如果你使用 5433:5432 它不会暴露 5433 端口,你会得到连接被拒绝。只要将其更改为“5433:5432”,它就会起作用。用官方 postgres:13.2 镜像测试(13 也是)。
标签: postgresql docker localhost docker-compose host