I'm new to podman
and trying to use podman-compose
to build multiple docker images from the docker-compose.yml
file. I'm unable to get my authentication-service
golang app docker image connected to the Postgres docker image. I tried checking this question but wasn't of much help. I'm unable to understand why is there no host
failed to connect to `host=postgres user=postgres database=users`: hostname resolving error (lookup postgres on 10.89.0.1:53: no such host)
Podman commands used:
podman-compose up -d
podman ps
podman logs container-id
Podman logs:
docker-compose.yml
:
version: '3'
services:
broker-service:
build:
context: ./../broker-service
dockerfile: ./../broker-service/broker-service.dockerfile
restart: always
ports:
- "8080:80"
deploy:
mode: replicated
replicas: 1
authentication-service:
build:
context: ./../authentication-service
dockerfile: ./../authentication-service/authentication-service.dockerfile
restart: always
ports:
- "8081:80"
deploy:
mode: replicated
replicas: 1
environment:
DSN: "host=postgres port=5432 user=postgres password=password dbname=users sslmode=disable timezone=UTC connect_timeout=5"
postgres:
image: 'postgres:14.2'
ports:
- "5432:5432"
restart: always
deploy:
mode: replicated
replicas: 1
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: users
volumes:
- ./db-data/postgres/:/var/lib/postgresql/data/
main.go
:
package main
import (
"authentication-service/data"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v4"
_ "github.com/jackc/pgx/v4/stdlib"
)
const webPort = "80"
var counts int64
type Config struct {
DB *sql.DB
Models data.Models
}
func main() {
log.Println("Starting authentication server")
// connect to DB
conn := connectToDB()
if conn == nil {
log.Panic("Can't connect to Postgres!")
}
// setup config
app := Config{
DB: conn,
Models: data.New(conn),
}
// define http server
srv := &http.Server{
Addr: fmt.Sprintf(":%s", webPort),
Handler: app.routes(),
}
// start the server
err := srv.ListenAndServe()
if err != nil {
log.Panic(err)
}
}
// function to open the database
func openDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Printf("open db pgx error: %s", err)
return nil, err
}
err = db.Ping()
if err != nil {
log.Printf("db ping error: %s", err)
return nil, err
}
return db, nil
}
// function to connect to the database
func connectToDB() *sql.DB {
dsn := os.Getenv("DSN")
for {
connection, err := openDB(dsn)
if err != nil {
log.Println("Postgres not yet ready...")
counts++
} else {
log.Println("Connected to Postgres!")
return connection
}
if counts > 10 {
log.Println(err)
return nil
}
log.Println("Backing off for 2 seconds...")
time.Sleep(2 * time.Second)
continue
}
}