Skip to content

Postgres

Since testcontainers-go v0.20.0

Introduction

The Testcontainers module for Postgres.

Adding this module to your project dependencies

Please run the following command to add the Postgres module to your Go dependencies:

go get github.com/testcontainers/testcontainers-go/modules/postgres

Usage example

ctx := context.Background()

dbName := "users"
dbUser := "user"
dbPassword := "password"

postgresContainer, err := postgres.RunContainer(ctx,
    testcontainers.WithImage("docker.io/postgres:16-alpine"),
    postgres.WithInitScripts(filepath.Join("testdata", "init-user-db.sh")),
    postgres.WithConfigFile(filepath.Join("testdata", "my-postgres.conf")),
    postgres.WithDatabase(dbName),
    postgres.WithUsername(dbUser),
    postgres.WithPassword(dbPassword),
    testcontainers.WithWaitStrategy(
        wait.ForLog("database system is ready to accept connections").
            WithOccurrence(2).
            WithStartupTimeout(5*time.Second)),
)
if err != nil {
    log.Fatalf("failed to start container: %s", err)
}

// Clean up the container
defer func() {
    if err := postgresContainer.Terminate(ctx); err != nil {
        log.Fatalf("failed to terminate container: %s", err)
    }
}()

Module reference

The Postgres module exposes one entrypoint function to create the Postgres container, and this function receives two parameters:

func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*PostgresContainer, error)
  • context.Context, the Go context.
  • testcontainers.ContainerCustomizer, a variadic argument for passing options.

Container Options

When starting the Postgres container, you can pass options in a variadic way to configure it.

Tip

You can find all the available configuration and environment variables for the Postgres Docker image on Docker Hub.

Image

If you need to set a different Postgres Docker image, you can use testcontainers.WithImage with a valid Docker image for Postgres. E.g. testcontainers.WithImage("docker.io/postgres:16-alpine").

Image Substitutions

In more locked down / secured environments, it can be problematic to pull images from Docker Hub and run them without additional precautions.

An image name substitutor converts a Docker image name, as may be specified in code, to an alternative name. This is intended to provide a way to override image names, for example to enforce pulling of images from a private registry.

Testcontainers for Go exposes an interface to perform this operations: ImageSubstitutor, and a No-operation implementation to be used as reference for custom implementations:

// ImageSubstitutor represents a way to substitute container image names
type ImageSubstitutor interface {
    // Description returns the name of the type and a short description of how it modifies the image.
    // Useful to be printed in logs
    Description() string
    Substitute(image string) (string, error)
}
type NoopImageSubstitutor struct{}

// Description returns a description of what is expected from this Substitutor,
// which is used in logs.
func (s NoopImageSubstitutor) Description() string {
    return "NoopImageSubstitutor (noop)"
}

// Substitute returns the original image, without any change
func (s NoopImageSubstitutor) Substitute(image string) (string, error) {
    return image, nil
}

Using the WithImageSubstitutors options, you could define your own substitutions to the container images. E.g. adding a prefix to the images so that they can be pulled from a Docker registry other than Docker Hub. This is the usual mechanism for using Docker image proxies, caches, etc.

WithEnv

If you need to either pass additional environment variables to a container or override them, you can use testcontainers.WithEnv for example:

postgres, err = postgresModule.RunContainer(ctx, testcontainers.WithEnv(map[string]string{"POSTGRES_INITDB_ARGS": "--no-sync"}))

WithHostPortAccess

If you need to access a port that is already running in the host, you can use testcontainers.WithHostPortAccess for example:

postgres, err = postgresModule.RunContainer(ctx, testcontainers.WithHostPortAccess(8080))

To understand more about this feature, please read the Exposing host ports to the container documentation.

WithLogConsumers

If you need to consume the logs of the container, you can use testcontainers.WithLogConsumers with a valid log consumer. An example of a log consumer is the following:

type TestLogConsumer struct {
    Msgs []string
}

func (g *TestLogConsumer) Accept(l Log) {
    g.Msgs = append(g.Msgs, string(l.Content))
}

WithLogger

If you need to either pass logger to a container, you can use testcontainers.WithLogger.

Info

Consider calling this before other "With" functions as these may generate logs.

In this example we also use TestLogger which writes to the passed in testing.TB using Logf. The result is that we capture all logging from the container into the test context meaning its hidden behind go test -v and is associated with the relevant test, providing the user with useful context instead of appearing out of band.

