or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-configuration.mdcontainers.mdimages.mdindex.mdnetworks.mdswarm.mdvolumes.md

networks.mddocs/

0

# Network Management

1

2

This document covers Docker network operations including network creation, configuration, container connectivity, and network inspection.

3

4

## Network Listing and Inspection

5

6

### Listing Networks

7

8

```java { .api }

9

import com.spotify.docker.client.DockerClient;

10

import com.spotify.docker.client.messages.Network;

11

12

// List all networks

13

List<Network> networks = docker.listNetworks();

14

15

// Filter by network ID

16

List<Network> specific = docker.listNetworks(

17

ListNetworksParam.byNetworkId("network-id")

18

);

19

20

// Filter by network name

21

List<Network> named = docker.listNetworks(

22

ListNetworksParam.byNetworkName("my-network")

23

);

24

25

// Filter by driver

26

List<Network> bridgeNetworks = docker.listNetworks(

27

ListNetworksParam.withDriver("bridge")

28

);

29

30

// Filter by type

31

List<Network> customNetworks = docker.listNetworks(

32

ListNetworksParam.customNetworks()

33

);

34

35

List<Network> builtinNetworks = docker.listNetworks(

36

ListNetworksParam.builtInNetworks()

37

);

38

39

// Filter by labels

40

List<Network> labeledNetworks = docker.listNetworks(

41

ListNetworksParam.withLabel("environment", "production")

42

);

43

```

44

45

### Network Inspection

46

47

```java { .api }

48

// Inspect specific network

49

Network network = docker.inspectNetwork("network-id-or-name");

50

51

System.out.println("Network ID: " + network.id());

52

System.out.println("Name: " + network.name());

53

System.out.println("Driver: " + network.driver());

54

System.out.println("Scope: " + network.scope());

55

System.out.println("Internal: " + network.internal());

56

System.out.println("IPv6 Enabled: " + network.enableIpv6());

57

58

// Network labels

59

Map<String, String> labels = network.labels();

60

System.out.println("Labels: " + labels);

61

62

// Driver options

63

Map<String, String> options = network.options();

64

System.out.println("Driver Options: " + options);

65

66

// IPAM configuration

67

Ipam ipam = network.ipam();

68

if (ipam != null) {

69

System.out.println("IPAM Driver: " + ipam.driver());

70

System.out.println("IPAM Config: " + ipam.config());

71

}

72

73

// Connected containers

74

Map<String, AttachedNetwork> containers = network.containers();

75

for (Map.Entry<String, AttachedNetwork> entry : containers.entrySet()) {

76

AttachedNetwork attached = entry.getValue();

77

System.out.println("Container: " + entry.getKey());

78

System.out.println(" Name: " + attached.name());

79

System.out.println(" Endpoint ID: " + attached.endpointId());

80

System.out.println(" MAC Address: " + attached.macAddress());

81

System.out.println(" IPv4 Address: " + attached.ipv4Address());

82

System.out.println(" IPv6 Address: " + attached.ipv6Address());

83

}

84

```

85

86

## Network Creation

87

88

### Basic Network Creation

89

90

```java { .api }

91

import com.spotify.docker.client.messages.*;

92

93

// Create simple bridge network

94

NetworkConfig config = NetworkConfig.builder()

95

.name("my-network")

96

.driver("bridge")

97

.build();

98

99

NetworkCreation creation = docker.createNetwork(config);

100

System.out.println("Created network ID: " + creation.id());

101

```

102

103

### Advanced Network Configuration

104

105

```java { .api }

106

// IPAM configuration for custom IP addressing

107

IpamConfig ipamConfig = IpamConfig.builder()

108

.subnet("172.20.0.0/16")

109

.ipRange("172.20.240.0/20")

110

.gateway("172.20.0.1")

111

.auxAddress(Map.of("host1", "172.20.1.5"))

112

.build();

113

114

Ipam ipam = Ipam.builder()

115

.driver("default")

116

.config(ipamConfig)

117

.options(Map.of("foo", "bar"))

118

.build();

119

120

// Network configuration with all options

121

NetworkConfig networkConfig = NetworkConfig.builder()

122

.name("production-network")

123

.driver("bridge")

124

.checkDuplicate(true)

125

.internal(false)

126

.enableIpv6(false)

127

.ipam(ipam)

128

.options(Map.of(

129

"com.docker.network.bridge.enable_icc", "true",

130

"com.docker.network.bridge.enable_ip_masquerade", "true",

131

"com.docker.network.bridge.host_binding_ipv4", "0.0.0.0",

132

"com.docker.network.bridge.name", "docker0",

133

"com.docker.network.driver.mtu", "1500"

134

))

135

.labels(Map.of(

136

"environment", "production",

137

"team", "backend",

138

"project", "webapp"

139

))

140

.build();

141

142

NetworkCreation creation = docker.createNetwork(networkConfig);

143

```

