dousi1970
2016-12-19 14:18
浏览 1.4k

无法连接到Docker容器内的postgresql

I'm writing a go app which is dockerized in 2 containers: db and app.

while starting containers 'docker-compose up' I see the message: dial tcp: lookup dbpgsql on 127.0.0.11:53: no such host

DB_ENV_DB=cldb
DB_ENV_USER=cldb
DB_ENV_PASS=cldb
DB_PORT_5432_TCP_ADDR=dbpgsql
DB_PORT_5432_TCP_PORT=5432

here is my docker-compose.yml

version: '2'
services:
  server:
    hostname: app
    image: golang:1.7.3-alpine
    build: ./server/
    privileged: true
    container_name: server
    command: go run server.go
    volumes:
      - ../src/:/go/src/
      - ../server.go:/go/server.go
    links:
      - db:db
    ports:
     - '8080:8080'
   env_file: environment

 db:
   hostname: dbpgsql
   image: postgres:latest
   container_name: db
   environment:
      POSTGRES_USER: cldb
      POSTGRES_PASSWORD: cldb
      POSTGRES_DB: cldb
    ports:
      - '5432:5432'
   volumes:
     - ./data:/docker-entrypoint-initdb.d

The app fails here when DB.Ping() is executed:

func InitDB(dataSourceName string) {
    var err error
    DB, err = sql.Open("postgres", dataSourceName)
    if err != nil {
       log.Panic(err)
    }

    if err = DB.Ping(); err != nil {
       log.Panic(err)
    }

    DB.SetMaxIdleConns(100)
}

图片转代码服务由CSDN问答提供 功能建议

我正在编写一个go应​​用,该应用在2个容器中被docker化:db和app。

在启动容器“ docker-compose up”时,我看到消息:拨号tcp:在127.0.0.11:53上查找dbpgsql:没有这样的主机 < pre> DB_EN​​V_DB = cldb DB_EN​​V_USER = cldb DB_EN​​V_PASS = cldb DB_PORT_5432_TCP_ADDR = dbpgsql DB_PORT_5432_TCP_PORT = 5432

这是我的docker-compose.yml < / p>

 版本:'2'
服务:
服务器:
主机名:app 
图像:golang:1.7.3-alpine 
构建:./server/ \  n特权:true 
 container_name:服务器
命令:运行server.go 
卷:
-../src/:/go/src/
-../server.go:/go/server  .go 
链接:
-db:db 
端口:
-'8080:8080'
 env_file:环境
 
 db:
主机名:dbpgsql 
图像:postgres:latest 
 container_name  :db 
环境:
 POSTGRES_USER:cldb 
 POSTGRES_PASSWORD:cldb 
 POSTGRES_DB:cldb 
端口:
  -'5432:5432'
卷:
-./data:/docker-entrypoint-initdb.d
  
 
 

在DB.Ping时应用在此处失败 ()已执行:

  func InitDB(dataSourceName字符串){
 var err错误
 DB,err = sql.Open(“ postgres”,dataSourceName)
  err!= nil {
 log.Panic(err)
} 
 
如果err = DB.Ping();  err!= nil {
 log.Panic(err)
} 
 
 DB.SetMaxIdleConns(100)
} 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douduan5073 2016-12-19 14:30
    已采纳

    You can connect to database with the service name (or alias name given in links options), in your case it's db. Hostname option sets the hostname by which the container knows itself. But it will not appear in docker ps nor in the /etc/hosts file of any other container. (https://docs.docker.com/engine/userguide/networking/default_network/configure-dns/)

    点赞 评论

相关推荐 更多相似问题