Home >Backend Development >Golang >Docker Compose Postgres Connection Refused: Why Does pgAdmin Work But My Go App Fails?
[Docker Compose] Postgres Connection Error: Resolving "connection refused"
Problem:
When attempting to establish a Go connection to a Postgres database running in Docker Compose, the error "connection refused" is encountered, despite being able to connect successfully from pg-admin.
Reason:
The connection string references the database hostname as "postgres," which matches the service name in Docker Compose. However, the actual container name is "database."
Solution:
To resolve the issue, either rename the database container in the Docker Compose file to "postgres" or explicitly specify the hostname:
database: build: database restart: always hostname: postgres # Add this line
Additional Considerations:
Connection String: Ensure that the connection string in Go code (_str_) includes the correct hostname:
str := fmt.Sprintf("database://%s:%s@%s:%s/%s?sslmode=disable", user, pass, "postgres", port, dbname) # Update the hostname to "postgres"
The above is the detailed content of Docker Compose Postgres Connection Refused: Why Does pgAdmin Work But My Go App Fails?. For more information, please follow other related articles on the PHP Chinese website!