144

145

### Overlay Network for Swarm

146

147

```java { .api }

148

// Create overlay network for Docker Swarm

149

NetworkConfig overlayConfig = NetworkConfig.builder()

150

.name("swarm-overlay")

151

.driver("overlay")

152

.attachable(true) // Allow standalone containers to attach

153

.scope("swarm")

154

.labels(Map.of("purpose", "swarm-communication"))

155

.build();

156

157

NetworkCreation swarmNetwork = docker.createNetwork(overlayConfig);

158

```

159

160

### Host and None Networks

161

162

```java { .api }

163

// Host network (containers share host network stack)

164

NetworkConfig hostConfig = NetworkConfig.builder()

165

.name("host-network")

166

.driver("host")

167

.build();

168

169

// None network (containers have no networking)

170

NetworkConfig noneConfig = NetworkConfig.builder()

171

.name("isolated-network")

172

.driver("null")

173

.build();

174

```

175

176

## Container Network Connectivity

177

178

### Connecting Containers to Networks

179

180

```java { .api }

181

// Connect container to network (simple)

182

docker.connectToNetwork("network-id", "container-id");

183

184

// Connect with specific configuration

185

NetworkConnection connection = NetworkConnection.builder()

186

.containerId("container-id")

187

.endpointConfig(EndpointConfig.builder()

188

.ipamConfig(EndpointIpamConfig.builder()

189

.ipv4Address("172.20.0.10")

190

.ipv6Address("2001:db8::10")

191

.build())

192

.aliases("web-server", "api")

193

.build())

194

.build();

195

196

docker.connectToNetwork("network-id", connection);

197

```

198

199

### Advanced Endpoint Configuration

200

201

```java { .api }

202

EndpointConfig endpointConfig = EndpointConfig.builder()

203

// Static IP assignment

204

.ipamConfig(EndpointIpamConfig.builder()

205

.ipv4Address("172.20.0.100")

206

.build())

207

208

// Network aliases

209

.aliases("web", "www", "frontend")

210

211

// Links (legacy)

212

.links("database:db", "cache:redis")

213

214

// Driver options

215

.driverOpts(Map.of("com.example.option", "value"))

216

217

.build();

218

219

NetworkConnection connection = NetworkConnection.builder()

220

.containerId("container-id")

221

.endpointConfig(endpointConfig)

222

.build();

223

224

docker.connectToNetwork("production-network", connection);

225

```

226

227

### Disconnecting Containers

228

229

```java { .api }

230

// Disconnect container from network

231

docker.disconnectFromNetwork("container-id", "network-id");

232

233

// Force disconnect (even if container is running)

234

docker.disconnectFromNetwork("container-id", "network-id", true);

235

```

236

237

## Network Configuration in Container Creation

238

239

### Container with Custom Networks

240

241

```java { .api }

242

// Create container with network configuration

243

NetworkingConfig networkingConfig = NetworkingConfig.builder()

244

.endpointsConfig(Map.of(

245

"my-network", EndpointConfig.builder()

246

.ipamConfig(EndpointIpamConfig.builder()

247

.ipv4Address("172.20.0.50")

248

.build())

249

.aliases("api-server")

250

.build()

251

))

252

.build();

253

254

ContainerConfig config = ContainerConfig.builder()

255

.image("nginx:latest")

256

.networkingConfig(networkingConfig)

257

.build();

258

259

ContainerCreation container = docker.createContainer(config);

260

```

261

262

### Host Configuration for Networking

263

264

```java { .api }

265

HostConfig hostConfig = HostConfig.builder()

266

// Network mode

267

.networkMode("my-network") // or "bridge", "host", "none", "container:name"

268

269

// Port bindings

270

.portBindings(Map.of(

271

"80/tcp", List.of(

272

PortBinding.of("0.0.0.0", "8080"),

273

PortBinding.of("127.0.0.1", "8081")

274

),

275

"443/tcp", List.of(PortBinding.of("0.0.0.0", "8443"))

276

))

277

278

// Publish all exposed ports

279

.publishAllPorts(false)

280

281

// DNS configuration

282

.dns("8.8.8.8", "1.1.1.1")

283

.dnsOptions("timeout:3")

284

.dnsSearch("example.com", "internal.local")

285

286

// Extra hosts (/etc/hosts entries)

287

.extraHosts("host.docker.internal:host-gateway", "api.local:172.20.0.10")

288

289

// Legacy container links

290

.links("database:db", "redis:cache")

291

292

.build();

293

294

ContainerConfig config = ContainerConfig.builder()

295

.image("nginx:latest")

296

.hostConfig(hostConfig)

297

.build();

298

```

