In this article, we are going to explore how to set up a Go application with Docker Compose alongside a PostgreSQL database. This setup is beneficial for many reasons, including ease of deployment and scalability.
Prerequisites
- Basic understanding of Go programming language.
- Docker and Docker Compose installed on your system.
- PostgreSQL database understanding.
Project Structure
First, let’s create a directory for our project to keep everything organized.
mkdir go-docker-postgres
cd go-docker-postgresCreating the Go Application
Create a new file called main.go and add the following Go code:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
connStr := "postgres://user:password@localhost/dbname?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 the database!")
}This Go application connects to a PostgreSQL database, where you will need to replace user, password, and dbname with your PostgreSQL credentials.
Creating Docker Environment
Create a Dockerfile for the Go application:
FROM golang:1.17-alpine
WORKDIR /app
COPY . .
RUN go mod init app && go mod tidy
RUN go build -o main .
CMD ["./main"]Setting Up Docker Compose
Create a docker-compose.yml file:
version: '3.8'
services:
db:
image: postgres:13
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: dbname
ports:
- "5432:5432"
app:
build: .
depends_on:
- db
ports:
- "8080:8080"The above configuration includes two services: a PostgreSQL database and our Go application. Make sure that the environment variables in the database service match those in your Go connection string.
Running the Application with Docker Compose
In the terminal within your project directory, execute:
docker-compose upThis command will build the Go application, start the PostgreSQL service, and wire them together. You should see logs indicating that your application has successfully connected to the database.
Conclusion
This setup provides a starting point for developing Go applications with PostgreSQL in a Docker environment. You can further enhance this by adjusting configurations, adding more services, or integrating with other tools.