Your postgres needs to listen on all IP addresses in the container, which must be the default in the official image. Then you can connect to it using “postgres” as hostname, since this is how your compose service is called, which is automatically registered in the internal DNS service.
If you use localhost as hostname, that works only in the following casees
- Your application container also runs the postgres db server
- You are using the host network in both the application container and the postgres container
- You are using a shared network namespace between the application container and the postgres container.
You do none of those, so just use “postgres” instead of localhost.
I see you also pass POSTGRES_HOST to the postgres container. Is it supported by postgres? Even if it is, setting the same value for both doesn’t make sense to me. The app container needs to connect to a postgres server and the postgres server needs to listen on an IP, and not using a hostname.
You may want to use the POSTGRES_HOST_AUTH_METHOD as described in the image description