Running docker container fails to connect to remote DB with psycopg2, but works in python interface

Viewed 19

I am running a dockerized version of my application by simple way of docker run (not running in host network mode). The goal is to make a database connection with the psycopg2 module. I am making two connections, one to a source database and one to a target database. The parameters are passed as values that are read from environment variables I pass to the container. The issue is the first connection runs fine without issue, but an exception as always thrown on the second connection object.

Relevant code snippets:

        conn_source = pg.connect(database=SOURCE_DB, 
                                        user=SOURCE_USER, 
                                        password=SOURCE_PASS, 
                                        host=SOURCE_HOST, 
                                        port=int(SOURCE_PORT),
                                        cursor_factory=RealDictCursor)
        

        conn_source.set_session(autocommit=False)
        cur1 = conn_source.cursor()

        conn_target = pg.connect(database=TARGET_DB,
                                        user=TARGET_USER, 
                                        password=TARGET_PASS, 
                                        host=TARGET_HOST, 
                                        port=int(TARGET_PORT),
                                        cursor_factory=RealDictCursor)

The error I receive is:

Traceback (most recent call last):
  File "/opt/spark/work-dir/app/dummy_app/app.py", line 99, in getPostgresConnectors
    conn_target = pg.connect(database=TARGET_DB,
  File "/opt/conda/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "dummy_host" (192.28.2.111), port 5432 failed: FATAL:  password authentication failed for user "dummy_user"

connection to server at "dummy_host" (192.28.2.111), port 5432 failed: FATAL:  password authentication failed for user "dummy_user"

This is a seemingly (to me) unexplainable bug. If I simply switch the source and target parameters, I still run into the same problem with the second connection call throwing an error, so it doesn't seem to be a specific database configuration problem. The strange thing is when I run the same code in the Python interactive shell, I have no issues creating two back to back connections. What could explain this?

Note: I would be unable to edit the pg_hba.conf files as I do not manage them.

0 Answers
Related