Home >Backend Development >Golang >Why Does My Go Application Get a 'Connection Refused' Error When Connecting to a Docker Compose Postgres Database?
Docker Compose Postgres Connection Refusal
Problem:
When attempting to establish a database connection from Go to a Postgres database running on Docker Compose, the error "dial tcp 127.0.0.1:5432: connect: connection refused" occurs.
Solution:
The issue stems from incorrect hostname referencing in the connection string.
Hostname Referencing:
The database hostname is referenced as "postgres" in the "POSTGRES_HOST" environment variable. However, the container/service name for the database in the docker-compose file is "database."
Resolution:
To resolve the issue, there are two options:
Network Configuration (Optional):
For improved isolation and communication between services, it is recommended to create a dedicated network for database and application containers. To do this:
Example:
database: # ... networks: - mynet backend: # ... networks: - mynet networks: mynet: name: my-shared-db-network
The above is the detailed content of Why Does My Go Application Get a 'Connection Refused' Error When Connecting to a Docker Compose Postgres Database?. For more information, please follow other related articles on the PHP Chinese website!