3

I'm having trouble connecting postgresDB to my app using docker-compose

My understanding of docker compose is that I can combine two containers so that they can communicate with each other. Suppose I have an app in the appcontainer that runs the psql command (just a one liner python script with os.command("psql")). Since the app container does not have postgres installed, it won't be able to run psql by itself. However, I thought combining two containers in docker-compose.yml would let me run psql but apparently not.

What am I missing here?

I am using 2 postgres images because I'm trying to find regression bugs between two dbms

version: "3"
services:
    app:
        image: "app:1.0"
        depends_on: 
            - postgres9
            - postgres12
        ports:
            - 8080:80 
    postgres9:
        image: postgres:9.6
        environment:
            POSTGRES_PASSWORD: mysecretpassword
            POSTGRES_USER: postgres
            POSTGRES_DB: test_bd
        ports:
            - '5432:5432'
    postgres12:
        image: postgres:12
        environment:
            POSTGRES_PASSWORD: mysecretpassword
            POSTGRES_USER: postgres
            POSTGRES_DB: test_bd
        ports:
            - '5435:5435'
1
  • From within the app container, you should be able to telnet postgres9 5432. What do you get? Commented Sep 14, 2020 at 7:07

2 Answers 2

3

Each Docker container has a self-contained filesystem. You can never directly run commands from the host or from other containers' filesystems; anything you want to run needs to be installed in the container (really, in its image's Dockerfile).

If you want to run a tool like psql, it needs to be installed in your image. You don't say what your base image is, but if it's based on Debian or Ubuntu, you need to install the postgresql-client package:

RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      postgresql-client

The right approach here is to add a standard Python PostgreSQL client library, like psycopg2, to your project's Python Pipfile, setup.py, and/or requirements.txt, and use that library instead of shelling out to psql. You will also need the PostgreSQL C library header files to install that package; instead of postgresql-client, install the Debian libpq-dev package.

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

Comments

1

In your case, those two containers with postgres instance in each, are running on different hosts (other than host with app). What you need is to specify correct host in psql command. It might look like (for postgres12 container):

PGPASSWORD="mysecretpassword" psql -h postgres12 -d test_bd -U postgres

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.