Home > Software engineering >  Depending on HOST NAME value for PostgreSQL database in my .env file I get different result
Depending on HOST NAME value for PostgreSQL database in my .env file I get different result

Time:10-18

I have created a PostgreSQL with a web server DOCKER CONTAINER and my app running with an API to manage all the endpoints.

The link of my git repo is: https://github.com/JulioValderrama/store-front-project.git

But I am facing problems with the connections with the Database, as depending on the Postgres HOST name value in my .env file one of the two servers (one local running in PORT 4000 and the web server running in the docker container in PORT 3000) will work or will fail.

I have tried the next:

Local server running in PORT 4000

Docker web server running in PORT 3000

HOST "127.0.0.1"

  • Going to¨:
http://localhost:3000/

Works fine and get response, now when trying to connect it to any of my database API:

http://localhost:3000/products
  • I get the error:
"Could not get PRODUCTS. Error: Error: connect ECONNREFUSED 127.0.0.1:5432"
  • Going to:
http://localhost:4000

Works fine and get response, now when trying to connect it to any of my database API:

http://localhost:4000/products

It works! I get the list of all my products!!

HOST "postgres"

I put "postgres" because I read online that you have to name HOST as the postgres docker image created, which is my case. And it works for the remote server.

  • Going to:
http://localhost:3000

Works fine and get response, then when trying to connect it to database API:

http://localhost:3000/products
  • It works!! It gives me the list of my products !!

  • Going to:

http://localhost:4000

Works fine and get response, then when trying to connect it to database API:

http://localhost:4000/products

It gives me the error:

"Could not get PRODUCTS. Error: Error: getaddrinfo ENOTFOUND postgres"

So it seems like there is an error when trying to connect to the database due to the server or the HOST name, I have no idea....

CodePudding user response:

In docker-compose.yaml you have linked your machine 5432 to containers 5432 port.

If you are using docker container and want to reach postgres, use postgres as POSTGRES_HOST value.

If you are running application outside the docker environment use 0.0.0.0, 127.0.0.1.

Make sure you haven't installed postgres locally

brew uninstall postgres
  • Related