gpt4 book ai didi

postgresql - 如何从主机连接到 Docker Postgres 容器

转载 作者:行者123 更新时间:2023-11-29 11:56:18 31 4
gpt4 key购买 nike

我按照以下说明搭建了一个 Rails 开发环境 https://docs.docker.com/compose/rails/

它可以工作,但我无法从主机连接到 Postgres 服务器。我正在运行 macOS High Sierra。当我运行 docker container ls我看到 5432/tcp作为 Postgres 容器的端口。请注意,5432 前面没有列出 IP。当我运行 docker network inspect <postgress_container_ID> 时我得到 172.18.0.2 作为 IP。

但是当我运行 psql -h 172.18.0.2 -p 5432 -U postgres我明白了

xpsql: could not connect to server: Operation timed out
Is the server running on host "172.18.0.2" and accepting
TCP/IP connections on port 5432?

我做错了什么?

最佳答案

通过查看您的详细信息5432/tcp,在我看来您还没有导出端口号5432

如果你有导出端口,那么它应该是这样的。

 0.0.0.0:5432->5432/tcp

然后使用 HOST IP 地址(您本地的 mac 机器 ip)您应该能够连接,如果仍然无法连接,请分享您的 docker 命令 - 您是如何运行容器的?

Docker 撰写文件

version: '3'
services:
db:
image: postgres
ports:
- "5432:5432"
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/airbnb
ports:
- "3000:3000"
depends_on:
- db

在您的 docker-compose 文件中,您没有公开端口号 5432,因此从外部您将无法连接 Postgres 数据库。

尝试在您的 docker-compose 文件中添加 ports: - "5432:5432"。然后使用您的机器 IP 地址,您应该能够连接数据库。

关于postgresql - 如何从主机连接到 Docker Postgres 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385824/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com