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)
if err != nil {
    fmt.Println(err)
    return
}
defer func() {
    if err := net.Remove(ctx); err != nil {
        log.Printf("failed to remove network: %s", err)
    }
}()
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"),
)
if err != nil {
    fmt.Println(err)
    return
}
defer func() {
    if err := net.Remove(ctx); err != nil {
        log.Printf("failed to remove network: %s", err)
    }
}()