Docker-Compose: Connection to Postgres Refused
When connecting to Postgres via pg-admin from within a Docker-compose setup, users may encounter a refusal to establish a connection from their Go application. This article delves into this issue and provides a solution.
The issue arises when the database URL generated by the Go application references the database hostname as "postgres," while the actual container/service name is "database." To resolve this, consider either changing the name within the compose.yaml file or explicitly defining a hostname field. For example:
database: build: database restart: always hostname: postgres
Alternatively, create a dedicated network for multiple container services to communicate with each other, preventing connection issues. Add a "networks" section to each service's configuration and define the network at the end of the compose.yaml:
database: # ... networks: - mynet backend: # ... networks: - mynet networks: mynet: name: my-shared-db-network
By implementing these changes, you can establish a connection between your Go application and Postgres while also ensuring efficient communication within the Docker-compose environment.
The above is the detailed content of Why Does My Go Application Refuse a Postgres Connection in Docker Compose?. For more information, please follow other related articles on the PHP Chinese website!