CockroachDB¶
Since v0.28.0
Introduction¶
The Testcontainers module for CockroachDB.
Adding this module to your project dependencies¶
Please run the following command to add the CockroachDB module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/cockroachdb
Usage example¶
ctx := context.Background()
cockroachdbContainer, err := cockroachdb.Run(ctx, "cockroachdb/cockroach:latest-v23.1")
defer func() {
if err := testcontainers.TerminateContainer(cockroachdbContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
Module Reference¶
Run function¶
- Since v0.32.0
Info
The RunContainer(ctx, opts...) function is deprecated and will be removed in the next major release of Testcontainers for Go.
The CockroachDB module exposes one entrypoint function to create the CockroachDB container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*CockroachDBContainer, error)
context.Context, the Go context.string, the Docker image to use.testcontainers.ContainerCustomizer, a variadic argument for passing options.
Container Options¶
When starting the CockroachDB container, you can pass options in a variadic way to configure it.
Image¶
Use the second argument in the Run function to set a valid Docker image.
In example: Run(context.Background(), "cockroachdb/cockroach:latest-v23.1").
Database¶
- Since v0.28.0
Set the database that is created & dialled with cockroachdb.WithDatabase.
User and Password¶
- Since v0.28.0
You can configure the container to create a user with a password by setting cockroachdb.WithUser and cockroachdb.WithPassword.
cockroachdb.WithPassword is incompatible with cockroachdb.WithInsecure.
Store size¶
- Since v0.28.0
Control the maximum amount of memory used for storage, by default this is 100% but can be changed by provided a valid option to WithStoreSize. Checkout https://www.cockroachlabs.com/docs/stable/cockroach-start#store for the full range of options available.
TLS authentication¶
- Since v0.35.0
cockroachdb.WithInsecure lets you disable the use of TLS on connections.
cockroachdb.WithInsecure is incompatible with cockroachdb.WithPassword.
Initialization Scripts¶
- Since v0.35.0
cockroachdb.WithInitScripts adds the given scripts to those automatically run when the container starts.
These will be ignored if data exists in the /cockroach/cockroach-data directory within the container.
No Cluster Defaults¶
- Since v0.35.0
cockroachdb.WithNoClusterDefaults disables the default cluster settings script.
Without this option Cockroach containers run data/cluster-defaults.sql on startup
which configures the settings recommended by Cockroach Labs for
local testing clusters
unless data exists in the /cockroach/cockroach-data directory within the container.
The following options are exposed by the testcontainers package.
Basic Options¶
WithExposedPortsSince v0.37.0WithEnvSince v0.29.0WithWaitStrategySince v0.20.0WithAdditionalWaitStrategySince v0.38.0WithWaitStrategyAndDeadlineSince v0.20.0WithAdditionalWaitStrategyAndDeadlineSince v0.38.0WithEntrypointSince v0.37.0WithEntrypointArgsSince v0.37.0WithCmdSince v0.37.0WithCmdArgsSince v0.37.0WithLabelsSince v0.37.0
Lifecycle Options¶
WithLifecycleHooksSince v0.38.0WithAdditionalLifecycleHooksSince v0.38.0WithStartupCommandSince v0.25.0WithAfterReadyCommandSince v0.28.0
Files & Mounts Options¶
WithFilesSince v0.37.0WithMountsSince v0.37.0WithTmpfsSince v0.37.0WithImageMountSince v0.37.0
Build Options¶
WithDockerfileSince v0.37.0
Logging Options¶
WithLogConsumersSince v0.28.0WithLogConsumerConfigSince v0.38.0WithLoggerSince v0.29.0
Image Options¶
WithAlwaysPullSince v0.38.0WithImageSubstitutorsSince v0.26.0WithImagePlatformSince v0.38.0
Networking Options¶
WithNetworkSince v0.27.0WithNetworkByNameSince v0.38.0WithBridgeNetworkSince v0.38.0WithNewNetworkSince v0.27.0
Advanced Options¶
WithHostPortAccessSince v0.31.0WithConfigModifierSince v0.20.0 · Chainable since mainWithHostConfigModifierSince v0.20.0 · Chainable since mainWithEndpointSettingsModifierSince v0.20.0 · Chainable since mainCustomizeRequestSince v0.20.0WithNameSince v0.38.0WithNoStartSince v0.38.0WithProviderSince v0.39.0
Experimental Options¶
WithReuseByNameSince v0.37.0
Container Methods¶
The CockroachDB container exposes the following methods:
ConnectionString¶
- Since v0.28.0
Returns a portable PostgreSQL URL. In secure mode the URL does not contain the
in-memory CA or client certificate; use ConnectionInfo or the optional pgx
adapter below to configure TLS.
MustConnectionString¶
- Since v0.28.0
Same URL semantics as ConnectionString; panics if address lookup fails.
TLSConfig¶
- Since v0.28.0
Returns *tls.Config setup to allow you to dial your client over TLS, if enabled, else this will error with cockroachdb.ErrTLSNotEnabled.
Info
The TLSConfig() function is deprecated. Use the TLSConfig field returned by
ConnectionInfo(ctx) for a cloned TLS configuration.
ConnectionInfo¶
Returns cockroachdb.ConnectionInfo with URL string and TLSConfig *tls.Config.
The TLS config is cloned and is nil in insecure mode. Apply it to your client
when connecting securely; preserve its CA trust, client certificate and
ServerName (127.0.0.1 by default).
Breaking change: pgx adapter moved¶
Combined CockroachDB and Dex SDK extraction
(*cockroachdb.CockroachDBContainer).ConnectionConfig(ctx) has been removed
from github.com/testcontainers/testcontainers-go/modules/cockroachdb.
The pgx API now belongs to the importable child package
github.com/testcontainers/testcontainers-go/modules/cockroachdb/examples.
This change ships together with the Dex admin adapter move.
Import the adapter as cockroachdbexamples and wrap the parent container:
import cockroachdbexamples "github.com/testcontainers/testcontainers-go/modules/cockroachdb/examples"
// Before: cfg, err := c.ConnectionConfig(ctx)
clientContainer := cockroachdbexamples.NewContainer(c)
cfg, err := clientContainer.ConnectionConfig(ctx) // *pgx.ConnConfig
// Pass cfg to pgx.ConnectConfig after checking err.
// Before: addr, err := c.ConnectionString(ctx)
addr, err := clientContainer.ConnectionString(ctx)
// Pass addr to sql.Open("pgx/v5", addr) after checking err.
Move explicit method expressions, interfaces and function references involving
ConnectionConfig(context.Context) (*pgx.ConnConfig, error) to the child
*cockroachdbexamples.Container. Its ConnectionString and
MustConnectionString preserve the old opaque stdlib.RegisterConnConfig
handle semantics. The adapter imports pgx's stdlib driver; callers own closing
pgx connections and *sql.DB, and can release unused registered handles with
stdlib.UnregisterConnConfig.
The parent's ConnectionString and MustConnectionString now return URLs,
not registered handles, despite their unchanged Go signatures. Existing
sql.Open callers must use the adapter to retain the in-memory certificate
configuration. A URL alone does not serialize the CA or client certificate.
Consumers implementing their own client must use ConnectionInfo and apply
its TLS settings, and register their own SQL driver when using database/sql.
The parent no longer registers pgx/v5 as an import side effect.
Provisioning and options remain in the parent. Readiness still waits, in order,
for init_success, HTTP health, and (in secure mode) CA/client certificates,
then executes cockroach sql --url <connection URL> --execute 'SELECT 1'
inside the container using the configured database, user and password. Secure
mode uses the container's CA/client certificate/key and 127.0.0.1; insecure
mode uses sslmode=disable. A nonzero SQL exit retries until the existing
startup timeout or caller context expires. This replaces the external pgx SQL
probe; applications still own connectivity from their process to the mapped
endpoint.
The adapter is optional example support in a separate Go module. To consume a local checkout, add replacements for both modules (substitute your checkout path), then add the adapter:
go mod edit -replace=github.com/testcontainers/testcontainers-go/modules/cockroachdb=/path/to/testcontainers-go/modules/cockroachdb
go mod edit -replace=github.com/testcontainers/testcontainers-go/modules/cockroachdb/examples=/path/to/testcontainers-go/modules/cockroachdb/examples
go get github.com/testcontainers/testcontainers-go/modules/cockroachdb/examples
Run the SDK tests and both runnable client examples from
modules/cockroachdb/examples; run the independent parent suite from
modules/cockroachdb. Parent go test ./... does not traverse the nested
module. The child pins pgx/v5 at v5.9.2.