dongyin8009 2019-06-02 02:34
浏览 81
已采纳

Go应用程序和Postgres之间的Docker-compose通信问题

I'm trying to set up my basic Go app to make a connection to a Postgres database. I have both being spun up as services using docker-compose. When I run docker-compose up, I end up getting a timeout error when the Go app tries to connect to Postgres. Something is wrong or missing that is preventing my Go app from being able to make a connection to Postgres.

docker-compose.yml

services:
  api:
    build: .
    ports:
      - 8080:8080
    environment:
      - GOPATH=/go # set up GOPATH in container to reference modules
      - DB_USERNAME=${DB_USERNAME}  # this is `postgres`
      - DB_PASSWORD=${DB_PASSWORD}  # this is an empty string
    volumes:
      - $GOPATH/pkg/mod:/go/pkg/mod

  db:
    image: postgres:11.3
    ports:
      - 5432:5432
    volumes:
      - ../db/postgres/data:/var/lib/postgresql/data

main.go

import (
    "database/sql"
    "log"

    "github.com/lib/pq"
)

func main() {
    dbConn, err := sql.Open("postgres", "sslmode=disable host=db port=5432 user=postgres dbname=postgres connect_timeout=30")
    if err != nil {
        log.Fatalf("error defining connection to database: %v", err)
    }
    defer func() { _ = dbConn.Close() }()

    // This forces the connection to be created
    err = dbConn.Ping()
    if err != nil {
        log.Fatalf("error opening connection to database: %v", err)
    }
    log.Println("Never get here because we timeout...")
}

I expect to make the connection and get to the end of main.go. Instead, I get the following error: error opening connection to database: dial tcp <container-ip>:5432: i/o timeout

I've tried starting the Postgres container first (docker-compose up db), to make sure it was ready, then spinning up my Go app (docker-compose up api). Same error.

I've logged into the Postgres container and connected to Postgres by using the connection string, manually: psql "sslmode=disable host=localhost port=5432 user=postgres dbname=postgres connect_timeout=30" (notice that only the host field changed from db to localhost, as compared to the connection string used in the main.go code, above). This works, so the connection string is fine.

When logged in to the Postgres container, I've verified that there is a database named postgres that I use in the dbname field in the connection string:

postgres=# \l
                                 List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges   
-----------+----------+----------+------------+------------+-----------------------
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
           |          |          |            |            | postgres=CTc/postgres
(3 rows)

I've also tried making my own database and using that in my connection string.

In the main.go code, above, I've also tried switching the sql.Open line out for the alternative approach:

c, err := pq.NewConnector("sslmode=disable host=db port=5432 user=postgres dbname=postgres connect_timeout=30")
dbConn = sql.OpenDB(c)

If I run my app with go run main.go (not running in a container) and make sure to switch the host to localhost in the Postgres connection string, it works fine. So, it's something to do with the communication between my app's container and the Postgres container.

  • 写回答

2条回答 默认 最新

  • dsc6517 2019-06-02 15:02
    关注

    Take a look to my example docker-compose file (with mysql, postgres is the same way)

    version: '3'
    services:
      application:
        image: dangminhtruong/truyencotich:v1
        container_name: truyencotich
        ports:
        - 80:8080
        depends_on:
        - mysql
        volumes:
         - .:/app
        tty: true
        restart: always
        expose:
          - 8080
      mysql:
        image: mysql:5.7
        container_name: truyencotichDB
        environment:
          MYSQL_DATABASE: rivendell
          MYSQL_USER: truyencotich
          MYSQL_PASSWORD: 789852
          MYSQL_ROOT_PASSWORD: 789852
        volumes:
          - ./database/exported/exported.sql:/docker-entrypoint-initdb.d/rivendell.sql
        expose:
        - 3306
        ports:
        - 3306:3306
    

    And then I connect by following (we connect to mysql db by host name now is mysql container name - truyencotichDB)

    package database 
    
    import (
        "database/sql"
        _ "github.com/go-sql-driver/mysql"
    )
    
    func DBConn() (db *sql.DB) {
        dbDriver := "mysql"
        dbUser := "root"
        dbPass := "789852"
        dbName := "rivendell"
        db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@tcp(truyencotichDB)/"+dbName)
        if err != nil {
            panic(err.Error())
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