Error when connecting to postgres from a Python container

Viewed 105

I'm trying to set up two communicating containers as different services

  1. PostgreSQL for holding the data
  2. Python with Jupyter notebook for querying the database

Here's my Dockerfile

FROM python:3.8.8-slim-buster

RUN mkdir /project
WORKDIR /project
COPY . /project/

RUN apt-get update && \
    apt-get install --no-install-recommends -y \
    build-essential \
    bash

RUN pip install --upgrade --no-use-pep517 \
    pip \
    setuptools \
    wheel \
    jupyterlab \
    ipython-sql \
    psycopg2-binary

EXPOSE 8888

and my docker-compose.yml

version: '3'

services:
  db:
    image: postgres:12.1-alpine
    environment:
      - POSTGRES_DB=ps_db
      - POSTGRES_USER=ps_user
      - POSTGRES_PASSWORD=ps_pass
    ports:
      - "5432:5432"
  web:
    build: 
      context: .
    command: 
      jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root
    volumes:
      - .:/project
    ports:
      - "8888:8888"
    depends_on:
      - db

Although I'm pretty sure my settings are fine, whenever I run

import psycopg2
conn = psycopg2.connect(database="ps_db", user="ps_user", password="ps_pass", host="0.0.0.0", port=5432)

I get this error

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

You need to set the 0.0.0.0 IP to 'db', because the postgres runs in another container called 'db', this is the name of your service. So your conn will look like this:

conn = psycopg2.connect(database="ps_db", user="ps_user", password="ps_pass", host="db", port=5432)
Related