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
Release: 2024-12-05 13:50:12
Original
399 people have browsed it

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
Copy after login

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"
    Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template