0
# Network Management
1
2
Docker network creation and management for container communication, enabling multi-container test scenarios with proper network isolation and service discovery between containers.
3
4
## Capabilities
5
6
### Network Interface
7
8
Core network management interface providing Docker network lifecycle management and container networking capabilities.
9
10
```java { .api }
11
/**
12
* Interface for Docker network management and container communication
13
*/
14
public interface Network extends AutoCloseable {
15
16
/** Shared network instance for simple multi-container scenarios */
17
static Network SHARED;
18
19
/** Create a new network with default settings */
20
static Network newNetwork();
21
22
/** Create a network builder for advanced configuration */
23
static Builder builder();
24
25
/** Get the Docker network ID */
26
String getId();
27
28
/** Get the network driver name */
29
String getDriver();
30
31
/** Get network creation options */
32
Map<String, String> getOptions();
33
34
/** Clean up the network (remove from Docker) */
35
@Override
36
void close();
37
38
/**
39
* Builder interface for creating networks with custom configuration
40
*/
41
interface Builder {
42
/** Configure network driver (default: bridge) */
43
Builder withDriver(String driver);
44
45
/** Configure network options */
46
Builder withOption(String key, String value);
47
48
/** Configure network labels */
49
Builder withLabel(String key, String value);
50
51
/** Enable manual network attachment instead of automatic */
52
Builder withAttachable(boolean attachable);
53
54
/** Configure internal network (no external connectivity) */
55
Builder withInternal(boolean internal);
56
57
/** Build the network with specified configuration */
58
Network build();
59
}
60
}
61
```
62
63
**Usage Examples:**
64
65
```java
66
import org.testcontainers.containers.Network;
67
import org.testcontainers.containers.GenericContainer;
68
69
// Using shared network for simple scenarios
70
GenericContainer<?> database = new GenericContainer<>("postgres:13")
71
.withNetwork(Network.SHARED)
72
.withNetworkAliases("db")
73
.withEnv("POSTGRES_DB", "testdb");
74
75
GenericContainer<?> application = new GenericContainer<>("myapp:latest")
76
.withNetwork(Network.SHARED)
77
.withNetworkAliases("app");
78
79
// Creating custom network
80
try (Network customNetwork = Network.newNetwork()) {
81
GenericContainer<?> service1 = new GenericContainer<>("service1:latest")
82
.withNetwork(customNetwork)
83
.withNetworkAliases("service1");
84
85
GenericContainer<?> service2 = new GenericContainer<>("service2:latest")
86
.withNetwork(customNetwork)
87
.withNetworkAliases("service2");
88
}
89
90
// Advanced network configuration
91
try (Network advancedNetwork = Network.builder()
92
.withDriver("bridge")
93
.withOption("com.docker.network.bridge.name", "testnetwork")
94
.withLabel("test", "integration")
95
.build()) {
96
97
// Use the configured network
98
}
99
```
100
101
### Network Creation
102
103
Factory methods and builders for creating Docker networks with various configurations.
104
105
```java { .api }
106
/**
107
* Network creation utilities and factory methods
108
*/
109
public class NetworkImpl implements Network {
110
111
/** Create network with default bridge driver */
112
public static Network newNetwork();
113
114
/** Create network with specific driver */
115
public static Network newNetwork(String driver);
116
117
/** Get network builder for advanced configuration */
118
public static Builder builder();
119
}
120
121
/**
122
* Network builder implementation for custom network configuration
123
*/
124
public static class NetworkBuilder implements Network.Builder {
125
126
private String driver = "bridge";
127
private Map<String, String> options = new HashMap<>();
128
private Map<String, String> labels = new HashMap<>();
129
private boolean attachable = false;
130
private boolean internal = false;
131
132
@Override
133
public Builder withDriver(String driver);
134
135
@Override
136
public Builder withOption(String key, String value);
137
138
@Override
139
public Builder withLabel(String key, String value);
140
141
@Override
142
public Builder withAttachable(boolean attachable);
143
144
@Override
145
public Builder withInternal(boolean internal);
146
147
@Override
148
public Network build();
149
}
150
```
151
152
### Container Network Configuration
153
154
Methods for configuring container networking and service discovery.
155
156
```java { .api }
157
/**
158
* Container networking configuration methods (from GenericContainer)
159
*/
160
// Network attachment
161
public SELF withNetwork(Network network);
162
public SELF withNetworkMode(String networkMode);
163
164
// Service discovery via network aliases
165
public SELF withNetworkAliases(String... aliases);
166
public Set<String> getNetworkAliases();
167
168
// Network-specific connection information
169
public String getNetworkAddress(String networkAlias);
170
public String getContainerIpAddress();
171
172
// Legacy container linking (deprecated)
173
@Deprecated
174
public SELF withLinks(String... links);
175
```
176
177
**Usage Examples:**
178
179
```java
180
// Multi-container communication via network aliases
181
Network testNetwork = Network.newNetwork();
182
183
GenericContainer<?> database = new GenericContainer<>("postgres:13")
184
.withNetwork(testNetwork)
185
.withNetworkAliases("database", "db", "postgres")
186
.withEnv("POSTGRES_DB", "testdb")
187
.withEnv("POSTGRES_USER", "user")
188
.withEnv("POSTGRES_PASSWORD", "password");
189
190
GenericContainer<?> app = new GenericContainer<>("myapp:latest")
191
.withNetwork(testNetwork)
192
.withNetworkAliases("application", "app")
193
.withEnv("DATABASE_URL", "jdbc:postgresql://database:5432/testdb");
194
195
// Application can now connect to database using alias "database"
196
```
197
198
### Network Modes
199
200
Standard Docker network modes that can be used with containers.
201
202
```java { .api }
203
/**
204
* Standard Docker network modes for container networking
205
*/
206
public static final String NETWORK_MODE_BRIDGE = "bridge";
207
public static final String NETWORK_MODE_HOST = "host";
208
public static final String NETWORK_MODE_NONE = "none";
209
public static final String NETWORK_MODE_CONTAINER = "container:";
210
211
// Usage examples:
212
container.withNetworkMode("host"); // Host networking
213
container.withNetworkMode("none"); // No networking
214
container.withNetworkMode("container:name"); // Share network with another container
215
```
216
217
### Service Discovery
218
219
Methods for discovering and connecting to services within Docker networks.
220
221
```java { .api }
222
/**
223
* Service discovery within Docker networks
224
*/
225
// From ContainerState interface
226
public String getNetworkAddress(String networkAlias);
227
public String getContainerIpAddress();
228
229
// Network-aware connection URLs
230
public String getJdbcUrl(); // For database containers
231
public String getConnectionUrl(); // Generic connection URL
232
233
// Port access within networks
234
public Integer getExposedPort(int containerPort); // Internal port
235
public Integer getMappedPort(int containerPort); // External mapped port
236
```
237
238
## Advanced Network Patterns
239
240
### Multi-Service Architecture
241
242
Setting up complex multi-service test environments with proper network isolation:
243
244
```java
245
@Test
246
public void testMicroservicesArchitecture() {
247
try (Network microservicesNetwork = Network.newNetwork()) {
248
249
// Database service
250
GenericContainer<?> database = new GenericContainer<>("postgres:13")
251
.withNetwork(microservicesNetwork)
252
.withNetworkAliases("postgres")
253
.withEnv("POSTGRES_DB", "orderdb")
254
.withEnv("POSTGRES_USER", "orders")
255
.withEnv("POSTGRES_PASSWORD", "secret");
256
257
// Message queue service
258
GenericContainer<?> messageQueue = new GenericContainer<>("rabbitmq:3-management")
259
.withNetwork(microservicesNetwork)
260
.withNetworkAliases("rabbitmq")
261
.withExposedPorts(5672, 15672);
262
263
// Order service
264
GenericContainer<?> orderService = new GenericContainer<>("orderservice:latest")
265
.withNetwork(microservicesNetwork)
266
.withNetworkAliases("orders")
267
.withEnv("DATABASE_URL", "jdbc:postgresql://postgres:5432/orderdb")
268
.withEnv("RABBITMQ_URL", "amqp://rabbitmq:5672")
269
.withExposedPorts(8080);
270
271
// User service
272
GenericContainer<?> userService = new GenericContainer<>("userservice:latest")
273
.withNetwork(microservicesNetwork)
274
.withNetworkAliases("users")
275
.withEnv("ORDERS_SERVICE_URL", "http://orders:8080")
276
.withExposedPorts(8081);
277
278
// Start all services
279
database.start();
280
messageQueue.start();
281
orderService.start();
282
userService.start();
283
284
// Services can communicate using network aliases
285
// Tests can access services via mapped ports
286
String userServiceUrl = "http://" + userService.getHost() + ":" + userService.getMappedPort(8081);
287
}
288
}
289
```
290
291
### Network Isolation Testing
292
293
Testing network isolation and security boundaries:
294
295
```java
296
@Test
297
public void testNetworkIsolation() {
298
// Create isolated networks
299
try (Network publicNetwork = Network.newNetwork();
300
Network privateNetwork = Network.newNetwork()) {
301
302
// Public-facing service
303
GenericContainer<?> webServer = new GenericContainer<>("nginx:alpine")
304
.withNetwork(publicNetwork)
305
.withNetworkAliases("web")
306
.withExposedPorts(80);
307
308
// Private database (not accessible from public network)
309
GenericContainer<?> database = new GenericContainer<>("postgres:13")
310
.withNetwork(privateNetwork) // Different network
311
.withNetworkAliases("db")
312
.withEnv("POSTGRES_DB", "private");
313
314
// Application bridge (connected to both networks)
315
GenericContainer<?> app = new GenericContainer<>("myapp:latest")
316
.withNetwork(publicNetwork) // Can receive public requests
317
.withNetworkAliases("app");
318
319
// Manually attach to private network for database access
320
// app.getContainerInfo().getNetworkSettings().getNetworks()
321
// .put(privateNetwork.getId(), ...);
322
}
323
}
324
```
325
326
### Custom Network Drivers
327
328
Working with custom network drivers and advanced configurations:
329
330
```java
331
// Custom bridge network with specific subnet
332
Network customBridge = Network.builder()
333
.withDriver("bridge")
334
.withOption("com.docker.network.bridge.name", "testbr0")
335
.withOption("com.docker.network.driver.mtu", "1500")
336
.withOption("subnet", "172.20.0.0/16")
337
.withLabel("environment", "test")
338
.withLabel("project", "integration-tests")
339
.build();
340
341
// Overlay network for swarm-like testing (requires Docker in swarm mode)
342
Network overlayNetwork = Network.builder()
343
.withDriver("overlay")
344
.withAttachable(true)
345
.withOption("encrypted", "true")
346
.build();
347
348
// Internal network with no external connectivity
349
Network internalNetwork = Network.builder()
350
.withDriver("bridge")
351
.withInternal(true)
352
.withLabel("isolation", "complete")
353
.build();
354
```
355
356
## Network Management Best Practices
357
358
### Resource Cleanup
359
360
```java
361
// Always use try-with-resources for automatic cleanup
362
try (Network network = Network.newNetwork()) {
363
// Use network with containers
364
} // Network is automatically removed
365
366
// Or manual cleanup
367
Network network = Network.newNetwork();
368
try {
369
// Use network
370
} finally {
371
network.close(); // Explicitly clean up
372
}
373
```
374
375
### Shared vs Custom Networks
376
377
```java
378
// Use SHARED network for simple scenarios
379
Network.SHARED; // Convenient but shared across tests
380
381
// Create custom networks for isolation
382
Network.newNetwork(); // Isolated per test/scenario
383
```