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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。