2

I can't get one of my containers (service) to connect to the postgres database container through docker. It seems to be complaining about using the wrong database...(I'm using node.js with the 'pg' and 'pg-promise' libraries.).

My postgres connection info

const pg = require('pg');
const pgp = require('pg-promise')();

var config = {
  user: 'root',
  password: 'myPassword',
  database: 'myDb',
  host: 'database',
  port: 5432
};
const db = pgp(config);

Error when docker attempts to connect to the database

{ Error: getaddrinfo ENOTFOUND database database:5432
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'database',
  host: 'database',
  port: 5432 }

I know that by default the container has the same hostname as the service name, but that didn't work (my service name is "database"). Anything I'm missing?

docker-compose.yml

version: '3'

services:
  myapp:
    build: My-App/
    depends_on:
      - 'database'
    ports:
      - '5000:5000'

  database:
    image: postgres:11.5
2
  • did you expose 5432 in your database container ? Commented Sep 6, 2019 at 5:28
  • I tried adding 'ports: "5432:5432"' under "database" in the docker-compose.yml file, but still didnt' work :( Commented Sep 6, 2019 at 19:26

1 Answer 1

3

So I eventually found the answer, so I thought I'd share:

The reason Docker couldn't automatically connect to Postgres was because Postgres was still initializing (and not receiving connection requests while it booted up).

One solution I found was to artificially delay Docker's connection attempt (basically wait until Postgres is ready before attempting to connect).

EDIT: Docker-compose version 3 now has docs on how to control which containers start first: https://docs.docker.com/compose/startup-order/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.