NATS¶
Since v0.24.0
Introduction¶
The Testcontainers module for NATS.
Adding this module to your project dependencies¶
Please run the following command to add the NATS module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/nats
Usage example¶
ctx := context.Background()
natsContainer, err := nats.Run(ctx, "nats:2.9")
defer func() {
if err := testcontainers.TerminateContainer(natsContainer); 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 NATS module exposes one entrypoint function to create the NATS container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*NATSContainer, error)
context.Context
, the Go context.string
, the Docker image to use.testcontainers.ContainerCustomizer
, a variadic argument for passing options.
Image¶
Use the second argument in the Run
function to set a valid Docker image.
In example: Run(context.Background(), "nats:2.9")
.
Container Options¶
When starting the NATS container, you can pass options in a variadic way to configure it.
Set username and password¶
- Since v0.24.0
If you need to set different credentials, you can use WithUsername
and WithPassword
options. By default, the username, the password are not set. To establish the connection with the NATS container:
ctx := context.Background()
ctr, err := nats.Run(ctx, "nats:2.9", nats.WithUsername("foo"), nats.WithPassword("bar"))
defer func() {
if err := testcontainers.TerminateContainer(ctr); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
uri, err := ctr.ConnectionString(ctx)
if err != nil {
log.Printf("failed to get connection string: %s", err)
return
}
nc, err := natsgo.Connect(uri, natsgo.UserInfo(ctr.User, ctr.Password))
if err != nil {
log.Printf("failed to connect to NATS: %s", err)
return
}
defer nc.Close()
Cmd Arguments¶
- Since v0.24.0
It's possible to pass extra arguments to the NATS container using the testcontainers.WithArgument
option. E.g. nats.WithArgument("cluster_name", "c1")
.
These arguments are passed to the NATS server when it starts, as part of the command line arguments of the entrypoint.
Note
Arguments do not need to be prefixed with --
: the NATS container will add them automatically.
natsContainer1, err := nats.Run(ctx,
"nats:2.9",
network.WithNetwork([]string{"nats1"}, nwr),
nats.WithArgument("name", "nats1"),
nats.WithArgument("cluster_name", "c1"),
nats.WithArgument("cluster", "nats://nats1:6222"),
nats.WithArgument("routes", "nats://nats1:6222,nats://nats2:6222,nats://nats3:6222"),
nats.WithArgument("http_port", "8222"),
)
Custom configuration file¶
- Since v0.35.0
It's possible to pass a custom config file to NATS container using nats.WithConfigFile(strings.NewReader(config))
. The content of io.Reader
is passed as a -config /etc/nats.conf
arguments to an entrypoint.
Note
Changing the connectivity (listen address or ports) can break the container setup. So configuration must be done with care.
The following options are exposed by the testcontainers
package.
Basic Options¶
WithExposedPorts
Since v0.37.0WithEnv
Since v0.29.0WithWaitStrategy
Since v0.20.0WithAdditionalWaitStrategy
Not available until the next release mainWithWaitStrategyAndDeadline
Since v0.20.0WithAdditionalWaitStrategyAndDeadline
Not available until the next release mainWithEntrypoint
Since v0.37.0WithEntrypointArgs
Since v0.37.0WithCmd
Since v0.37.0WithCmdArgs
Since v0.37.0WithLabels
Since v0.37.0
Lifecycle Options¶
WithLifecycleHooks
Not available until the next release mainWithAdditionalLifecycleHooks
Not available until the next release mainWithStartupCommand
Since v0.25.0WithAfterReadyCommand
Since v0.28.0
Files & Mounts Options¶
WithFiles
Since v0.37.0WithMounts
Since v0.37.0WithTmpfs
Since v0.37.0WithImageMount
Since v0.37.0
Build Options¶
WithDockerfile
Since v0.37.0
Logging Options¶
WithLogConsumers
Since v0.28.0WithLogConsumerConfig
Not available until the next release mainWithLogger
Since v0.29.0
Image Options¶
WithAlwaysPull
Not available until the next release mainWithImageSubstitutors
Since v0.26.0WithImagePlatform
Not available until the next release main
Networking Options¶
WithNetwork
Since v0.27.0WithNetworkByName
Not available until the next release mainWithBridgeNetwork
Not available until the next release mainWithNewNetwork
Since v0.27.0
Advanced Options¶
WithHostPortAccess
Since v0.31.0WithConfigModifier
Since v0.20.0WithHostConfigModifier
Since v0.20.0WithEndpointSettingsModifier
Since v0.20.0CustomizeRequest
Since v0.20.0WithName
Not available until the next release mainWithNoStart
Not available until the next release main
Experimental Options¶
WithReuseByName
Since v0.37.0
Container Methods¶
The NATS container exposes the following methods:
ConnectionString¶
- Since v0.24.0
This method returns the connection string to connect to the NATS container, using the default 4222
port.
uri, err := ctr.ConnectionString(ctx)
MustConnectionString¶
- Since v0.30.0
Exactly like ConnectionString
, but it panics if an error occurs, returning just a string.
Examples¶
NATS Cluster¶
ctx := context.Background()
nwr, err := network.New(ctx)
if err != nil {
log.Printf("failed to create network: %s", err)
return
}
defer func() {
if err := nwr.Remove(context.Background()); err != nil {
log.Printf("failed to remove network: %s", err)
}
}()
// withArguments {
natsContainer1, err := nats.Run(ctx,
"nats:2.9",
network.WithNetwork([]string{"nats1"}, nwr),
nats.WithArgument("name", "nats1"),
nats.WithArgument("cluster_name", "c1"),
nats.WithArgument("cluster", "nats://nats1:6222"),
nats.WithArgument("routes", "nats://nats1:6222,nats://nats2:6222,nats://nats3:6222"),
nats.WithArgument("http_port", "8222"),
)
// }
defer func() {
if err := testcontainers.TerminateContainer(natsContainer1); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
natsContainer2, err := nats.Run(ctx,
"nats:2.9",
network.WithNetwork([]string{"nats2"}, nwr),
nats.WithArgument("name", "nats2"),
nats.WithArgument("cluster_name", "c1"),
nats.WithArgument("cluster", "nats://nats2:6222"),
nats.WithArgument("routes", "nats://nats1:6222,nats://nats2:6222,nats://nats3:6222"),
nats.WithArgument("http_port", "8222"),
)
defer func() {
if err := testcontainers.TerminateContainer(natsContainer2); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
natsContainer3, err := nats.Run(ctx,
"nats:2.9",
network.WithNetwork([]string{"nats3"}, nwr),
nats.WithArgument("name", "nats3"),
nats.WithArgument("cluster_name", "c1"),
nats.WithArgument("cluster", "nats://nats3:6222"),
nats.WithArgument("routes", "nats://nats1:6222,nats://nats2:6222,nats://nats3:6222"),
nats.WithArgument("http_port", "8222"),
)
defer func() {
if err := testcontainers.TerminateContainer(natsContainer3); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
// cluster URL
servers := natsContainer1.MustConnectionString(ctx) + "," + natsContainer2.MustConnectionString(ctx) + "," + natsContainer3.MustConnectionString(ctx)
nc, err := natsgo.Connect(servers, natsgo.MaxReconnects(5), natsgo.ReconnectWait(2*time.Second))
if err != nil {
log.Printf("connecting to nats container failed:\n\t%v\n", err)
return
}
// Close connection
defer nc.Close()
{
// Simple Publisher
err = nc.Publish("foo", []byte("Hello World"))
if err != nil {
log.Printf("failed to publish message: %s", err)
return
}
}
{
// Channel subscriber
ch := make(chan *natsgo.Msg, 64)
sub, err := nc.ChanSubscribe("channel", ch)
if err != nil {
log.Printf("failed to subscribe to message: %s", err)
return
}
// Request
err = nc.Publish("channel", []byte("Hello NATS Cluster!"))
if err != nil {
log.Printf("failed to publish message: %s", err)
return
}
msg := <-ch
fmt.Println(string(msg.Data))
err = sub.Unsubscribe()
if err != nil {
log.Printf("failed to unsubscribe: %s", err)
return
}
err = sub.Drain()
if err != nil {
log.Printf("failed to drain: %s", err)
return
}
}
{
// Responding to a request message
sub, err := nc.Subscribe("request", func(m *natsgo.Msg) {
err1 := m.Respond([]byte("answer is 42"))
if err1 != nil {
log.Printf("failed to respond to message: %s", err1)
return
}
})
if err != nil {
log.Printf("failed to subscribe to message: %s", err)
return
}
// Request
msg, err := nc.Request("request", []byte("what is the answer?"), 1*time.Second)
if err != nil {
log.Printf("failed to send request: %s", err)
return
}
fmt.Println(string(msg.Data))
err = sub.Unsubscribe()
if err != nil {
log.Printf("failed to unsubscribe: %s", err)
return
}
err = sub.Drain()
if err != nil {
log.Printf("failed to drain: %s", err)
return
}
}
// Drain connection (Preferred for responders)
// Close() not needed if this is called.
err = nc.Drain()
if err != nil {
log.Printf("failed to drain connection: %s", err)
return
}
// Output:
// Hello NATS Cluster!
// answer is 42