0

I can connect to my local Postgres DB in my web app, but NOT if I am running the web app inside of a Docker container.

  • Web app running inside of a Docker container
  • Postgres running in the Host machine

I am not sure if it is related to the Postgres connection settings or to the Docker network settings.

Follow my settings and commands:

Host:

  • OSX 10.11.6
  • PostgreSQL 9.6

Docker container

  • Docker 1.13.1
  • Docker-machine 0.9.0
  • Docker container OS: python:3.6.0-alpine
  • Python 3.6 + psycopg2==2.7

postgresql.conf:

listen_addresses = '*'

pg_hba.conf

host    all             all             127.0.0.1/32            trust
host    all             all             0.0.0.0/0               trust
host    all             all             172.17.0.0/24           trust
host    all             all             192.168.99.0/24       trust

With Docker network in HOST mode

docker run -i --net=host -h 127.0.0.1 -e POSTGRES_URI=postgresql://127.0.0.1:5432/db my/image

Error:

could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

With Docker network in BRIDGE mode

docker run -i --add-host=dockerhost:`docker-machine ip ${DOCKER_MACHINE}` -e POSTGRES_URI=postgresql://dockerhost:5432/db -p 8000:8000 -p 5432:5432 my/image

Error:

server closed the connection unexpectedly
This probably means the server terminated abnormally before or while processing the request.

Any ideas?

1
  • Any particular reason for not running postgres in a container as well? Commented Mar 4, 2017 at 3:17

1 Answer 1

1

There is a note about doing this in the docs

I want to connect from a container to a service on the host

The Mac has a changing IP address (or none if you have no network access). Our current recommendation is to attach an unused IP to the lo0 interface on the Mac; for example: sudo ifconfig lo0 alias 10.200.10.1/24, and make sure that your service is listening on this address or 0.0.0.0 (ie not 127.0.0.1). Then containers can connect to this address.

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

2 Comments

I was able to connect to the external service with this tip, thanks! I missed that.
@PauloCheque, glad I could help. Don't forget to mark answers that solve your problem as correct. That helps other people who come across your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.