Home >Backend Development >Golang >Why Does My Go Application Get a 'Connection Refused' Error When Connecting to a Docker Compose Postgres Database?

Why Does My Go Application Get a 'Connection Refused' Error When Connecting to a Docker Compose Postgres Database?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 01:04:11147browse

Why Does My Go Application Get a

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:

  1. Change the container/service name: In the docker-compose file, change the "database" service name to "postgres."
  2. Add an explicit hostname: Add an "hostname" field to the "database" service in the docker-compose file, explicitly setting it to "postgres."

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:

  1. Add a "networks" configuration to each service that should use the shared network.
  2. Define the network at the end of the docker-compose file with a name and optional options.

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!

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