How to use PostgreSQL in Docker with Docker Compose and Go

In this article, we will explore how to configure PostgreSQL using Docker and Docker Compose and how to integrate it into a Go application. This approach is useful to simplify local development and application deployment.

Configuring Docker Compose

Let's create a docker-compose.yml file to configure PostgreSQL:

version: '3.8'
services:
  db:
    image: postgres:15
    container_name: postgres_container
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: mydb
    ports:
      - "5432:5432"
    volumes:
      - db_data:/var/lib/postgresql/data
volumes:
  db_data:

Starting PostgreSQL with Docker Compose

Run the following command to start the container:

docker compose up -d

Check that the container is running:

docker ps

Connecting to PostgreSQL in Go

Add the pq library to your Go project to connect to PostgreSQL:

go get github.com/lib/pq

Create a Go file, for example, main.go, with the following code:

package main

import (
  "database/sql"
  "fmt"
  _ "github.com/lib/pq"
)

func main() {
  connStr := "postgres://user:password@localhost:5432/mydb?sslmode=disable"
  db, err := sql.Open("postgres", connStr)
  if err != nil {
    panic(err)
  }
  defer db.Close()

  err = db.Ping()
  if err != nil {
    panic(err)
  }

  fmt.Println("Successfully connected to PostgreSQL!")
}

Testing the Application

Run the Go application to test the database connection:

go run main.go

If everything is configured correctly, you should see the message:

Successfully connected to PostgreSQL!

Conclusion

In this article, we configured PostgreSQL using Docker and Docker Compose, and we created a Go application to connect to the database. This workflow greatly simplifies database management in local development.

Back to top