Flask app can't connect to PostgreSQL service – connection refused error

Hi everyone,

I deployed my Flask web application inside a Kubernetes cluster using a Deployment and a ClusterIP Service.

The application connects to a PostgreSQL database, which is also deployed in the same cluster as a separate Pod with its own ClusterIP service.

However, when I try to access the app, I get this error in the logs:
psycopg2.OperationalError: could not connect to server: Connection refused

My environment variable DB_HOST is set to postgres-service.

Both services and pods are running in the same namespace

Here’s what I’ve already checked:

  • Both Pods are running
  • Services are correctly named
  • The port exposed by the PostgreSQL service is 5432

Is there anything else I should verify?

Thanks in advance!

Hi!

This error usually means the Flask app is trying to connect to PostgreSQL before the database is ready to accept connections.

Here are a few things you can check:

Make sure the status is Running and READY shows 1/1
Make sure your Flask app is using postgres-service as the DB_HOST, and that this matches the name of your Service
PostgreSQL usually listens on 5432, but double-check in your PostgreSQL deployment and Service definition
Sometimes the app starts too quickly. You can use a simple shell script

Hi,

Thank you!

That was exactly the issue — the Flask app was trying to connect before PostgreSQL was ready.

I added a small wait script before starting the app, and now everything works perfectly.

Really appreciate the help!