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 单片机 如何进行数据存储
  • ¥20 配置UGM库出现问题
  • ¥15 把Excel导入MATLAB显示错误怎么解决?
  • ¥15 Java中消息和缓存如何使用
  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站