title: How to connect to PostgreSQL using docker-compose?
body: <p>Want to use <code>docker-compose</code> to run api application and postgresql database together. </p>
  
  <p><code>docker-compose</code> file:</p>
  
  <pre><code>version: '3'
  
  volumes:
    database_data:
      driver: local
  
  services:
    db:
      image: postgres:latest
      volumes:
        - database_data:/var/lib/postgresql/data
  
    api:
      build: ./api
      expose:
        - 8080
      ports:
        - 8080:8080
      volumes:
        - ./api:/usr/src/app/
      links:
        - db
      environment:
        - PGHOST=db
        - PGDATABASE=postgres
        - PGUSER=postgres
  </code></pre>
  
  <p>Api <code>main.go</code> file:</p>
  
  <pre><code>func main() {
      db, err = gorm.Open("postgres", "host=db port=5432 user=postgres dbname=postgres")
    // ...
  }
  </code></pre>
  
  <p>When run the services, got message from log:</p>
  
  <pre><code>api_1     | [GIN] 2018/06/22 - 07:31:10 | 404 |      1.4404ms |      172.20.0.1 | GET      /posts
  api_1     |
  api_1     | (sql: database is closed)
  api_1     | [2018-06-22 07:31:10]
  api_1     |
  api_1     | (sql: database is closed)
  api_1     | [2018-06-22 07:31:10]
  api_1     | [GIN] 2018/06/22 - 07:32:14 | 403 |        15.6µs |      172.20.0.1 | GET      /posts
  db_1      | 2018-06-22 07:34:27.296 UTC [81] FATAL:  role "root" does not exist
  db_1      | 2018-06-22 07:34:36.897 UTC [90] FATAL:  role "root" does not exist
  </code></pre>
  
  <p>Does this way not good? <code>host=db</code> in the connection string? Since <code>db</code> is the docker compose service name.</p>
  
  <hr>
  
  <h1>Add</h1>
  
  <p>It can work:</p>
  
  <p><a href="https://docs.docker.com/samples/library/postgres/#-or-via-psql" rel="noreferrer">https://docs.docker.com/samples/library/postgres/#-or-via-psql</a></p>