Fix DatabaseConnectionError: dial tcp 127.0.0.1:5432: connect: connection refused in Gin
This error occurs when your Gin application cannot connect to the PostgreSQL database, typically because the database is not running, the connection string is wrong, or the connection pool is exhausted. Fix it by validating the connection at startup with db.Ping(), configuring pool settings, and implementing a health check endpoint.
Reading the Stack Trace
Here's what each line means:
- main.ListUsers(0x14000226000) /app/handlers/user.go:35 +0x1c4: The ListUsers handler at line 35 triggers a database query that fails because the database connection cannot be established.
- database/sql.(*DB).QueryContext(0x14000118300, {0x1029f0ea0, 0x14000196040}, {0x1028f1e60, 0x15}, {0x0, 0x0, 0x0}): Go's database/sql package attempts to run the query, which requires opening a connection from the pool.
- net.(*Dialer).DialContext(0x14000196040, {0x1029f0ea0, 0x14000196040}, {0x1028f0f20, 0x3}, {0x1028f1e60, 0x15}): The net dialer tries to connect to 127.0.0.1:5432 but the connection is refused because nothing is listening on that port.
Common Causes
1. Database not running or unreachable
The PostgreSQL server is not started or the host/port in the connection string is incorrect.
var db *sql.DB
func main() {
var err error
db, err = sql.Open("postgres", "host=localhost port=5432 dbname=myapp sslmode=disable")
if err != nil {
log.Fatal(err)
}
// sql.Open does not actually connect — first query fails
r := gin.Default()
r.GET("/api/users", ListUsers)
r.Run()
}
2. Connection pool exhausted
All connections in the pool are in use and new queries block until timeout.
db.SetMaxOpenConns(5)
// Under high load, all 5 connections are busy
// New requests wait until ConnMaxLifetime expires
3. No connection retry or health check
The app starts accepting traffic before verifying the database is reachable, leading to 500 errors on the first requests.
func main() {
db, _ = sql.Open("postgres", connStr)
// No db.Ping() — no health check endpoint
r := gin.Default()
r.Run()
}
The Fix
Call db.PingContext at startup to verify the database is reachable before accepting traffic. Configure connection pool settings to prevent exhaustion. Add a health check endpoint that probes the database for use by load balancers and orchestrators.
var db *sql.DB
func main() {
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
r := gin.Default()
r.GET("/api/users", ListUsers)
r.Run()
}
var db *sql.DB
func main() {
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal("failed to open database:", err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
log.Fatal("database unreachable:", err)
}
log.Println("database connected")
r := gin.Default()
r.GET("/health", func(c *gin.Context) {
if err := db.Ping(); err != nil {
c.JSON(503, gin.H{"status": "unhealthy", "db": err.Error()})
return
}
c.JSON(200, gin.H{"status": "healthy"})
})
r.GET("/api/users", ListUsers)
r.Run()
}
Testing the Fix
package main_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestHealthCheck_Healthy(t *testing.T) {
mockDB, mock, _ := sqlmock.New(sqlmock.MonitorPingsOption(true))
defer mockDB.Close()
mock.ExpectPing()
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/health", healthHandler(mockDB))
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "healthy")
}
func TestListUsers_DBError(t *testing.T) {
mockDB, mock, _ := sqlmock.New()
defer mockDB.Close()
mock.ExpectQuery("SELECT").WillReturnError(fmt.Errorf("connection refused"))
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/api/users", listUsersHandler(mockDB))
req := httptest.NewRequest(http.MethodGet, "/api/users", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
}
Run your tests:
go test ./... -v
Pushing Through CI/CD
git checkout -b fix/gin-database-error,git add main.go handlers/user.go,git commit -m "fix: validate database connection at startup and add health check",git push origin fix/gin-database-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
env:
DATABASE_URL: postgres://postgres:test@localhost:5432/testdb?sslmode=disable
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally with a running PostgreSQL instance.
- Open a pull request with the database connection improvements.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the health endpoint in staging.
Frequently Asked Questions
BugStack runs the fix through your test suite with database mocks, validates connection pool configuration, and checks that the health endpoint correctly reports status before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Start with MaxOpenConns=25, MaxIdleConns=5, ConnMaxLifetime=5min. Tune based on your database's max_connections and your application's concurrency.
sql.Open only validates the driver and DSN format. It does not open a network connection until the first query or Ping call. Always call db.Ping() after sql.Open.