func TestHandler(t *testing.T) {
    logger := TestLogger(t)
    _, err := postgresModule.RunContainer(ctx, testcontainers.WithLogger(logger))
    require.NoError(t, err)
    // Do something with container.
}

Please read the Following Container Logs documentation for more information about creating log consumers.

Wait Strategies

If you need to set a different wait strategy for the container, you can use testcontainers.WithWaitStrategy with a valid wait strategy.

Info

The default deadline for the wait strategy is 60 seconds.

At the same time, it's possible to set a wait strategy and a custom deadline with testcontainers.WithWaitStrategyAndDeadline.

Startup Commands

Testcontainers exposes the WithStartupCommand(e ...Executable) option to run arbitrary commands in the container right after it's started.

Info

To better understand how this feature works, please read the Create containers: Lifecycle Hooks documentation.

It also exports an Executable interface, defining the following methods:

  • AsCommand(), which returns a slice of strings to represent the command and positional arguments to be executed in the container;
  • Options(), which returns the slice of functional options with the Docker's ExecConfigs used to create the command in the container (the working directory, environment variables, user executing the command, etc) and the possible output format (Multiplexed).

You could use this feature to run a custom script, or to run a command that is not supported by the module right after the container is started.

Ready Commands

Testcontainers exposes the WithAfterReadyCommand(e ...Executable) option to run arbitrary commands in the container right after it's ready, which happens when the defined wait strategies have finished with success.

Info

To better understand how this feature works, please read the Create containers: Lifecycle Hooks documentation.

It leverages the Executable interface to represent the command and positional arguments to be executed in the container.

You could use this feature to run a custom script, or to run a command that is not supported by the module right after the container is ready.

WithNetwork

By default, the container is started in the default Docker network. If you want to use an already existing Docker network you created in your code, you can use the network.WithNetwork(aliases []string, nw *testcontainers.DockerNetwork) option, which receives an alias as parameter and your network, attaching the container to it, and setting the network alias for that network.

In the case you need to retrieve the network name, you can simply read it from the struct's Name field. E.g. nw.Name.

Warning

This option is not checking whether the network exists or not. If you use a network that doesn't exist, the container will start in the default Docker network, as in the default behavior.

WithNewNetwork

If you want to attach your containers to a throw-away network, you can use the network.WithNewNetwork(ctx context.Context, aliases []string, opts ...network.NetworkCustomizer) option, which receives an alias as parameter, creating the new network with a random name, attaching the container to it, and setting the network alias for that network.

In the case you need to retrieve the network name, you can use the Networks(ctx) method of the Container interface, right after it's running, which returns a slice of strings with the names of the networks where the container is attached.

Docker type modifiers

If you need an advanced configuration for the container, you can leverage the following Docker type modifiers:

  • testcontainers.WithConfigModifier
  • testcontainers.WithHostConfigModifier
  • testcontainers.WithEndpointSettingsModifier

Please read the Create containers: Advanced Settings documentation for more information.

Customising the ContainerRequest

This option will merge the customized request into the module's own ContainerRequest.

container, err := RunContainer(ctx,
    /* Other module options */
    testcontainers.CustomizeRequest(testcontainers.GenericContainerRequest{
        ContainerRequest: testcontainers.ContainerRequest{
            Cmd: []string{"-c", "log_statement=all"},
        },
    }),
)

The above example is updating the predefined command of the image, appending them to the module's command.

Info

This can't be used to replace the command, only to append options.

Initial Database

If you need to set a different database, and its credentials, you can use the WithDatabase(db string), WithUsername(user string) and WithPassword(pwd string) options.

Init Scripts

If you would like to do additional initialization in the Postgres container, add one or more *.sql, *.sql.gz, or *.sh scripts to the container request with the WithInitScripts function. Those files will be copied after the container is created but before it's started under /docker-entrypoint-initdb.d. According to Postgres Docker image, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.

An example of a *.sh script that creates a user and database is shown below:

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
    CREATE TABLE IF NOT EXISTS testdb (id int, name varchar(255));
    INSERT INTO testdb (id, name) VALUES (1, 'test')
EOSQL

Database configuration

In the case you have a custom config file for Postgres, it's possible to copy that file into the container before it's started, using the WithConfigFile(cfgPath string) function.

Tip

For information on what is available to configure, see the PostgreSQL docs for the specific version of PostgreSQL that you are running.

