3

I can confirm docker container is running:

Name                      Command                  State     Ports
-----------------------------------------------------------------------------------------------
adminer_1             entrypoint.sh docker-php-e ...   Up      0.0.0.0:8080->8080/tcp
db_1                  docker-entrypoint.sh postgres    Up      5432/tcp

I can also connect to the db via adminer (image below):

enter image description here

But then I cannot connect from outside docker with Python:

# import the connect library from psycopg2
from psycopg2 import connect

table_name = "trips"

# declare connection instance
conn = connect(
    dbname = "postgres",
    user = "postgres",
    host = "localhost", #known ip 172.20.0.2
    password = "password"
)

# declare a cursor object from the connection
cursor = conn.cursor()

# execute an SQL statement using the psycopg2 cursor object
cursor.execute(f"SELECT * FROM {table_name};")

# enumerate() over the PostgreSQL records
for i, record in enumerate(cursor):
    print ("\n", type(record))
    print ( record )

# close the cursor object to avoid memory leaks
cursor.close()

# close the connection as well
conn.close()

Error raised:

psycopg2.OperationalError: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Connection refused
        Is the server running on host "localhost" (fe80::1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?

In also tried checking the ip for with postgres is listening:

docker inspect db_1 | grep "IPAddress"
            "SecondaryIPAddresses": null,
            "IPAddress": "",
                    "IPAddress": "172.20.0.2",

And replaced the host in my python script with 172.20.0.2, still I cannot connect.

1 Answer 1

2

Your docker containers "collection" is only exposing (forwarding) one port to the outside world (aka your localhost); the 8080 that is your adminer website. So you can get to that, and that being on the same internal network as the DB can find the DB, but you can't get to the DB as the port is not exposed/forwarded.

You will want to forward the DB port in the same manner as you are for the web port. Note that in your first screenshot, you can see that adminer_1 is forwarding 8080 to the outside, while the db_1 is not forwarding.

If you are using docker-compose you likely want to add a:

ports:
  - "5432:5432"

to your postgres container specification.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct! That solves the problem, many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.