hustas88
hustas88

Reputation: 307

Can not connect to postgresql which is inside of a docker container

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)
}

Upvotes: 4

Views: 4233

Answers (2)

user2047665
user2047665

Reputation: 81

In my case, I was using container_name in my post-gres service and thats what was required to be set as hostname while connecting to db in application

Upvotes: 0

Lauri
Lauri

Reputation: 4679

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/)

Upvotes: 4

Related Questions