Search code examples
pythonpostgresqldockerubuntu

Allow Docker container to access local/host Postgres database


I had a project using Python and a Postgres database installed on Windows. Now I need to transfer this to Ubuntu and turn the Python file that I used earlier into a Docker container. I tried to do this, but something doesn't work out for me. First I'll describe the contents of my project.

Contents of the project folder:

  • Dockerfile
  • webhook_receiver.py

webhook_receiver.py:

from flask import Flask,reuqest,jsonify
import psycopg2
import select
import json
import psycopg2.extensions
import requests
import pycopg2.extras as extras
app=Flask(__name__)
@app.route('/webhook',methods=['POST'])
def webhook():
    data=request.json
    print(f"received webhook data:{data}")
    return jsonify({"status":"success"}),200
def webhook_receiver():
    conn=psycopg2.connect("host=127.0.0.1 dbname=webhook_db user=postgres password=***** port=5432")
conn.setisolation_level(psycopg2.exrensions.ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute("LISTEN my_channel")
print("Waiting")
while True:
    if select.select([conn],[],[],5)==([],[],[]):
       continue
conn.poll()
while conn.notifies:
     notify=conn.notifies.pop(0)
      print(f"Received notification {notify.payload} from {notify.channel}")
      response = requests.post('http://localhost:5000/webhook',json=notify.payload)
      print(f"API response: {response.status_code} - {response.text}")
if __name__="__main__":
    webhook_receiver()
    from threading import Thread
    Thread(target=webhook_receiver).start()
    app.run(host='0.0.0.0', port=5000)

Dockerfile:

#Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY . /app
RUN pip install psycopg2-binary requests flask
EXPOSE 5000
CMD ["python","webhook_receiver.py"]

When I run the command docker build -t webhook_receiver . everything is fine, but when I run the command docker run --rm -p 5000:5000 webhook_receiver & the following error pops up:

psycopg2.OperationalError:connection to server at "127.0.0.1", port 5432 failed:Connection refused. Is the server running on that host and accepting TCP/IP connections?

In the postgresql.conf file, there is a '*' in the listen_addresses line. How to fix this error?

Edit: I changed this:

conn=psycopg2.connect("host=172.0.0.1 ....... port=5432")

to this:

conn=pyscopg2.connect("host=host.docker.internal ...... port=5432")

sometimes after the internal I put :5432, but the error does not change: psycopg2.OperationalError:could not translate host name "host,docker,internal" to address: Name or service not known


Solution

  • Try running container like this:

    docker run --rm -p 5000:5000 --add-host=host.docker.internal:host-gateway webhook_receiver &
    

    It should add host.docker.internal to /etc/hosts in container.

    Then as endpoint add host=host.docker.internal