Skip to content

Commit 066ee8e

Browse files
committed
docs: Add section for IContainer.ConnectAsync(...)
1 parent ca9f416 commit 066ee8e

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

docs/api/create_docker_network.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,37 @@ var execResult = await ultimateQuestionContainer.ExecAsync(new[] { "nc", MagicNu
5656
Assert.Equal(MagicNumber, execResult.Stdout.Trim());
5757
```
5858

59+
## Connecting a running container to an existing network
60+
61+
If a container is already running, use `IContainer.ConnectAsync(...)` to attach it to an existing network.
62+
63+
The network must already exist. You can reference it either by network name or by an `INetwork` instance:
64+
65+
```csharp
66+
var network = new NetworkBuilder()
67+
.WithName(Guid.NewGuid().ToString("D"))
68+
.Build();
69+
70+
var container = new ContainerBuilder("alpine:3.20.0")
71+
.WithEntrypoint("top")
72+
.Build();
73+
74+
await network.CreateAsync()
75+
.ConfigureAwait(false);
76+
77+
await container.StartAsync()
78+
.ConfigureAwait(false);
79+
80+
await container.ConnectAsync(network)
81+
.ConfigureAwait(false);
82+
83+
// Equivalent when only the network name is available:
84+
await container.ConnectAsync(network.Name)
85+
.ConfigureAwait(false);
86+
```
87+
88+
Prefer `WithNetwork(...)` during container configuration whenever possible. Use `ConnectAsync(...)` when you explicitly need to attach a running container to an already existing network.
89+
5990
## Exposing container ports to the host
6091

6192
It is common to connect to a container from your test process running on your test host. To bind and expose a container port, use the `WithPortBinding(ushort, true)` container builder member. To retrieve the actual port at runtime, use the container `GetMappedPublicPort(ushort)` member. Further information on network configurations is included in our [best practices](https://dotnet.testcontainers.org/api/best_practices/).

0 commit comments

Comments
 (0)