Skip to content

How to create a network

Apart from creating containers, Testcontainers for Go allows you to create networks. This is useful when you need to connect multiple containers to the same network.

For that, please import the testcontainers/network package.

import "github.com/testcontainers/testcontainers-go/network"

Then, you can create a network using the network.New function. This function receives a variadic list of options that can be used to configure the network.

  • WithAttachable()
  • WithCheckDuplicate()
  • WithDriver(driver string)
  • WithEnableIPv6()
  • WithInternal()
  • WithLabels(labels map[string]string)
  • WithIPAMConfig(config *network.IPAMConfig)

It's important to mention that the name of the network is automatically generated by the library, and it's not possible to set it manually. However, you can retrieve the name of the network using the Name field of the DockerNetwork struct returned by the New function.

Usage example

ctx := context.Background()

net, err := network.New(ctx,
    network.WithAttachable(),
    // Makes the network internal only, meaning the host machine cannot access it.
    // Remove or use `network.WithDriver("bridge")` to change the network's mode.
    network.WithInternal(),
    network.WithLabels(map[string]string{"this-is-a-test": "value"}),
)
if err != nil {
    fmt.Println(err)
    return
}
defer func() {
    if err := net.Remove(ctx); err != nil {
        log.Fatalf("failed to remove network: %s", err)
    }
}()

networkName := net.Name
ctx := context.Background()

// dockernetwork is the alias used for github.com/docker/docker/api/types/network
ipamConfig := dockernetwork.IPAM{
    Driver: "default",
    Config: []dockernetwork.IPAMConfig{
        {
            Subnet:  "10.1.1.0/24",
            Gateway: "10.1.1.254",
        },
    },
    Options: map[string]string{
        "driver": "host-local",
    },
}
net, err := network.New(ctx,
    network.WithIPAM(&ipamConfig),
    network.WithAttachable(),
    network.WithDriver("bridge"),
)