P
P
PtrGrd2021-10-31 00:19:18
Python
PtrGrd, 2021-10-31 00:19:18

How to connect Python to Postgresql inside Docker?

I have a Python script that pulls data from Postgres. On the local machine, everything works, in Docker the situation is different. Can't connect Python to Postgres inside Docker container. I use docker-compose in this case, for the host parameter I take the ip of the container with the database. Still sees nothing and the script is not connected. Please help me with this issue

[Python database connection code snippet]

try:
  conn = psycopg2.connect(
    database = "users",
    user = "postgres",
    password ="postgres",
    port = "5432",
    host = "172.22.0.2"
  )
  print("[INFO] Подключение с БД установлено")
  cur = conn.cursor()
except:
  print("[INFO] Нет соединения с БД")


[ The error itself that crashes when connecting to the database ]
[INFO] Нет соединения с БД
[INFO] Не удалось узнать кол-во записей в БД
var = cur.fetchall()
NameError: name 'cur' is not defined. Did you mean: 'chr'?


[dockerfile]

FROM python:latest

WORKDIR /script/src

COPY ./ /script

COPY requirements.txt /script
COPY src /script/src

RUN apt-get update && apt-get install -y python3-pip
RUN pip install -r /script/requirements.txt
RUN chmod +x /script/src/script.py

CMD ["python3", "/script/src/script.py"]


[docker-compose.yml]
version: '3.8'

services:
 script:
  build: ./script/
  command: /script/src/script.py
  container_name: script-mtg
  depends_on:
    - db
  networks:
    - net
 db:
  image: postgres:latest
  container_name: dbpg-mtg
  restart: always
  volumes:
    - ./ .database/postgres/data:/var/lib/postgresql/data
  ports:
    - "5432"
  networks:
    - net


networks:
 net:
  driver: bridge

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
antares4045, 2021-10-31
@PtrGrd

host = "172.22.0.2"
Replace with
server="db"
Or
host="db"
(I don't remember exactly the Paycopgw syntax)
And this won't hurt you, but by explicitly creating a bridge network and binding services to it, you reproduced the default behavior, that is wrote a lot of stuff.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question