这些Docker设置有何不同?一个有效,另一个无效



我在带有映射端口的M1 Mac上的Docker中运行Postgres镜像"5432:5432";。我的应用程序可以通过调用localhost:5432从主机连接到数据库。我现在正试图在Docker中运行该应用程序,但我对看到的行为感到困惑。

此命令有效:

docker run --name api --add-host host.docker.internal:host-gateway -e DB_HOST=host.docker.internal -p 8000:8000

但是,当我试图通过像这样将api放入docker compose中来复制相同的内容时,它不起作用:

services:
postgres:
image: postgres:14.2
ports:
- "5432:5432"
networks:
- my-network

api:
image: api
environment:
DB_HOST: host.docker.internal
extra_hosts:
- "host.docker.internal:host-gateway"

连接数据库失败:

无法连接到host=host.docker.internal user=postgres database=postgres:无法接收消息(意外EOF(

我还尝试将api容器与postgres放在同一个my-network网络上,并将DB主机更改为DB容器:

api:
image: api
environment:
DB_HOST: postgres
networks:
- my-network

但这给了我一个不同的错误:

无法连接到host=postgres user=postgres database=postgres:拨号错误(拨号tcp 192.168.192.2:5432:连接:拒绝连接(

数据库正在侦听IPv4 address "0.0.0.0", port 5432IPv6 address "::", port 5432。为什么docker run命令有效,而其他两个命令无效?

由于David在评论中发现了这个问题,我建议wait-for-it解决这样的问题,立即等待一段时间,然后重新手动启动。

wait-for-it.sh通常像这个一样位于entrypoint.sh

#!/bin/sh
# Wait fot the cassandra db to be ready
./wait-for.sh cassandra:9042 --timeout=0

--timeout=0将继续等待,直到cassandra启动并运行。

并且可以直接在docker-compose.yaml中使用,如以下示例:

version: "2"
services:
web:
build: .
ports:
- "80:8000"
depends_on:
- "cassandra"
command: ["./wait-for-it.sh", "cassandra:9042"]
db:
image: cassandra

有关更多信息,您可以在Compose 中查看控制启动和关闭顺序

Wait-for-itgithub

最新更新