Container Methods

ConnectionString

This method returns the connection string to connect to the Postgres container, using the default 5432 port. It's possible to pass extra parameters to the connection string, e.g. sslmode=disable or application_name=myapp, in a variadic way.

// explicitly set sslmode=disable because the container is not configured to use TLS
connStr, err := container.ConnectionString(ctx, "sslmode=disable", "application_name=test")

Postgres variants

It's possible to use the Postgres container with PGVector, Timescale or Postgis, to name a few. You simply need to update the image name and the wait strategy.

image: "docker.io/pgvector/pgvector:pg16",
wait:  wait.ForLog("database system is ready to accept connections").WithOccurrence(2).WithStartupTimeout(30 * time.Second),
image: "docker.io/timescale/timescaledb:2.1.0-pg11",
wait:  wait.ForLog("database system is ready to accept connections").WithOccurrence(2).WithStartupTimeout(5 * time.Second),
image: "docker.io/postgis/postgis:12-3.0",
wait:  wait.ForLog("database system is ready to accept connections").WithOccurrence(2).WithStartupTimeout(30 * time.Second),

Examples

Using Snapshots

This example shows the usage of the postgres module's Snapshot feature to give each test a clean database without having to recreate the database container on every test or run heavy scripts to clean your database. This makes the individual tests very modular, since they always run on a brand-new database.

Tip

You should never pass the "postgres" system database as the container database name if you want to use snapshots. The Snapshot logic requires dropping the connected database and using the system database to run commands, which will not work if the database for the container is set to "postgres".

ctx := context.Background()

// 1. Start the postgres container and run any migrations on it
container, err := postgres.RunContainer(
    ctx,
    testcontainers.WithImage("docker.io/postgres:16-alpine"),
    postgres.WithDatabase(dbname),
    postgres.WithUsername(user),
    postgres.WithPassword(password),
    testcontainers.WithWaitStrategy(
        wait.ForLog("database system is ready to accept connections").
            WithOccurrence(2).
            WithStartupTimeout(5*time.Second)),
)
if err != nil {
    t.Fatal(err)
}

// Run any migrations on the database
_, _, err = container.Exec(ctx, []string{"psql", "-U", user, "-d", dbname, "-c", "CREATE TABLE users (id SERIAL, name TEXT NOT NULL, age INT NOT NULL)"})
if err != nil {
    t.Fatal(err)
}

// 2. Create a snapshot of the database to restore later
err = container.Snapshot(ctx, postgres.WithSnapshotName("test-snapshot"))
if err != nil {
    t.Fatal(err)
}

// Clean up the container after the test is complete
t.Cleanup(func() {
    if err := container.Terminate(ctx); err != nil {
        t.Fatalf("failed to terminate container: %s", err)
    }
})

dbURL, err := container.ConnectionString(ctx)
if err != nil {
    t.Fatal(err)
}

t.Run("Test inserting a user", func(t *testing.T) {
    t.Cleanup(func() {
        // 3. In each test, reset the DB to its snapshot state.
        err = container.Restore(ctx)
        if err != nil {
            t.Fatal(err)
        }
    })

    conn, err := pgx.Connect(context.Background(), dbURL)
    if err != nil {
        t.Fatal(err)
    }
    defer conn.Close(context.Background())

    _, err = conn.Exec(ctx, "INSERT INTO users(name, age) VALUES ($1, $2)", "test", 42)
    if err != nil {
        t.Fatal(err)
    }

    var name string
    var age int64
    err = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age)
    if err != nil {
        t.Fatal(err)
    }

    if name != "test" {
        t.Fatalf("Expected %s to equal `test`", name)
    }
    if age != 42 {
        t.Fatalf("Expected %d to equal `42`", age)
    }
})

// 4. Run as many tests as you need, they will each get a clean database
t.Run("Test querying empty DB", func(t *testing.T) {
    t.Cleanup(func() {
        err = container.Restore(ctx)
        if err != nil {
            t.Fatal(err)
        }
    })

    conn, err := pgx.Connect(context.Background(), dbURL)
    if err != nil {
        t.Fatal(err)
    }
    defer conn.Close(context.Background())

    var name string
    var age int64
    err = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age)
    if !errors.Is(err, pgx.ErrNoRows) {
        t.Fatalf("Expected error to be a NoRows error, since the DB should be empty on every test. Got %s instead", err)
    }
})