2

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 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your quick response, it worked! Do you mind providing more details on setting the IP of "db"? I'm asking as a beginner.
Sorry for the late response! Every container has its own network, its own IPs which differs every time it restarts, and you can't access or 'guess' those IPs from another container, only by providing the name of the service and the port. Docker can resolve the names and search for the current IP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.