0

I created a docker image with Postgres via Dockerfile:

FROM postgres:9.6-alpine

After I started this docker container, I'm checking that it's up and running using a connection from the different docker container that has pre-installed psql:

docker run -it --rm --link ml-postgres:postgres postgres:12.2-alpine psql --dbname mlpython -h postgres -U postgres

The result is that I'm able to connect to the first container with postgres and perform all regular operations with the postgres DB.

Troubles begin when I want to connect to the container with postgres DB from a Python script that I created locally:

import psycopg2
    
conn = psycopg2.connect(
    host="127.0.0.1",
    database="mlpython",
    user="postgres",
    password="test",
    port="5431"
)
cur = conn.cursor()
    
cursor.execute('SELECT COUNT(*) FROM mytable LIMIT 10')
cur.close()

Here is an error which I get:

> psycopg2.OperationalError: server closed the connection unexpectedly
>   This probably means the server terminated abnormally    before or while
> processing the request.

What do I miss while trying to bootstrap this simple code sample where Python interacts with Postgres?

Alex Fruzenshtein
  • 2,846
  • 6
  • 32
  • 53
  • 1
    When you start the database container, you need a `docker run -p` option for it to be accessible from outside Docker; with that connection string, something like `docker run -p 5431:5432 postgres:9.6-alpine` (the second port number must be the default port 5432 but the first can be anything). – David Maze Aug 15 '21 at 11:39

1 Answers1

0

Please read through the README.md of a docker image you use. It should answer your questions. I'm not sure, if you did, because:

  1. I see, you started psql - the client. Why, if you're going to connect from python? And have you started the server?
  2. I can't see if you exposed any container port to a host machine
madbird
  • 1,326
  • 7
  • 11