登录
首页 >  Golang >  Go问答

连接不上 docker-compose 中的 postgres 容器的 Go 应用程序

来源:stackoverflow

时间:2024-02-29 17:30:26 374浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《连接不上 docker-compose 中的 postgres 容器的 Go 应用程序》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我一直在尝试使用 docker-compose 将我的 go 应用程序连接到 postgresql 数据库。

这是我的 web 服务器 dockerfile

from golang:latest

run mkdir /app
copy . /app
workdir /app
run go mod download
expose 5000
cmd ["go","run","main.go"]

这是我的 docker-compose.yml 文件

version: '3'
services:
  db:
    image: postgres:latest
    restart: always
    network_mode: bridge
    environment:
      postgres_user: factly
      postgres_password: qwertyui
      postgres_db: factly
    ports:
      - "5432:5432"
  server:
    build: .
    depends_on:
      - db
    ports:
      - "5000:5000"

但是我无法连接到 postgresql 数据库,因为它给出了连接被拒绝的错误消息

Go serverStarting factly_db_1 ... 
Starting factly_db_1 ... done
Recreating factly_server_1 ... 
Recreating factly_server_1 ... done
Attaching to factly_db_1, factly_server_1
db_1      | 
db_1      | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1      | 
db_1      | 2020-08-19 06:11:17.151 UTC [1] LOG:  starting PostgreSQL 12.4 (Debian 12.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1      | 2020-08-19 06:11:17.151 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1      | 2020-08-19 06:11:17.152 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1      | 2020-08-19 06:11:17.266 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1      | 2020-08-19 06:11:17.906 UTC [26] LOG:  database system was shut down at 2020-08-19 05:56:39 UTC
db_1      | 2020-08-19 06:11:18.213 UTC [1] LOG:  database system is ready to accept connections
server_1  | host=127.0.0.1 port=5432 user=factly password=qwertyui dbname=factly sslmode=disable
server_1  | 2020/08/19 06:11:21 dial tcp 127.0.0.1:5432: connect: connection refused
server_1  | exit status 1
factly_server_1 exited with code 1

我尝试仅运行 postgres 容器并将其与 go 应用程序连接,该应用程序工作得很好,但是在容器内运行 go 应用程序会出现相同的错误(这让我觉得 go web 服务器容器无法在外部连接)这是网络)。 我该如何纠正这个问题?


解决方案


我猜问题是您正在尝试从 go 程序连接到 127.0.0.1,而不是使用数据库容器 db 的主机名。

终于介绍完啦!小伙伴们,这篇关于《连接不上 docker-compose 中的 postgres 容器的 Go 应用程序》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>