Search code examples
postgresqldockerflaskpsycopg2

Connect to PostgreSQL from Flask app in another docker container


On a virtual machine I have 2 docker containers running with the names <postgres> and <system> that run on the network with name <network>. I can't change options in these containers. I have created a flask application that connects to a database and outputs the required information. To connect from local computer I use

conn = psycopg2.connect(
   database="db", user='user1', password='user1_passwd'
   host='<VM_ip>', port='<db_port>',
   sslmode='require',
   sslcert='./user1.crt',
   sslkey='./user1.key')

and it worked great.
But, when I run my application on the same VM and specify

conn = psycopg2.connect(
   database="db", user='user1', password='user1_passwd'
   host='<postgres>.<network>', port='<db_port>',
   sslmode='require',
   sslcert='./user1.crt',
   sslkey='./user1.key')

I get an error:

psycopg2.OperationalError: could not parse network address \"<postgres>.<network>\": Name or service not known.

Local connections are allowed in pg_hba, the problem is in connecting from the new container in VM. Here are the settings of my new container:

version: '3'

services:
  app:
    container_name: app
    restart: always
    build: ./app
    ports:
      - "5000:5000"
    command: gunicorn -w 1 -b 0.0.0.0:8000 wsgi:server

I tried to make the same connection as from the local computer, specifying the VM_ip, but that didn't help either. I also tried to specify the <postgres> container ip instead of its name in the host=, but this also caused an error.

Do you know what could be the problem?


Solution

  • You need to create a network first which you will use to communicate between containers. You can do that by:

    docker network create <example> #---> you can name it whatever you want
    

    Then you need to connect both containers with the network that you made.

    docker run -d --net example --name <postgres_container> <postgres_image>
    docker run -d --net example --name <flask_container> <flask_image>
    

    You can read more about the docker network in its documentation here:

    https://docs.docker.com/network/