Home >Backend Development >Golang >Why Does My Go App Get 'Connection Refused' to Docker Compose Postgres When pgAdmin Connects Successfully?
Docker-Compose Postgres Connection Refused: Resolving Connection Issues
In a docker-compose setup involving Postgres DB with pg-admin and Go, you may encounter connection issues between Go and Postgres, even though pg-admin can successfully connect. This article delves into the potential causes and provides solutions.
Root Cause
The issue arises due to the hostname specified in the database connection URI. While the environment variable points to "postgres," the Docker container/service name for Postgres is "database." This discrepancy prevents Go from establishing a connection.
Solution
There are two possible solutions:
Option 1: Change the Container Name
Modify the Docker compose file to change the service name from "database" to "postgres."
database: build: database restart: always hostname: postgres
Option 2: Use an Explicit Hostname Field
Alternatively, you can add an explicit hostname field to the Postgres service configuration:
database: build: database restart: always hostname: postgres
Either of these solutions will ensure that the hostname in the connection URI matches the Postgres container's name, allowing Go to establish a successful connection.
Additional Considerations
For multiple container services to communicate effectively, you may consider creating a dedicated network. To do this, add a "networks" section to each service you want on the same network.
database: # ... networks: - mynet backend: # ... networks: - mynet
Finally, define the network at the end of the compose file:
networks: mynet: name: my-shared-db-network
The above is the detailed content of Why Does My Go App Get 'Connection Refused' to Docker Compose Postgres When pgAdmin Connects Successfully?. For more information, please follow other related articles on the PHP Chinese website!