2

I'm trying to connect to postgres running locally through a python script that's running in a container. I'm setting it up like this because in the future once I deploy I'll be using a managed database service that spins up postgres.

Ideally I'm able to define a postgres url in the .env, docker-compose uses the env to set the environment variables and the application reads the postgres url.

  1. Is this the best approach or if I should have a postgres container.

  2. Best approach to achieve the flow I just described.

Tried passing POSTGRES_URL in the .env using localhost, public ip, local ip. e.g: postgresql://username:password@localhost:5432/dbname

version: "3.7"

services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    volumes:
      - "./:/usr/src/app"
    environment:
      - ENV=${ENV}
      - LOGS=${LOGS}
      - AWS_REGION=${AWS_REGION}
      - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
      - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
      - POSTGRES_URL=${POSTGRES_URL}

Expected: Connection to the local database successful.

Actual: Is the server running on host <"ip"> and accepting TCP/IP connections on port 5432?

3 Answers3

0

localhost in container means the container itself, not the docker host. If you visit postgres using localhost, it will try to find service in the container, but the container in fact did not have db service. You should set the docker host ip for local postgres.

E.g. if your docker host ip is 10.192.225.111, then the POSTGRES_URL in .env should be:

postgresql://username:password@10.192.225.111:5432/dbname
atline
  • 28,355
  • 16
  • 77
  • 113
0

I would use a postgres container in docker-compose like so:

  db:
    image: postgres:11.4
    ports:
      # In order to connect to the database from the host
      - "5432:5432"
    environment:
      - POSTGRES_PASSWORD=pw
      - POSTGRES_USER=user

In this example, you would fill in a username and password to start your container with.

Once you have this in your docker-compose.yml file, your app container will be able to access the database container through the service name. In this example, it would be db. So your connection string would be postgresql://user:pw@db:5432/dbname

alexbclay
  • 1,389
  • 14
  • 19
0

Ok, so I'm using a mac as a development machine should have mentioned that, for people struggling with the same problem. mac's docker host IP is always changing.

Changing my .env postgres url to:

postgresql://username:password@docker.for.mac.localhost:5432/dbname

seems to do the trick.