Home >Backend Development >Golang >Docker Compose Postgres Connection Refused: Why Does pgAdmin Work But My Go App Fails?

Docker Compose Postgres Connection Refused: Why Does pgAdmin Work But My Go App Fails?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 13:50:12394browse

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:

  • Network: Adding a dedicated network for multiple container services to communicate may improve connectivity.
  • 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn