Home > Software design >  How Python app can find a Postgres Database using Docker-compose
How Python app can find a Postgres Database using Docker-compose

Time:09-29

I had a problem to connect the Docker Python application to Docker Postgres database. And I solved using the solution of put the two containers in the same network and use the "Docker Names" in the DBHOST on Python app.

docker network create <network_name>

Now I want to put this 2 Dockers containers into one

docker-compose

But now my application don't find the database. The connection string is:

from flask import Flask, request, render_template


app = Flask(__name__)


#import decimal
import psycopg2

DBHOST = "mypostgres"
#DB_HOST = "localhost"
DB_NAME = "correntista"
DB_USER = "postgres"
DB_PASS = "mysecretpassword"
DB_PORT = 5432

conn = psycopg2.connect(dbname = DB_NAME, user = DB_USER, password = DB_PASS, host = DBHOST, port = DB_PORT)

cur = conn.cursor()

The name of container change when I run the docker-compose

       Name                     Command              State     Ports  
----------------------------------------------------------------------
banco_api_1          python ./app.py                 Exit 1           
banco_mypostgres_1   docker-entrypoint.sh postgres   Up       5432/tcp

But I tryied to use "banco_mypostgres_1" in the DBHOST but nothing happened.

This is my docker-compose.yml

version: "3"

#volumes:

networks:
    backend:

services:
    
    mypostgres:
            image: "mypostgres"
            networks:
                - backend
            environment:
                - bind-address=0.0.0.0
                - POSTGRES_PASSWORD=password 
                - POSTGRES_DB=db_name

    api:
            image: "my-docker_flask2"
            networks:
                - backend
            environment:
                - DBHOST=mypostgres 
            depends_on:
                - mypostgres

I appreciate your help!

CodePudding user response:

you will have to explicitely specify the container name here (for postgres) in order for the other container to connect to it.

On the network you created containers can communicate with each other using container names which in your case will be some auto generated container names .

For this to work your postgres container name and your DBHOST name must be same.

you can edit your docker-compose file and add the container name for postgres like this:

services:
    
    mypostgres:
            image: "mypostgres"
            container_name: mypostgres
            networks:
                - backend
            environment:
                - bind-address=0.0.0.0
                - POSTGRES_PASSWORD=password 
                - POSTGRES_DB=db_name
  • Related