### Full Example: Using Qdrant with Testcontainers Go Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/qdrant.md This comprehensive Go example demonstrates the full lifecycle of using the Qdrant Testcontainers module. It includes starting a Qdrant container, configuring it, retrieving its endpoints, and performing basic operations with the Qdrant client. This example is useful for understanding how to integrate Qdrant into Go applications managed by Testcontainers. ```go func fullExample(ctx context.Context) error { // Start Qdrant container qdrantContainer, err := qdrant.Run(ctx, "qdrant/qdrant:latest") if err != nil { return fmt.Errorf("failed to start Qdrant container: %w", err) } // Get container endpoints restEndpoint, err := qdrantContainer.RestEndpoint(ctx) if err != nil { return fmt.Errorf("failed to get REST endpoint: %w", err) } grpcEndpoint, err := qdrantContainer.GrpcEndpoint(ctx) if err != nil { return fmt.Errorf("failed to get gRPC endpoint: %w", err) } fmt.Printf("Qdrant REST endpoint: %s\n", restEndpoint) fmt.Printf("Qdrant gRPC endpoint: %s\n", grpcEndpoint) // Example: Initialize Qdrant client (using qdrant-go client library) // client, err := qdrant.NewClient(restEndpoint) // Assuming qdrant.NewClient exists // if err != nil { // return fmt.Errorf("failed to create Qdrant client: %w", err) // } // Perform Qdrant operations here... // Clean up the container (optional, Testcontainers usually handles this) // defer func() { // if err := qdrantContainer.Terminate(ctx); err != nil { // log.Printf("failed to terminate Qdrant container: %v", err) // } // }() return nil } ``` -------------------------------- ### Run Cassandra Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/cassandra.md Example of how to create and run a Cassandra container using the testcontainers-go module. This function initializes and starts a Cassandra instance. ```go func runCassandraContainer(ctx context.Context) (*testcontainers.Resource, error) { return cassandra.Run(ctx, "cassandra:latest") } ``` -------------------------------- ### NATS Cluster Setup Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/nats.md Example demonstrating how to configure a NATS cluster using the module. ```golang nats.Run(ctx, "nats:2.9", nats.WithArgument("cluster_name", "c1"), nats.WithArgument("cluster_listen", "0.0.0.0:6222")) ``` -------------------------------- ### Connect and Create Database Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Example demonstrating how to connect to a CosmosDB container and create a database. ```go func ExampleRun_connect(t *testing.T) { ctx := context.Background() cosmosdbContainer, err := cosmosdb.Run(ctx, "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-preview") if err != nil { t.Fatal(err) } defer func() { if err := cosmosdbContainer.Terminate(ctx); err != nil { t.Fatalf("failed to terminate container: %s", err) } }() connectionString, err := cosmosdbContainer.ConnectionString(ctx) if err != nil { t.Fatal(err) } client, err := cosmosdb.NewClient(connectionString) if err != nil { t.Fatal(err) } _, err = client.CreateDatabase(ctx, "my-database") if err != nil { t.Fatal(err) } } ``` -------------------------------- ### Run SurrealDB Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/surrealdb.md Example Go code demonstrating how to create and run a SurrealDB container using the Testcontainers Go module. This snippet shows the basic setup for initializing a SurrealDB instance for testing. ```go package main import ( "context" "fmt" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/surrealdb" ) func main() { ctx := context.Background() // RunSurrealDBContainer creates a SurrealDB container with default options. scontainer, err := surrealdb.Run(ctx, "surrealdb/surrealdb:v1.1.1") if err != nil { panic(err) } // Clean up the container when done. defer func() { if err := container.Terminate(ctx); err != nil { panic(fmt.Sprintf("failed to terminate container: %s", err)) } }() // You can now use the container, for example, get its URL. wsURL, err := container.WsURL(ctx) if err != nil { panic(err) } fmt.Printf("SurrealDB WebSocket URL: %s\n", wsURL) } ``` -------------------------------- ### ServiceBus Configuration for Examples Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Configuration for running ServiceBus examples, setting up the necessary environment and image details. ```go cfg := servicebus.Configuration{ Image: "mcr.microsoft.com/azure-messaging/servicebus-emulator:0.1.0", } ``` -------------------------------- ### Run TiDB Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/tidb.md Example Go code demonstrating how to create and run a TiDB container using the Testcontainers Go module. It shows the basic setup for initializing a TiDB instance for testing. ```go package main import ( "context" "fmt" "testing" "github.com/go-sql-driver/mysql" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/tidb" ) func runTiDBContainer(ctx context.Context) (*tidb.Container, error) { // By default, it uses the "pingcap/tidb:v8.4.0" image. container, err := tidb.Run(ctx, "") if err != nil { return nil, fmt.Errorf("failed to start container: %w", err) } return container, nil } func TestTiDBContainer(t *testing.T) { ctx := context.Background() container, err := runTiDBContainer(ctx) if err != nil { t log.Fatal(err) } defer func() { err := container.Terminate(ctx) if err != nil { log.Fatalf("failed to terminate container: %s", err) } }() connectionString, err := container.ConnectionString(ctx) if err != nil { log.Fatal(err) } _, err = mysql.ParseDSN(connectionString) if err != nil { log.Fatal(err) } // You can now use the connection string to connect to the TiDB container // For example, using the go-sql-driver/mysql: // db, err := sql.Open("mysql", connectionString) // if err != nil { // log.Fatal(err) // } // defer db.Close() // Ping the database to ensure the connection is successful // err = db.Ping() // if err != nil { // log.Fatal(err) // } } ``` -------------------------------- ### Cassandra Init Script Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/cassandra.md An example of an initialization script (`.sh`) used to set up keyspaces and tables within a Cassandra container upon startup. ```bash #!/bin/bash KEYSPACE_NAME=my_keyspace TABLE_NAME=my_table cqlsh -e "CREATE KEYSPACE IF NOT EXISTS ${KEYSPACE_NAME} WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '1' };" cqlsh -e "USE ${KEYSPACE_NAME}; CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (id uuid PRIMARY KEY, name text);" ``` -------------------------------- ### Example of All Wait Strategy Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/features/wait/all.md Demonstrates how to configure and use the All wait strategy with a deadline and a default startup timeout. ```go package main import ( "context" "fmt" "testing" "time" ``` ```go "github.com/testcontainers/testcontainers-go" ``` ```go "github.com/testcontainers/testcontainers-go/wait" ) func ExampleForAll(t *testing.T) { ctx := context.Background() // Define a custom wait strategy that waits for a specific port waitStrategy1 := wait.ForHTTP("/healthz"). WithPort("8080/tcp"). WithStartupTimeout(10 * time.Second) // Define another wait strategy that waits for a log message waitStrategy2 := wait.ForLog("Application started"). WithStartupTimeout(5 * time.Second) // Create a new container request with the All wait strategy req := testcontainers.ContainerRequest{ Image: "my-custom-app:latest", ExposedPorts: []string{"8080/tcp"}, WaitingFor: wait.ForAll( waitStrategy1, waitStrategy2, ). WithDeadline(30 * time.Second), // Set a deadline for all strategies to complete } // Start the container container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: req, Started: true, }) if err != nil { t.Fatalf("failed to start container: %s", err) } // Get the container IP address ip, err := container.Host(ctx) if err != nil { t.Fatalf("failed to get container host: %s", err) } // Get the mapped port mappedPort, err := container.MappedPort(ctx, "8080") if err != nil { t.Fatalf("failed to get mapped port: %s", err) } fmt.Printf("Container started at %s:%s\n", ip, mappedPort.Port()) // Clean up the container defer func() { if err := container.Terminate(ctx); err != nil { t.Fatalf("failed to terminate container: %s", err) } }() // Output: Container started at : } ``` -------------------------------- ### Run EventHubs with Configuration Object Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Shows how to start the EventHubs emulator using a programmatically built configuration object. This method is type-safe and validates configuration against emulator limits before starting. ```go eventhubsContainer, err := Run(ctx, "mcr.microsoft.com/azure-messaging/eventhubs-emulator:latest", WithConfigObject(cfg)) if err != nil { t.Fatal(err) } ``` -------------------------------- ### Start Azurite Container for EventHubs Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Shows how to start an Azurite container, specifying its Docker image and network. This container will serve as the backend for the EventHubs emulator. ```go azuriteContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ Image: "mcr.microsoft.com/azure-storage/azurite:latest", Network: network, ExposedPorts: []string{"10000/tcp", "10001/tcp", "10002/tcp"}, Cmd: []string{ "azurite-blob", "--blob", "--queue", "--table", }, }) if err != nil { t.Fatal(err) } ``` -------------------------------- ### Connect to MCP Gateway using MCP Client Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/dockermcpgateway.md An example demonstrating how to connect to the MCP Gateway using an MCP client. This snippet combines running the gateway, getting its endpoint, and establishing a connection. ```go import ( "context" "fmt" "log" "github.com/testcontainers/testcontainers-go/modules/dockermcpgateway" // Import the MCP client SDK if available // "github.com/modelcontextprotocol/go-sdk/mcpclient" ) func connectMCPClient(ctx context.Context) { // Run the MCP Gateway container ctr, err := dockermcpgateway.Run(ctx, "docker/mcp-gateway:latest") if err != nil { log.Fatalf("failed to run MCP Gateway container: %s", err) } // Get the MCP Gateway's endpoint endpoint := ctr.GatewayEndpoint() fmt.Printf("MCP Gateway endpoint: %s\n", endpoint) // Connect with an MCP client (example using a placeholder) // Replace with actual MCP client initialization // client, err := mcpclient.NewClient(endpoint) // if err != nil { // log.Fatalf("failed to create MCP client: %s", err) // } // fmt.Println("Successfully connected to MCP Gateway.") // List tools available in the container top := ctr.Tools() fmt.Printf("Available tools: %+v\n", top) // Clean up the container (usually done automatically when the context is cancelled) // defer func() { // if err := ctr.Terminate(ctx); err != nil { // log.Fatalf("failed to terminate container: %s", err) // } // }() } ``` -------------------------------- ### Run Commands on Container Startup with testcontainers.WithStartupCommand Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/features/common_functional_options.md The `WithStartupCommand` option allows you to execute arbitrary commands within a container immediately after it has started. This is achieved by implementing the `Executable` interface, which defines how to represent the command and its associated options. This feature is useful for running setup scripts or commands not inherently supported by the module. ```go import "github.com/testcontainers/testcontainers-go" // Define a custom command that implements the Executable interface type MyCustomCommand struct { // ... fields for command and options } func (m MyCustomCommand) AsCommand() []string { // Return the command and its arguments return []string{"echo", "Hello from startup!"} } func (m MyCustomCommand) Options() []testcontainers.ExecOption { // Return Docker ExecConfigs options return []testcontainers.ExecOption{} } // Example usage (assuming mymodule and ctx are defined elsewhere) myCommand := MyCustomCommand{} cnt, err := mymodule.Run(ctx, "docker.io/myservice:1.2.3", testcontainers.WithStartupCommand(myCommand)) if err != nil { // Handle error } ``` -------------------------------- ### Create Nginx Container with Testcontainers Go Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/examples/nginx.md This Go code snippet shows how to create a basic Nginx container using the Testcontainers library. It initializes Testcontainers and starts an Nginx container, making it available for testing. ```go package main import ( "context" "fmt" "testing" "github.com/docker/docker/client" "github.com/testcontainers/testcontainers-go" ``` ```go "github.com/testcontainers/testcontainers-go/modules/nginx" ) func main() { ctx := context.Background() // Start Nginx container nginxContainer, err := nginx.Run(ctx, "latest") if err != nil { panic(err) } defer func() { if err := nginxContainer.Terminate(ctx); err != nil { panic(fmt.Sprintf("failed to terminate container: %s", err)) } }() // Container is now running, you can interact with it fmt.Println("Nginx container started successfully!") // Example: Get the mapped port mappedPort, err := nginxContainer.MappedPort(ctx, nginx.Port) if err != nil { panic(fmt.Sprintf("failed to get mapped port: %s", err)) } fmt.Printf("Nginx is available on port %s\n", mappedPort.Port()) } ``` -------------------------------- ### Create Toxiproxy Client Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/toxiproxy.md Example of creating a Toxiproxy client using the URI obtained from the Toxiproxy container. This client can then be used to interact with Toxiproxy. ```go func createToxiproxyClient(ctx context.Context, toxiproxyContainer *toxiproxy.Container) (*client.ToxiproxyClient, error) { toxiproxyClient, err := client.NewClient(toxiproxyContainer.URI()) if err != nil { return nil, err } return toxiproxyClient, nil } ``` -------------------------------- ### Run Azurite Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Example of how to create and run an Azurite container. This snippet demonstrates the basic usage of the `azurite.Run` function. ```go func runAzuriteContainer(ctx context.Context) (*azurite.Container, error) { return azurite.Run(ctx, "mcr.microsoft.com/azure-storage/azurite:3.28.0") } ``` -------------------------------- ### Run MS SQL Server Container Example (Go) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mssql.md Example Go code demonstrating how to create and run an MS SQL Server container using the Testcontainers module. This includes setting necessary options like EULA acceptance. ```go import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/mssql" ) func runMSSQLServerContainer(ctx context.Context) (*mssql.MSSQLServerContainer, error) { return mssql.Run(ctx, mssql.WithAcceptEULA()) } func TestMSSQLServerContainer(t *testing.T) { ctx := context.Background() container, err := runMSSQLServerContainer(ctx) if err != nil { t.Fatal(err) } defer func() { err := container.Terminate(ctx) if err != nil { t.Fatalf("failed to terminate container: %s", err) } }() connectionString, err := container.ConnectionString(ctx) if err != nil { t.Fatal(err) } assert.NotEmpty(t, connectionString) } ``` -------------------------------- ### Run RabbitMQ Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/rabbitmq.md This Go code snippet demonstrates how to create and run a RabbitMQ container using the Testcontainers module. It initializes a context, specifies the Docker image, and optionally accepts customizer functions for further configuration. The function returns a RabbitMQContainer object and an error if the container fails to start. ```go func runRabbitMQContainer(ctx context.Context) (*rabbitmq.RabbitMQContainer, error) { return rabbitmq.Run(ctx, "rabbitmq:latest") } ``` -------------------------------- ### Toxiproxy Configuration File Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/toxiproxy.md Example JSON structure for a Toxiproxy configuration file. This file defines proxies and their settings. ```json { "proxies": { "my-redis": { "name": "my-redis", "upstreams": ["localhost:6379"], "listen": "localhost:8666" } } } ``` -------------------------------- ### Initialize ClickHouse Container with Scripts Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/clickhouse.md Demonstrates how to provide initialization scripts (SQL or shell scripts) to the ClickHouse container. These scripts are executed after the container starts but before the service is fully available, allowing for schema setup or data seeding. ```go func withInitScripts(ctx context.Context) (*ClickHouseContainer, error) { container, err := clickhouse.Run(ctx, "clickhouse/clickhouse-server:latest", clickhouse.WithInitScripts( "file://../../modules/clickhouse/testdata/init-db.sh", )) if err != nil { return nil, err } return container, nil } ``` ```bash #!/bin/bash echo "CREATE DATABASE IF NOT EXISTS my_db;" ``` -------------------------------- ### Run Memcached Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/memcached.md Go code example demonstrating how to create and run a Memcached container using the testcontainers-go module. This includes setting up the context and potentially configuring the container. ```go package memcached_test import ( "context" "testing" "github.com/docker/go-connections/nat" "github.com/stretchr/testify/assert" "github.com/testcontainers/testcontainers-go/modules/memcached" ) func runMemcachedContainer(t *testing.T) { ctx := context.Background() memcachedContainer, err := memcached.Run(ctx, "memcached:1.6-alpine") if err != nil { t.Fatal(err) } defer func(memcachedContainer *memcached.Container) { err := memcachedContainer.Terminate(context.Background()) if err != nil { t.Fatalf("error terminating memcached container: %s", err) } }(memcachedContainer) endpoint, err := memcachedContainer.HostPort(ctx) if err != nil { t.Fatal(err) } expectedEndpoint := "localhost:11211" // Check if the endpoint is in the expected format and contains the default port addr, port, err := nat.SplitHostPort(endpoint) if err != nil { t.Fatal(err) } assert.Equal(t, "localhost", addr) assert.Equal(t, "11211", port) assert.Equal(t, expectedEndpoint, endpoint) } ``` -------------------------------- ### Run Weaviate Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/weaviate.md Example Go code demonstrating how to create and run a Weaviate container using the Testcontainers module. This typically involves setting up the context and potentially specifying the Docker image. ```go func runWeaviateContainer(ctx context.Context) (*weaviate.WeaviateContainer, error) { container, err := weaviate.Run(ctx, "semitechnologies/weaviate:latest") if err != nil { return nil, err } return container, nil } ``` -------------------------------- ### MS SQL Server Image Specification Example (Go) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mssql.md Example of how to specify a Docker image for the MS SQL Server container when using the `Run` function. ```go Run(context.Background(), "mcr.microsoft.com/mssql/server:2022-RTM-GDR1-ubuntu-20.04") ``` -------------------------------- ### Run MongoDB Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mongodb.md Example of how to run a MongoDB container using the testcontainers-go module. This demonstrates basic container instantiation. ```go package main import ( "context" "fmt" "log" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/mongodb" ) func main() { ctx := context.Background() mongoContainer, err := mongodb.Run(ctx, "mongo:latest") if err != nil { log.Fatalf("failed to start mongo container: %s", err) } defer func() { if err := mongoContainer.Terminate(ctx); err != nil { log.Fatalf("failed to terminate mongo container: %s", err) } }() connectionString, err := mongoContainer.ConnectionString(ctx) if err != nil { log.Fatalf("failed to get connection string: %s", err) } fmt.Printf("Successfully started MongoDB container with connection string: %s\n", connectionString) } ``` -------------------------------- ### Run Toxiproxy Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/toxiproxy.md Initializes and starts a new Toxiproxy container instance. ```APIDOC ## FUNCTION Run ### Description Creates and starts a Toxiproxy container instance with specified configuration options. ### Method Go Function ### Parameters - **ctx** (context.Context) - Required - The Go context for the operation. - **img** (string) - Required - The Docker image to use (e.g., "shopify/toxiproxy:2.12.0"). - **opts** (...testcontainers.ContainerCustomizer) - Optional - Variadic options to configure the container. ### Request Example ```go container, err := toxiproxy.Run(ctx, "shopify/toxiproxy:2.12.0") ``` ### Response - **Container** (*Container) - The running Toxiproxy container instance. - **error** (error) - Returns an error if the container fails to start. ``` -------------------------------- ### Run ClickHouse Container Example Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/clickhouse.md Example test demonstrating how to run a ClickHouse container using the testcontainers-go module. This typically involves setting up the container and potentially performing basic assertions. ```go func runClickHouseContainer(ctx context.Context) (*ClickHouseContainer, error) { container, err := clickhouse.Run(ctx, "clickhouse/clickhouse-server:latest") if err != nil { return nil, err } return container, nil } ``` -------------------------------- ### Get TLS Connection Configuration Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/cassandra.md Example showing how to retrieve the TLS configuration for connecting to a Cassandra container that has been started with TLS enabled. ```go func getTLSConnectionHost(ctx context.Context) (string, error) { container, err := cassandra.Run(ctx, "cassandra:latest", cassandra.WithTLS()) if err != nil { return "", err } tlsConfig, err := container.TLSConfig() if err != nil { return "", err } host, err := container.ConnectionHost(ctx) if err != nil { return "", err } // Use tlsConfig and host to establish a secure connection _ = tlsConfig return host, nil } ``` -------------------------------- ### Example of Any Wait Strategy Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/features/wait/any.md Demonstrates how to use the Any wait strategy with multiple conditions. If any of the provided wait strategies succeed, the overall wait operation will succeed. If any fail, it will fail. ```go func ExampleForAny() { ctx := context.Background() postgres, err := NewContainer(). WithDatabase("my-db"). WithPassword("my-password"). WithWaitStrategy(Any( Wait.ForLog("database system is ready to accept connections"), Wait.ForListeningPort(5432), )). Build() if err != nil { panic(err) } defer postgres.Terminate(ctx) content, err := postgres.Logs(ctx).Get(ctx) if err != nil { panic(err) } fmt.Println(content.String()) } ``` -------------------------------- ### Run a K3s Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/k3s.md Example of how to run a K3s container using the Testcontainers module. This is useful for integration tests. ```go k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1") if err != nil { panic(err) } ``` -------------------------------- ### Prepare Key Client for Local Mode Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Initializes a Key Vault client for interacting with keys in local mode. ```go keyClient, err := lowkeyvault.NewKeyClient(ctx, lowkeyVaultContainer) if err != nil { log.Fatalf("failed to create key client: %s", err) } ``` -------------------------------- ### Create a Certificate in Local Mode Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Demonstrates creating a certificate using the Key Vault Certificates API in local mode. ```go certName := "my-certificate" err = certClient.CreateCertificate(ctx, certName) if err != nil { log.Fatalf("failed to create certificate: %s", err) } ``` -------------------------------- ### Run Neo4j Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/neo4j.md Example of starting a Neo4j container instance with APOC plugins enabled using the Run function. ```golang neo4jContainer, err := neo4j.Run(ctx, "neo4j:5.2.0", neo4j.WithAPOC()) if err != nil { log.Fatalf("failed to start container: %s", err) } defer neo4jContainer.Terminate(ctx) ``` -------------------------------- ### Prepare Certificate Client for Local Mode Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Initializes a Key Vault client for interacting with certificates in local mode. ```go certClient, err := lowkeyvault.NewCertClient(ctx, lowkeyVaultContainer) if err != nil { log.Fatalf("failed to create certificate client: %s", err) } ``` -------------------------------- ### Get Dex gRPC Endpoint Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/dex.md Retrieves the host and mapped port for Dex's gRPC admin API. Ensure the container has started before calling this method. ```golang target, err := c.GRPCEndpoint(ctx) ``` -------------------------------- ### Run OpenFGA Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/openfga.md Demonstrates how to initialize and start an OpenFGA container using the Run function with context and custom options. ```golang func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*OpenFGAContainer, error) ``` -------------------------------- ### Add Dex Module to Project Dependencies Source: https://github.com/testcontainers/testcontainers-go/blob/main/modules/dex/README.md Install the Dex module using go get. This command adds the necessary package to your project's dependencies. ```bash go get github.com/testcontainers/testcontainers-go/modules/dex ``` -------------------------------- ### Example: Running EventHubs with an External Azurite Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Demonstrates how to set up an external Azurite container and network, and then run the EventHubs container using `WithAzuriteContainer`. ```APIDOC ## Example: Running EventHubs with an External Azurite Container ### Description This example shows how to manually create a Docker network and an Azurite container, then configure the EventHubs container to use them via the `WithAzuriteContainer` option. This approach gives the user explicit control over the lifecycle of the Azurite dependency. ### Steps 1. **Create Docker Network**: Instantiate a new Docker network. 2. **Start Azurite Container**: Create and start an Azurite container, attaching it to the created network. 3. **Run EventHubs Container**: Start the EventHubs container, referencing the previously created Azurite container and network using `WithAzuriteContainer`. ### Code Snippet ```golang // Create Network network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{... }) // Start Azurite azuriteContainer, err := azurite.Run(ctx, testcontainers.WithNetwork(network), azurite.WithImage("mcr.microsoft.com/azure-sdk/storage.azurite:latest")) // Run EventHubs with external Azurite eventHubsContainer, err := eventhubs.Run(ctx, "mcr.microsoft.com/azure-messaging/eventhubs-emulator:2.0.1", eventhubs.WithAzuriteContainer(azuriteContainer, network) ) ``` ``` -------------------------------- ### Install OpenSearch module dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/opensearch.md Command to add the OpenSearch module to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/opensearch ``` -------------------------------- ### Install Minio Module Dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/minio.md Command to add the Minio module to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/minio ``` -------------------------------- ### Example: Building and Running EventHubs with a Config Object Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Illustrates how to construct a typed configuration object for EventHubs using functional options and then pass it to the `Run` function via `WithConfigObject`. ```APIDOC ## Example: Building and Running EventHubs with a Config Object ### Description This example demonstrates using the `WithConfigObject` option to provide a structured, type-safe configuration for the EventHubs emulator. It involves creating a `Config` object using builder functions and then passing it to the `Run` function. ### Steps 1. **Build Configuration**: Use `eventhubs.NewConfig` and associated options (`WithNamespace`, `WithEntity`, etc.) to create a `*Config` object. 2. **Run EventHubs Container**: Call the `eventhubs.Run` function, passing the constructed `Config` object using the `eventhubs.WithConfigObject` option. ### Code Snippet ```golang // Build Config Object cfg, err := eventhubs.NewConfig(eventhubs.WithNamespace(eventhubs.EmulatorNamespaceName), eventhubs.WithEntity("my-entity", eventhubs.WithPartitionCount(10), eventhubs.WithConsumerGroup("my-consumer-group")), ) // Run EventHubs with Config Object eventHubsContainer, err := eventhubs.Run(ctx, "mcr.microsoft.com/azure-messaging/eventhubs-emulator:2.0.1", eventhubs.WithConfigObject(cfg) ) ``` ``` -------------------------------- ### Install MockServer Module Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mockserver.md Command to add the MockServer module dependency to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/mockserver ``` -------------------------------- ### Install Inbucket module dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/inbucket.md Command to add the Inbucket module to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/inbucket ``` -------------------------------- ### Configure Container Build with Custom Options Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/features/build_from_dockerfile.md Examples for configuring container requests including registry authentication, image persistence, and advanced build option modifiers. ```go // Registry Auth Example req := ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: "/path/to/build/context", Dockerfile: "CustomDockerfile", }, } // Keep Image Example req := ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ KeepImage: true, }, } // Build Options Modifier Example req := testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: "../../testdata", Dockerfile: "target.Dockerfile", BuildOptionsModifier: func(buildOptions *dockertypes.ImageBuildOptions) { buildOptions.Target = "builder" }, }, } ``` -------------------------------- ### Get Proxied Endpoint Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/toxiproxy.md Example of retrieving the host and port of a proxied endpoint from a Toxiproxy container. This is used to connect to the proxied service. ```go func getProxiedEndpoint(ctx context.Context, toxiproxyContainer *toxiproxy.Container) (string, string, error) { host, port, err := toxiproxyContainer.ProxiedEndpoint(8666) if err != nil { return "", "", err } return host, port, nil } ``` -------------------------------- ### Get MongoDB Connection String Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mongodb.md Example of retrieving the connection string from a running MongoDB container. This string can be used to connect to the database. ```go package main import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/mongodb" ) func main() { ctx := context.Background() mongoContainer, err := mongodb.Run(ctx, "mongo:latest") if err != nil { log.Fatalf("failed to start mongo container: %s", err) } defer func() { if err := mongoContainer.Terminate(ctx); err != nil { log.Fatalf("failed to terminate mongo container: %s", err) } }() connectionString, err := mongoContainer.ConnectionString(ctx) if err != nil { log.Fatalf("failed to get connection string: %s", err) } clientOptions := options.Client().ApplyURI(connectionString) client, err := mongo.Connect(ctx, clientOptions) if err != nil { log.Fatalf("failed to connect to MongoDB: %s", err) } if err := client.Ping(ctx, nil); err != nil { log.Fatalf("failed to ping MongoDB: %s", err) } fmt.Println("Successfully connected to MongoDB!") } ``` -------------------------------- ### Managing Local Documentation Server Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/contributing.md Makefile commands to build, serve, and clean up the local documentation environment using Docker. ```shell make serve-docs make clean-docs ``` -------------------------------- ### Install Redis module dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/redis.md Command to add the Redis module to your Go project dependencies using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/redis ``` -------------------------------- ### Install Postgres Module Dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/postgres.md Command to add the Testcontainers Postgres module to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/postgres ``` -------------------------------- ### Install Milvus module dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/milvus.md Command to add the Milvus module to your Go project dependencies using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/milvus ``` -------------------------------- ### Module Development: Run Function Pattern Source: https://github.com/testcontainers/testcontainers-go/blob/main/AI.md Implement the run function using a five-step process: process options, build defaults, add conditional options, append user options, and call testcontainers.Run with error wrapping. ```go func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*Container, error) { // See docs/modules/index.md for complete implementation moduleOpts := []testcontainers.ContainerCustomizer{ testcontainers.WithExposedPorts("5432/tcp"), // ... defaults } moduleOpts = append(moduleOpts, opts...) ctr, err := testcontainers.Run(ctx, img, moduleOpts...) if err != nil { return nil, fmt.Errorf("run modulename: %w", err) } return &Container{Container: ctr}, nil } ``` -------------------------------- ### Prepare Secret Client for Local Mode Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Initializes a Key Vault client for interacting with secrets in local mode. ```go secretClient, err := lowkeyvault.NewSecretClient(ctx, lowkeyVaultContainer) if err != nil { log.Fatalf("failed to create secret client: %s", err) } ``` -------------------------------- ### Install Consul Module Dependency Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/consul.md Command to add the Testcontainers Consul module to a Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/consul ``` -------------------------------- ### Install Testcontainers for Go via Go Modules Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/quickstart.md Command to add the Testcontainers for Go library to your project dependencies using go get. ```shell go get github.com/testcontainers/testcontainers-go ``` -------------------------------- ### Initialize MS SQL Server with SQL Script (Go) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/mssql.md Example of using `WithInitSQL` to execute SQL files upon container startup. The provided SQL files are copied into the container and executed sequentially. ```go import ( "context" "os" "testing" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/mssql" ) func TestMSSQLServerContainerWithInitSQL(t *testing.T) { ctx := context.Background() seedSQL, err := os.ReadFile("testdata/seed.sql") if err != nil { t.Fatal(err) } container, err := mssql.Run(ctx, mssql.WithInitSQL(bytes.NewReader(seedSQL)), mssql.WithAcceptEULA()) if err != nil { t.Fatal(err) } defer container.Terminate(ctx) // ... further assertions using the container } ``` -------------------------------- ### Install Kafka Testcontainers Module Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/kafka.md Command to add the Kafka module dependency to your Go project using the go get tool. ```bash go get github.com/testcontainers/testcontainers-go/modules/kafka ``` -------------------------------- ### Read Proxied Endpoint and Connect Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/toxiproxy.md Example demonstrating how to get a proxied endpoint and use it to establish a connection to the proxied service, illustrated with a Redis client. ```go func readProxiedEndpoint(ctx context.Context, toxiproxyContainer *toxiproxy.Container) error { host, port, err := toxiproxyContainer.ProxiedEndpoint(8666) if err != nil { return err } redisClient, err := redis.NewClient(&redis.Options{ Addr: net.JoinHostPort(host, port), }) if err != nil { return err } _, err = redisClient.Ping(ctx).Result() return err } ``` -------------------------------- ### Create a Key in Local Mode Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Demonstrates creating a new key using the Key Vault Keys API in local mode. ```go keyName := "my-key" err = keyClient.CreateKey(ctx, keyName) if err != nil { log.Fatalf("failed to create key: %s", err) } ``` -------------------------------- ### Create Vearch Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/vearch.md Example of creating a Vearch container using the Testcontainers for Go module. This function initializes and starts a Vearch container with specified options. ```go func runVearchContainer(ctx context.Context) (*testcontainers.DockerContainer ``` -------------------------------- ### Get Cassandra TLS Configuration Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/cassandra.md Method to retrieve the TLS configuration object for secure connections to a Cassandra container. This is only available if the container was started with TLS enabled. ```go func tlsConfig(ctx context.Context) (*tls.Config, error) { container, err := cassandra.Run(ctx, "cassandra:latest", cassandra.WithTLS()) if err != nil { return nil, err } tlsConfig, err := container.TLSConfig() if err != nil { return nil, err } return tlsConfig, nil } ``` -------------------------------- ### Build Container from Dockerfile with Repository and Tag Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/features/build_from_dockerfile.md Demonstrates how to build a container image by specifying a local file system context and optional repository and tag names. ```go req := testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: "../../testdata", Dockerfile: "Dockerfile", Repo: "test-container", Tag: "latest", }, } ``` -------------------------------- ### Configure Dex Client Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/dex.md Use NewClient to create a client configuration. Pass options like secret, redirect URIs, and grant types. This client can then be passed to the Run function. ```golang app, err := dex.NewClient("my-app", dex.WithClientSecret("secret"), dex.WithClientRedirectURIs("http://localhost:8080/callback"), dex.WithClientGrantTypes("authorization_code", "refresh_token"), dex.WithClientName("My App"), ) // ... c, err := dex.Run(ctx, "dexidp/dex:v2.45.1", dex.WithClient(app)) ``` -------------------------------- ### Create Weaviate Client (No Modules) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/weaviate.md Example of creating a Weaviate Go client without using any specific modules. This is a basic setup for interacting with a Weaviate instance. ```go func createClientNoModules(ctx context.Context) (*weaviate.Client, error) { container, err := weaviate.Run(ctx, "semitechnologies/weaviate:latest") if err != nil { return nil, err } httpHost, err := container.HTTPHostAddress(ctx) if err != nil { return nil, err } client, err := weaviate.NewClient(weaviate.Config{ Host: httpHost, Scheme: "http", }) if err != nil { return nil, err } return client, nil } ``` -------------------------------- ### Run Pubsub Container in Go Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/gcloud.md Provides an example of how to run a Pubsub container using the `Run` function. This setup is foundational for interacting with the Pubsub emulator in tests. ```go package main import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/testcontainers/testcontainers-go" ``` -------------------------------- ### Run BigTable Container (Go) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/gcloud.md Example of how to run a BigTable container using the Testcontainers Go module. It shows the function signature for starting the container with a specified Docker image. ```go c, err := bigtable.Run(ctx, "gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators") if err != nil { // handle error } ``` -------------------------------- ### Test Nginx Container with Testcontainers Go Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/examples/nginx.md This Go test code snippet demonstrates how to verify the functionality of an Nginx container started with Testcontainers. It checks if the container is running and accessible. ```go package nginx_test import ( "context" "net/http" "testing" ``` ```go "github.com/stretchr/testify/assert" "github.com/testcontainers/testcontainers-go/modules/nginx" ) func TestNginxContainer(t *testing.T) { ctx := context.Background() // Start Nginx container nginxContainer, err := nginx.Run(ctx, "latest") if err != nil { t *testing.T).Fatal(err) } defer func() { if err := nginxContainer.Terminate(ctx); err != nil { t *testing.T).Fatalf("failed to terminate container: %s", err) } }() // Get the mapped port mappedPort, err := nginxContainer.MappedPort(ctx, nginx.Port) if err != nil { t *testing.T).Fatal(err) } // Make an HTTP request to the Nginx container resp, err := http.Get(nginxContainer.URI + mappedPort.Port()) if err != nil { t *testing.T).Fatalf("failed to get response from nginx: %s", err) } defer resp.Body.Close() // Assert that the response status code is OK assert.Equal(t, http.StatusOK, resp.StatusCode) } ``` -------------------------------- ### Create Docker Network for EventHubs Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Demonstrates how to create a Docker network that will be used by the Azurite and EventHubs containers. This is part of managing external dependencies manually. ```go network, err := testcontainers.NewNetwork(ctx, "eventhubs-network") if err != nil { t.Fatal(err) } ``` -------------------------------- ### Get Memcached Container Host and Port Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/memcached.md Go code example demonstrating how to retrieve the host and port of a running Memcached container. This is essential for connecting your application to the Memcached instance managed by Testcontainers. ```go endpoint, err := memcachedContainer.HostPort(ctx) if err != nil { t.Fatal(err) } // The endpoint will be in the format "host:port", e.g., "localhost:11211" ``` -------------------------------- ### Run K6 Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/k6.md Demonstrates initializing a K6 container using the Run function, which requires a context, a k6x Docker image, and optional container configurations. ```go func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*K6Container, error) // Example usage: Run(context.Background(), "szkiba/k6x:v0.3.1") ``` -------------------------------- ### Get Qdrant Container gRPC Endpoint Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/qdrant.md This Go code retrieves the gRPC endpoint URL for a running Qdrant container. It assumes the container is already started and accessible. The gRPC endpoint is used for high-performance communication with Qdrant services. ```go func gRPCEndpoint(ctx context.Context) (string, error) { container, err := qdrant.Run(ctx, "qdrant/qdrant:latest") if err != nil { return "", err } endpoint, err := container.GrpcEndpoint(ctx) if err != nil { return "", err } return endpoint, nil } ``` -------------------------------- ### Configure EventHubs Container Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/azure.md Sets up the configuration for the EventHubs container. This is typically the first step in using the EventHubs module. ```go cfg := azure.NewEventHubsConfig() cfg.WithImageName(azure.EventHubsImage()) ``` -------------------------------- ### Get Ollama Connection String (Go) Source: https://github.com/testcontainers/testcontainers-go/blob/main/docs/modules/ollama.md Retrieves the connection string to connect to the Ollama instance. This method is available both for containerized and local Ollama executions. For local execution, it returns the connection string to the locally started Ollama binary. ```go import ( "context" "github.com/testcontainers/testcontainers-go/modules/ollama" ) func main() { ctx := context.Background() // Assuming 'o' is an initialized Ollama container or local instance o, err := ollama.Run(ctx, "ollama/ollama:0.5.7") if err != nil { panic(err) } connectionString, err := o.ConnectionString() if err != nil { panic(err) } // Use connectionString to connect to Ollama _ = connectionString } ```