Skip to content

How to create a network

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

Usage example

ctx := context.Background()
networkName := "new-network"
net, _ := GenericNetwork(ctx, GenericNetworkRequest{
    NetworkRequest: NetworkRequest{
        Name:           networkName,
        CheckDuplicate: true,
    },
})
defer func() {
    if err := net.Remove(ctx); err != nil {
        panic(err)
    }
}()
ctx := context.Background()
networkName := "test-network-with-ipam"
ipamConfig := network.IPAM{
    Driver: "default",
    Config: []network.IPAMConfig{
        {
            Subnet:  "10.1.1.0/24",
            Gateway: "10.1.1.254",
        },
    },
    Options: map[string]string{
        "driver": "host-local",
    },
}
net, err := GenericNetwork(ctx, GenericNetworkRequest{
    NetworkRequest: NetworkRequest{
        Name:           networkName,
        CheckDuplicate: true,
        IPAM:           &ipamConfig,
    },
})