Cannot connect to database: failed to connect to `host=localhost user=root database=userdb`: failed to receive message (unexpected EOF

main.go

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/jmechavez/PSO-Sarangani/db"
)

type Config struct {
	Port string
}

type Application struct {
	Config Config
}

// global port varialbe for both main and serve
var port = os.Getenv("PORT")

func (app *Application) Serve() error {
	fmt.Println("API listening on port", port)

	srv := &http.Server{
		Addr: fmt.Sprintf(":%s", port),
	}

	return srv.ListenAndServe()
}

db.go


package db

import (
	"database/sql"
	"fmt"
	"time"

	_ "github.com/jackc/pgconn"
	_ "github.com/jackc/pgx/v4"
	_ "github.com/jackc/pgx/v4/stdlib"
	_ "github.com/lib/pq"
)

type DB struct {
	DB *sql.DB
}

var dbConn = &DB{}

const (
	maxOpenDbConn = 10
	maxIdleDbConn = 5
	maxDbLifeTime = 5 * time.Minute
)

func ConnectPostgres(dsn string) (*DB, error) {
	d, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, err
	}
	d.SetMaxOpenConns(maxOpenDbConn)
	d.SetMaxIdleConns(maxIdleDbConn)
	d.SetConnMaxLifetime(maxDbLifeTime)

	err = testDB(d)
	if err != nil {
		return nil, err
	}
	dbConn.DB = d
	return dbConn, nil
}

func testDB(d *sql.DB) error {
	err := d.Ping()
	if err != nil {
		fmt.Println("Error", err)
		return err
	}
	fmt.Println("*** Pinged database successfully! ***")
	return nil
}

Makefile


DSN="host=localhost port=5432 user=root password=secret dbname=userdb sslmode=disable timezone=UTC connect_timeout=5"
PORT=8080
DB_DOCKER_CONTAINER=psosarangani_db
BINARY_NAME=psosaranganiapi

# ! creating the container with postgres software
postgres:
	docker run --name ${DB_DOCKER_CONTAINER} -p 5432:5432 -e POSTGRES_USER=root -e POSTGRES_PASSWORD=secret -d postgres:12-alpine


# ! creating the coffee db inside the postgres container
createdb:
	docker exec -it ${DB_DOCKER_CONTAINER} createdb --username=root --owner=root userdb 

#	docker exec -it $(DB_DOCKER_CONTAINER) psql --username=root --command "CREATE DATABASE userdb OWNER root;"


# ! stop other docker containers
stop_containers:
	echo "Stopping other docker containers"
	if [ $$(docker ps -q) ]; then \
		echo "Found and stopped docker containers..."; \
		docker stop $$(docker ps -q); \
	else \
		echo "No active containers found..."; \
	fi


# ! start docker container 
start-docker:
	docker start ${DB_DOCKER_CONTAINER}

create_migrations:
	sqlx migrate add -r init

migrate-up:
	sqlx migrate run --database-url "postgres://root:secret@localhost:5432/userdb?sslmode=disable"

migrate-down:
	sqlx migrate revert --database-url "postgres://root:secret@localhost:5432/userdb?sslmode=disable"

build:
	@echo "Building backend api binary"
	go build -o ${BINARY_NAME} cmd/server/*.go
	@echo "Binary built!"

run: build stop_containers start-docker
	@echo "Startin api"
	@env PORT=${PORT} DSN=${DSN} ./${BINARY_NAME} &
	@echo "api started!"

stop:
	@echo "Stopping backend"
	@-pkill -SIGTERM -f "./${BINARY_NAME}"
	@echo "Stopped backend"

start: run

restart: stop start

sorry i am try my best to solve this… please help me. just studying golang and postgre

Hi @John_Michael_Echavez, welcome to the forum.

On a first glance, you might need to expose the container to the host’s network by adding --network host to your docker run command.

thanks man it work… i see now what is the problem.

1 Like