How to Use testcontainers-go for Docker-Based Integration Tests

Use testcontainers-go to automate spinning up Docker containers for integration tests, handling lifecycle management and port mapping automatically.

Use the testcontainers-go library to spin up Docker containers as test dependencies, interact with them, and tear them down automatically.

package main

import (
	"context"
	"testing"
	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/wait"
)

func TestDatabase(t *testing.T) {
	ctx := context.Background()
	req := testcontainers.ContainerRequest{
		Image:        "postgres:15",
		ExposedPorts: []string{"5432/tcp"},
		Env: map[string]string{
			"POSTGRES_USER":     "test",
			"POSTGRES_PASSWORD": "test",
			"POSTGRES_DB":       "test",
		},
		WaitingFor: wait.ForLog("database system is ready to accept connections"),
	}
	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
		ContainerRequest: req,
		Started:          true,
	})
	if err != nil {
		t.Fatal(err)
	}
	defer container.Terminate(ctx)

	endpoint, err := container.MappedPort(ctx, "5432")
	if err != nil {
		t.Fatal(err)
	}
	// Use endpoint.Port() to connect your Go code to the DB
}