299

300

## Network Removal

301

302

### Removing Networks

303

304

```java { .api }

305

// Remove network by ID or name

306

docker.removeNetwork("network-id-or-name");

307

308

// Safe removal with error handling

309

public void safeRemoveNetwork(DockerClient docker, String networkId) {

310

try {

311

// First disconnect all containers

312

Network network = docker.inspectNetwork(networkId);

313

for (String containerId : network.containers().keySet()) {

314

try {

315

docker.disconnectFromNetwork(containerId, networkId);

316

System.out.println("Disconnected container: " + containerId);

317

} catch (DockerException e) {

318

System.err.println("Failed to disconnect container " + containerId + ": " + e.getMessage());

319

}

320

}

321

322

// Then remove the network

323

docker.removeNetwork(networkId);

324

System.out.println("Removed network: " + networkId);

325

326

} catch (DockerException e) {

327

System.err.println("Failed to remove network: " + e.getMessage());

328

}

329

}

330

```

331

332

## Network Filtering Parameters

333

334

### ListNetworksParam Options

335

336

```java { .api }

337

// Filter by network ID

338

ListNetworksParam.byNetworkId("network-id")

339

340

// Filter by network name

341

ListNetworksParam.byNetworkName("my-network")

342

343

// Filter by driver type

344

ListNetworksParam.withDriver("bridge")

345

ListNetworksParam.withDriver("overlay")

346

ListNetworksParam.withDriver("macvlan")

347

348

// Filter by network type

349

ListNetworksParam.withType(Network.Type.BUILTIN)

350

ListNetworksParam.withType(Network.Type.CUSTOM)

351

352

// Convenience filters

353

ListNetworksParam.builtInNetworks()

354

ListNetworksParam.customNetworks()

355

356

// Filter by labels

357

ListNetworksParam.withLabel("environment")

358

ListNetworksParam.withLabel("team", "backend")

359

360

// Custom filters

361

ListNetworksParam.filter("scope", "local")

362

ListNetworksParam.filter("type", "custom")

363

```

364

365

## Network Types and Drivers

366

367

### Bridge Networks

368

369

```java { .api }

370

// Default bridge network

371

NetworkConfig bridgeConfig = NetworkConfig.builder()

372

.name("custom-bridge")

373

.driver("bridge")

374

.options(Map.of(

375

"com.docker.network.bridge.name", "br-custom",

376

"com.docker.network.bridge.enable_icc", "true",

377

"com.docker.network.bridge.enable_ip_masquerade", "true",

378

"com.docker.network.bridge.host_binding_ipv4", "0.0.0.0",

379

"com.docker.network.driver.mtu", "1500"

380

))

381

.build();

382

```

383

384

### Overlay Networks

385

386

```java { .api }

387

// Overlay network for multi-host communication

388

NetworkConfig overlayConfig = NetworkConfig.builder()

389

.name("multi-host-overlay")

390

.driver("overlay")

391

.options(Map.of(

392

"encrypted", "true" // Enable overlay encryption

393

))

394

.labels(Map.of("purpose", "cross-host"))

395

.build();

396

```

397

398

### MACVLAN Networks

399

400

```java { .api }

401

// MACVLAN network for direct physical network access

402

NetworkConfig macvlanConfig = NetworkConfig.builder()

403

.name("macvlan-network")

404

.driver("macvlan")

405

.options(Map.of(

406

"parent", "eth0", // Parent interface

407

"macvlan_mode", "bridge"

408

))

409

.ipam(Ipam.builder()

410

.driver("default")

411

.config(IpamConfig.builder()

412

.subnet("192.168.1.0/24")

413

.gateway("192.168.1.1")

414

.build())

415

.build())

416

.build();

417

```

418

419

## Complete Network Management Example

420

421

