How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Gin · Go

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

2024/03/15 18:30:10 [GIN] 2024/03/15 - 18:30:10 | 500 | 5002.104ms | 127.0.0.1 | GET /api/users goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.ListUsers(0x14000226000) /app/handlers/user.go:35 +0x1c4 github.com/gin-gonic/gin.(*Context).Next(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 +0x74 database/sql.(*DB).QueryContext(0x14000118300, {0x1029f0ea0, 0x14000196040}, {0x1028f1e60, 0x15}, {0x0, 0x0, 0x0}) /usr/local/go/src/database/sql/sql.go:1716 +0x1e4 database/sql.(*DB).Query(0x14000118300, {0x1028f1e60, 0x15}, {0x0, 0x0, 0x0}) /usr/local/go/src/database/sql/sql.go:1700 +0x7c net.(*Dialer).DialContext(0x14000196040, {0x1029f0ea0, 0x14000196040}, {0x1028f0f20, 0x3}, {0x1028f1e60, 0x15}) /usr/local/go/src/net/dial.go:589 +0x5e0

Here's what each line means:

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.

Before (broken)
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()
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally with a running PostgreSQL instance.
  2. Open a pull request with the database connection improvements.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.