How can I connect to a PostgreSQL instance from a container using localhost?

0
0
Asked By CuriousCoder42 On

I'm working on upgrading my Amazon RDS with a blue/green deployment and need to test my app locally while pointing it at the green instance. For our in-house applications, we leverage AWS SSM to access a bastion host, which we then map to port 9000. This setup allows clients on the host machine, like pgAdmin and psql, to connect using localhost:9000 without issues.

However, I have a third-party app that runs inside a container and only relies on config files. I want this app to ultimately point to localhost:9000 as well. I've tried connecting using localhost, 0.0.0.0, and host.docker.internal, and even set the --add-host="host.docker.internal:host-gateway" flag, but nothing seems to work. When I exec into the container and try using psql, I get a connection refused error, indicating that I can't connect to "host.docker.internal".

Is this connection method only viable for the Docker Desktop app? If not, what steps can I take to successfully connect my containerized app to PostgreSQL?

2 Answers

Answered By ContainerCaptain On

One approach could be to run your container in host network mode and connect it directly using the IP address and port. Just keep in mind that host network mode has its drawbacks, so be cautious with how it's set up.

Answered By DockerDude27 On

It sounds like you're running into networking issues! If you have a PostgreSQL container alongside your app, consider connecting both containers using a shared Docker network. This way, you can easily reference the PostgreSQL service by name, like postgres:9000.

If PostgreSQL isn't in a container, you should be able to use host.docker.internal or your host's IP, but make sure PostgreSQL is set to listen on 0.0.0.0 rather than just 127.0.0.1. That may fix the connection refused error.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.