```java { .api }

422

public class NetworkManagementExample {

423

424

public void demonstrateNetworkManagement(DockerClient docker)

425

throws DockerException, InterruptedException {

426

427

// 1. Create a custom network for a multi-tier application

428

System.out.println("Creating application network...");

429

430

IpamConfig ipamConfig = IpamConfig.builder()

431

.subnet("172.25.0.0/16")

432

.gateway("172.25.0.1")

433

.build();

434

435

NetworkConfig appNetworkConfig = NetworkConfig.builder()

436

.name("webapp-network")

437

.driver("bridge")

438

.ipam(Ipam.builder()

439

.driver("default")

440

.config(ipamConfig)

441

.build())

442

.labels(Map.of(

443

"project", "webapp",

444

"environment", "development"

445

))

446

.build();

447

448

NetworkCreation appNetwork = docker.createNetwork(appNetworkConfig);

449

String networkId = appNetwork.id();

450

System.out.println("Created network: " + networkId);

451

452

try {

453

// 2. Create containers for different tiers

454

455

// Database container

456

ContainerConfig dbConfig = ContainerConfig.builder()

457

.image("postgres:13")

458

.env("POSTGRES_DB=myapp", "POSTGRES_USER=user", "POSTGRES_PASSWORD=pass")

459

.exposedPorts("5432/tcp")

460

.build();

461

462

ContainerCreation dbContainer = docker.createContainer(dbConfig, "webapp-db");

463

464

// Connect database to network with specific IP

465

EndpointConfig dbEndpoint = EndpointConfig.builder()

466

.ipamConfig(EndpointIpamConfig.builder()

467

.ipv4Address("172.25.0.10")

468

.build())

469

.aliases("database", "db", "postgres")

470

.build();

471

472

docker.connectToNetwork(networkId, NetworkConnection.builder()

473

.containerId(dbContainer.id())

474

.endpointConfig(dbEndpoint)

475

.build());

476

477

// Web application container

478

ContainerConfig webConfig = ContainerConfig.builder()

479

.image("nginx:latest")

480

.exposedPorts("80/tcp")

481

.build();

482

483

ContainerCreation webContainer = docker.createContainer(webConfig, "webapp-web");

484

485

// Connect web server to network

486

EndpointConfig webEndpoint = EndpointConfig.builder()

487

.ipamConfig(EndpointIpamConfig.builder()

488

.ipv4Address("172.25.0.20")

489

.build())

490

.aliases("web", "frontend", "www")

491

.build();

492

493

docker.connectToNetwork(networkId, NetworkConnection.builder()

494

.containerId(webContainer.id())

495

.endpointConfig(webEndpoint)

496

.build());

497

498

// 3. Start containers

499

docker.startContainer(dbContainer.id());

500

docker.startContainer(webContainer.id());

501

502

System.out.println("Started database container: " + dbContainer.id());

503

System.out.println("Started web container: " + webContainer.id());

504

505

// 4. Inspect the network to see connected containers

506

Network network = docker.inspectNetwork(networkId);

507

System.out.println("Network inspection:");

508

System.out.println(" Name: " + network.name());

509

System.out.println(" Driver: " + network.driver());

510

System.out.println(" Subnet: " + network.ipam().config().get(0).subnet());

511

512

System.out.println("Connected containers:");

513

for (Map.Entry<String, AttachedNetwork> entry : network.containers().entrySet()) {

514

AttachedNetwork attached = entry.getValue();

515

System.out.println(" Container: " + attached.name());

516

System.out.println(" IP: " + attached.ipv4Address());

517

System.out.println(" Endpoint ID: " + attached.endpointId());

518

}

519

520

// 5. Test connectivity between containers

521

testContainerConnectivity(docker, webContainer.id(), "database", 5432);

522

523

// 6. Demonstrate network isolation

524

demonstrateNetworkIsolation(docker);

525

526

} finally {

527

// 7. Cleanup

528

cleanupNetworkDemo(docker, networkId);

529

}

530

}

531

532

private void testContainerConnectivity(DockerClient docker, String containerId,

533

String targetHost, int port)

534

throws DockerException, InterruptedException {

535

536

System.out.println("Testing connectivity from container to " + targetHost + ":" + port);

537

538

ExecCreation exec = docker.execCreate(containerId,

539

new String[]{"nc", "-z", "-v", targetHost, String.valueOf(port)},

540

DockerClient.ExecCreateParam.attachStdout(),

541

DockerClient.ExecCreateParam.attachStderr());

542

543

try (LogStream output = docker.execStart(exec.id())) {

544

String result = output.readFully();

545

System.out.println("Connectivity test result: " + result);

546

}

547

}

548

549

private void demonstrateNetworkIsolation(DockerClient docker)

550

throws DockerException, InterruptedException {

551

552

System.out.println("Demonstrating network isolation...");

553

554

// Create isolated network

555

NetworkConfig isolatedConfig = NetworkConfig.builder()

556

.name("isolated-network")

557

.driver("bridge")

558

.internal(true) // No external connectivity

559

.build();

560

561

NetworkCreation isolated = docker.createNetwork(isolatedConfig);

562

563

// Create container in isolated network

564

ContainerConfig config = ContainerConfig.builder()

565

.image("alpine:latest")

566

.cmd("sleep", "30")

567

.build();

568

569

ContainerCreation container = docker.createContainer(config);

570

docker.connectToNetwork(isolated.id(), container.id());

571

docker.startContainer(container.id());

572

573

// Test that container cannot reach external hosts

574

ExecCreation exec = docker.execCreate(container.id(),

575

new String[]{"ping", "-c", "1", "8.8.8.8"},

576

DockerClient.ExecCreateParam.attachStdout(),

577

DockerClient.ExecCreateParam.attachStderr());

578

579

try (LogStream output = docker.execStart(exec.id())) {

580

String result = output.readFully();

581

System.out.println("Isolation test (should fail): " + result);

582

}

583

584

// Cleanup isolated demo

585

docker.stopContainer(container.id(), 5);

586

docker.removeContainer(container.id());

587

docker.removeNetwork(isolated.id());

588

}

589

590

private void cleanupNetworkDemo(DockerClient docker, String networkId) {

591

try {

592

// Stop and remove containers

593

List<Container> containers = docker.listContainers(

594

DockerClient.ListContainersParam.allContainers());

595

596

for (Container container : containers) {

597

if (container.names().stream().anyMatch(name -> name.contains("webapp-"))) {

598

try {

599

docker.stopContainer(container.id(), 5);

600

docker.removeContainer(container.id());

601

System.out.println("Removed container: " + container.id());

602

} catch (DockerException e) {

603

System.err.println("Error removing container: " + e.getMessage());

604

}

605

}

606

}

607

608

// Remove network

609

docker.removeNetwork(networkId);

610

System.out.println("Removed network: " + networkId);

611

612

} catch (DockerException | InterruptedException e) {

613

System.err.println("Cleanup error: " + e.getMessage());

614

}

615

}

616

}

617

```

618

619

## Network Security and Best Practices

620

621

### Secure Network Configuration

622

623

```java { .api }

624

// Create secure production network

625

NetworkConfig secureConfig = NetworkConfig.builder()

626

.name("secure-production")

627

.driver("bridge")

628

.internal(false) // Allow external access only as needed

629

.options(Map.of(

630

// Disable inter-container communication by default

631

"com.docker.network.bridge.enable_icc", "false",

632

// Enable IP masquerading for outbound traffic

633

"com.docker.network.bridge.enable_ip_masquerade", "true"

634

))

635

.labels(Map.of(

636

"security.level", "high",

637

"environment", "production"

638

))

639

.build();

640

641

NetworkCreation secureNetwork = docker.createNetwork(secureConfig);

642

```

643

644

### Network Segmentation

645

646

```java { .api }

647

public void createNetworkSegmentation(DockerClient docker)

648

throws DockerException, InterruptedException {

649

650

// Frontend network (public-facing)

651

NetworkConfig frontendConfig = NetworkConfig.builder()

652

.name("frontend-network")

653

.driver("bridge")

654

.labels(Map.of("tier", "frontend", "access", "public"))

655

.build();

656

657

// Backend network (internal only)

658

NetworkConfig backendConfig = NetworkConfig.builder()

659

.name("backend-network")

660

.driver("bridge")

661

.internal(true) // No external access

662

.labels(Map.of("tier", "backend", "access", "internal"))

663

.build();

664

665

// Database network (highly restricted)

666

NetworkConfig dbConfig = NetworkConfig.builder()

667

.name("database-network")

668

.driver("bridge")

669

.internal(true)

670

.options(Map.of(

671

"com.docker.network.bridge.enable_icc", "false"

672

))

673

.labels(Map.of("tier", "database", "access", "restricted"))

674

.build();

675

676

docker.createNetwork(frontendConfig);

677

docker.createNetwork(backendConfig);

678

docker.createNetwork(dbConfig);

679

}

680

```

681

682

The network management system provides comprehensive control over container connectivity with support for custom addressing, service discovery, network isolation, and multi-host communication for scalable Docker deployments.