0
# Container Operations
1
2
This document covers the complete container lifecycle management including creation, configuration, execution, monitoring, and file operations.
3
4
## Container Lifecycle
5
6
### Listing Containers
7
8
```java { .api }
9
import com.spotify.docker.client.DockerClient;
10
import com.spotify.docker.client.messages.Container;
11
12
// List running containers (default)
13
List<Container> running = docker.listContainers();
14
15
// List all containers (including stopped)
16
List<Container> all = docker.listContainers(
17
ListContainersParam.allContainers()
18
);
19
20
// Filter by status
21
List<Container> exited = docker.listContainers(
22
ListContainersParam.withStatusExited()
23
);
24
25
// Filter by label
26
List<Container> labeled = docker.listContainers(
27
ListContainersParam.withLabel("env", "production")
28
);
29
30
// Combine parameters
31
List<Container> filtered = docker.listContainers(
32
ListContainersParam.allContainers(),
33
ListContainersParam.withLabel("app"),
34
ListContainersParam.limitContainers(10)
35
);
36
```
37
38
### Creating Containers
39
40
#### Basic Container Creation
41
42
```java { .api }
43
import com.spotify.docker.client.messages.*;
44
45
// Simple container
46
ContainerConfig config = ContainerConfig.builder()
47
.image("nginx:latest")
48
.build();
49
50
ContainerCreation creation = docker.createContainer(config);
51
String containerId = creation.id();
52
53
// Named container
54
ContainerCreation creation = docker.createContainer(config, "my-web-server");
55
```
56
57
#### Advanced Container Configuration
58
59
```java { .api }
60
ContainerConfig config = ContainerConfig.builder()
61
.image("nginx:latest")
62
.hostname("web-server")
63
.domainname("example.com")
64
.user("www-data")
65
.attachStdin(false)
66
.attachStdout(true)
67
.attachStderr(true)
68
.tty(true)
69
.openStdin(false)
70
.stdinOnce(false)
71
.env("NGINX_PORT=8080", "ENV=production")
72
.cmd("nginx", "-g", "daemon off;")
73
.entrypoint("/entrypoint.sh")
74
.exposedPorts("80/tcp", "443/tcp")
75
.volumes("/var/log/nginx", "/etc/nginx/conf.d")
76
.workingDir("/usr/share/nginx/html")
77
.labels(Map.of(
78
"app", "nginx",
79
"version", "1.0",
80
"env", "production"
81
))
82
.macAddress("02:42:ac:11:00:02")
83
.networkDisabled(false)
84
.stopSignal("SIGTERM")
85
.stopTimeout(30)
86
.build();
87
88
ContainerCreation creation = docker.createContainer(config);
89
```
90
91
### Host Configuration
92
93
```java { .api }
94
import com.spotify.docker.client.messages.*;
95
96
HostConfig hostConfig = HostConfig.builder()
97
// Resource limits
98
.memory(512L * 1024 * 1024) // 512MB
99
.memorySwap(1024L * 1024 * 1024) // 1GB total (512MB + 512MB swap)
100
.memoryReservation(256L * 1024 * 1024) // 256MB soft limit
101
.cpuShares(512) // CPU weight
102
.cpuQuota(50000L) // 50% of CPU
103
.cpuPeriod(100000L) // CPU period
104
.cpusetCpus("0-1") // Use cores 0 and 1
105
106
// Port bindings
107
.portBindings(Map.of(
108
"80/tcp", List.of(PortBinding.of("0.0.0.0", "8080")),
109
"443/tcp", List.of(PortBinding.of("0.0.0.0", "8443"))
110
))
111
.publishAllPorts(false)
112
113
// Volume mounts
114
.binds("/host/path:/container/path:ro",
115
"/logs:/var/log/nginx:rw")
116
.volumesFrom("data-container")
117
118
// Network configuration
119
.networkMode("bridge")
120
.links("database:db", "cache:redis")
121
.dns("8.8.8.8", "1.1.1.1")
122
.dnsSearch("example.com")
123
.extraHosts("host.docker.internal:host-gateway")
124
125
// Security
126
.privileged(false)
127
.readonlyRootfs(false)
128
.capAdd("NET_ADMIN")
129
.capDrop("MKNOD")
130
.securityOpt("no-new-privileges:true")
131
132
// Restart policy
133
.restartPolicy(RestartPolicy.builder()
134
.name("unless-stopped")
135
.maximumRetryCount(0)
136
.build())
137
138
// Devices
139
.devices(Device.builder()
140
.pathOnHost("/dev/sda")
141
.pathInContainer("/dev/xvda")
142
.cgroupPermissions("rwm")
143
.build())
144
145
// Resource constraints
146
.ulimits(Ulimit.builder()
147
.name("nofile")
148
.soft(1024L)
149
.hard(2048L)
150
.build())
151
152
.build();
153
154
ContainerConfig config = ContainerConfig.builder()
155
.image("nginx:latest")
156
.hostConfig(hostConfig)
157
.build();
158
```
159
160
### Starting and Stopping Containers
161
162
```java { .api }
163
// Start container
164
docker.startContainer(containerId);
165
166
// Stop container (with timeout)
167
docker.stopContainer(containerId, 10); // Wait 10 seconds before SIGKILL
168
169
// Restart container
170
docker.restartContainer(containerId);
171
172
// Kill container
173
docker.killContainer(containerId);
174
175
// Kill with specific signal
176
docker.killContainer(containerId, DockerClient.Signal.SIGTERM);
177
178
// Pause container
179
docker.pauseContainer(containerId);
180
181
// Unpause container
182
docker.unpauseContainer(containerId);
183
```
184
185
## Container Inspection and Monitoring
186
187
### Container Information
188
189
```java { .api }
190
// Get detailed container information
191
ContainerInfo info = docker.inspectContainer(containerId);
192
193
System.out.println("Container ID: " + info.id());
194
System.out.println("Name: " + info.name());
195
System.out.println("Image: " + info.image());
196
System.out.println("State: " + info.state().running());
197
System.out.println("Exit Code: " + info.state().exitCode());
198
System.out.println("Started At: " + info.state().startedAt());
199
System.out.println("Finished At: " + info.state().finishedAt());
200
201
// Network settings
202
NetworkSettings network = info.networkSettings();
203
System.out.println("IP Address: " + network.ipAddress());
204
System.out.println("Gateway: " + network.gateway());
205
206
// Mounts
207
for (ContainerMount mount : info.mounts()) {
208
System.out.println("Mount: " + mount.source() + " -> " + mount.destination());
209
}
210
```
211
212
### Container Statistics
213
214
```java { .api }
215
// Get real-time container statistics
216
ContainerStats stats = docker.stats(containerId);
217
218
// CPU statistics
219
CpuStats cpuStats = stats.cpuStats();
220
System.out.println("CPU Usage: " + cpuStats.cpuUsage().totalUsage());
221
System.out.println("System CPU Usage: " + cpuStats.systemCpuUsage());
222
223
// Memory statistics
224
MemoryStats memStats = stats.memoryStats();
225
System.out.println("Memory Usage: " + memStats.usage());
226
System.out.println("Memory Limit: " + memStats.limit());
227
System.out.println("Max Usage: " + memStats.maxUsage());
228
229
// Network statistics
230
Map<String, NetworkStats> networks = stats.networks();
231
for (Map.Entry<String, NetworkStats> entry : networks.entrySet()) {
232
NetworkStats netStats = entry.getValue();
233
System.out.println("Network " + entry.getKey() + ":");
234
System.out.println(" RX Bytes: " + netStats.rxBytes());
235
System.out.println(" TX Bytes: " + netStats.txBytes());
236
}
237
238
// Block I/O statistics
239
BlockIoStats ioStats = stats.blockIoStats();
240
System.out.println("Block I/O Read: " + ioStats.ioServiceBytesRecursive());
241
```
242
243
### Process Information
244
245
```java { .api }
246
// List processes running in container
247
TopResults top = docker.topContainer(containerId);
248
249
System.out.println("Process Titles: " + top.titles());
250
for (List<String> process : top.processes()) {
251
System.out.println("Process: " + process);
252
}
253
254
// With custom ps arguments
255
TopResults topWithArgs = docker.topContainer(containerId, "aux");
256
```
257
258
### Container Changes
259
260
```java { .api }
261
// Inspect filesystem changes
262
List<ContainerChange> changes = docker.inspectContainerChanges(containerId);
263
264
for (ContainerChange change : changes) {
265
System.out.println("Path: " + change.path());
266
System.out.println("Kind: " + change.kind()); // 0=Modified, 1=Added, 2=Deleted
267
}
268
```
269
270
## Container Logs
271
272
### Reading Logs
273
274
```java { .api }
275
// Get all logs
276
try (LogStream logs = docker.logs(containerId,
277
LogsParam.stdout(),
278
LogsParam.stderr())) {
279
280
String logContent = logs.readFully();
281
System.out.println(logContent);
282
}
283
284
// Stream logs with parameters
285
try (LogStream logs = docker.logs(containerId,
286
LogsParam.follow(), // Follow log stream
287
LogsParam.stdout(true), // Include stdout
288
LogsParam.stderr(true), // Include stderr
289
LogsParam.since(1234567890), // Since timestamp
290
LogsParam.tail(100), // Last 100 lines
291
LogsParam.timestamps(true))) { // Include timestamps
292
293
String logLine;
294
while ((logLine = logs.readFully()) != null) {
295
System.out.println(logLine);
296
}
297
}
298
```
299
300
### Processing Log Messages
301
302
```java { .api }
303
try (LogStream logs = docker.logs(containerId,
304
LogsParam.stdout(), LogsParam.stderr(), LogsParam.follow())) {
305
306
logs.forEachRemaining(logMessage -> {
307
String content = logMessage.content().toStringUtf8();
308
LogMessage.Stream stream = logMessage.stream();
309
310
switch (stream) {
311
case STDOUT:
312
System.out.println("STDOUT: " + content);
313
break;
314
case STDERR:
315
System.err.println("STDERR: " + content);
316
break;
317
case STDIN:
318
System.out.println("STDIN: " + content);
319
break;
320
}
321
});
322
}
323
```
324
325
## Container Execution
326
327
### Exec Commands
328
329
```java { .api }
330
// Create exec instance
331
ExecCreation exec = docker.execCreate(containerId,
332
new String[]{"bash", "-c", "echo 'Hello World'"},
333
ExecCreateParam.attachStdout(),
334
ExecCreateParam.attachStderr());
335
336
// Start execution and get output
337
try (LogStream execOutput = docker.execStart(exec.id())) {
338
String output = execOutput.readFully();
339
System.out.println("Output: " + output);
340
}
341
342
// Inspect exec state
343
ExecState execState = docker.execInspect(exec.id());
344
System.out.println("Exit Code: " + execState.exitCode());
345
System.out.println("Running: " + execState.running());
346
```
347
348
### Interactive Exec
349
350
```java { .api }
351
// Interactive exec with TTY
352
ExecCreation exec = docker.execCreate(containerId,
353
new String[]{"bash"},
354
ExecCreateParam.attachStdin(),
355
ExecCreateParam.attachStdout(),
356
ExecCreateParam.attachStderr(),
357
ExecCreateParam.tty());
358
359
try (LogStream execStream = docker.execStart(exec.id(),
360
ExecStartParameter.TTY)) {
361
362
// Handle interactive session
363
// Note: Interactive sessions require special handling
364
// for stdin/stdout/stderr multiplexing
365
}
366
```
367
368
### Exec with User and Working Directory
369
370
```java { .api }
371
ExecCreation exec = docker.execCreate(containerId,
372
new String[]{"whoami"},
373
ExecCreateParam.attachStdout(),
374
ExecCreateParam.user("nginx"),
375
ExecCreateParam.workingDir("/var/www"));
376
377
try (LogStream output = docker.execStart(exec.id())) {
378
System.out.println("User: " + output.readFully());
379
}
380
```
381
382
## File Operations
383
384
### Copying Files to Container
385
386
```java { .api }
387
import java.nio.file.*;
388
389
// Copy single file
390
Path sourceFile = Paths.get("/local/file.txt");
391
docker.copyToContainer(sourceFile, containerId, "/container/path/");
392
393
// Copy directory
394
Path sourceDir = Paths.get("/local/directory");
395
docker.copyToContainer(sourceDir, containerId, "/container/path/");
396
397
// Copy from InputStream
398
try (InputStream input = new FileInputStream("/local/file.txt")) {
399
docker.copyToContainer(input, containerId, "/container/path/file.txt");
400
}
401
```
402
403
### Copying Files from Container
404
405
```java { .api }
406
// Archive files from container
407
try (InputStream archive = docker.archiveContainer(containerId, "/path/in/container")) {
408
// Process tar archive
409
try (TarArchiveInputStream tarStream = new TarArchiveInputStream(archive)) {
410
TarArchiveEntry entry;
411
while ((entry = tarStream.getNextTarEntry()) != null) {
412
System.out.println("File: " + entry.getName());
413
System.out.println("Size: " + entry.getSize());
414
415
if (!entry.isDirectory()) {
416
// Read file content
417
byte[] content = new byte[(int) entry.getSize()];
418
tarStream.read(content);
419
// Process content
420
}
421
}
422
}
423
}
424
```
425
426
## Container Attachment
427
428
### Attaching to Running Container
429
430
```java { .api }
431
// Attach to container
432
try (LogStream stream = docker.attachContainer(containerId,
433
AttachParameter.LOGS,
434
AttachParameter.STREAM,
435
AttachParameter.STDIN,
436
AttachParameter.STDOUT,
437
AttachParameter.STDERR)) {
438
439
// Read attached stream
440
stream.forEachRemaining(logMessage -> {
441
System.out.println(logMessage.content().toStringUtf8());
442
});
443
}
444
```
445
446
### TTY Resize
447
448
```java { .api }
449
// Resize container TTY
450
docker.resizeTty(containerId, 80, 24); // width=80, height=24
451
452
// Resize exec TTY
453
docker.execResizeTty(execId, 120, 30);
454
```
455
456
## Container Management
457
458
### Waiting for Container
459
460
```java { .api }
461
// Wait for container to exit
462
ContainerExit exit = docker.waitContainer(containerId);
463
System.out.println("Exit status: " + exit.statusCode());
464
```
465
466
### Renaming Containers
467
468
```java { .api }
469
// Rename container
470
docker.renameContainer(containerId, "new-container-name");
471
```
472
473
### Updating Container Configuration
474
475
```java { .api }
476
// Update container resources
477
HostConfig newConfig = HostConfig.builder()
478
.memory(1024L * 1024 * 1024) // 1GB
479
.cpuShares(1024)
480
.build();
481
482
ContainerUpdate update = docker.updateContainer(containerId, newConfig);
483
System.out.println("Warnings: " + update.warnings());
484
```
485
486
### Removing Containers
487
488
```java { .api }
489
// Remove stopped container
490
docker.removeContainer(containerId);
491
492
// Force remove running container
493
docker.removeContainer(containerId,
494
RemoveContainerParam.forceKill());
495
496
// Remove container and its volumes
497
docker.removeContainer(containerId,
498
RemoveContainerParam.removeVolumes());
499
500
// Remove with multiple options
501
docker.removeContainer(containerId,
502
RemoveContainerParam.forceKill(),
503
RemoveContainerParam.removeVolumes());
504
```
505
506
## Container Export and Import
507
508
### Exporting Containers
509
510
```java { .api }
511
// Export container as tarball
512
try (InputStream export = docker.exportContainer(containerId)) {
513
// Save to file
514
Files.copy(export, Paths.get("/path/to/export.tar"));
515
}
516
517
// Process exported tarball
518
try (InputStream export = docker.exportContainer(containerId);
519
TarArchiveInputStream tarStream = new TarArchiveInputStream(export)) {
520
521
TarArchiveEntry entry;
522
while ((entry = tarStream.getNextTarEntry()) != null) {
523
System.out.println("Entry: " + entry.getName());
524
}
525
}
526
```
527
528
## Container Filtering
529
530
### ListContainersParam Options
531
532
```java { .api }
533
// Status filters
534
ListContainersParam.withStatusCreated()
535
ListContainersParam.withStatusRestarting()
536
ListContainersParam.withStatusRunning()
537
ListContainersParam.withStatusPaused()
538
ListContainersParam.withStatusExited()
539
540
// Label filters
541
ListContainersParam.withLabel("key")
542
ListContainersParam.withLabel("key", "value")
543
544
// Other filters
545
ListContainersParam.allContainers(true)
546
ListContainersParam.limitContainers(10)
547
ListContainersParam.withContainerSizes(true)
548
ListContainersParam.containersCreatedSince("container-id")
549
ListContainersParam.containersCreatedBefore("container-id")
550
ListContainersParam.withExitStatus(0)
551
552
// Custom filters
553
ListContainersParam.filter("ancestor", "nginx")
554
ListContainersParam.filter("expose", "80")
555
ListContainersParam.filter("volume", "/data")
556
```
557
558
## Complete Container Lifecycle Example
559
560
```java { .api }
561
public class ContainerLifecycleExample {
562
563
public void demonstrateLifecycle(DockerClient docker)
564
throws DockerException, InterruptedException {
565
566
// 1. Create container configuration
567
HostConfig hostConfig = HostConfig.builder()
568
.memory(512L * 1024 * 1024)
569
.portBindings(Map.of("80/tcp",
570
List.of(PortBinding.of("0.0.0.0", "8080"))))
571
.build();
572
573
ContainerConfig config = ContainerConfig.builder()
574
.image("nginx:latest")
575
.env("NGINX_PORT=80")
576
.exposedPorts("80/tcp")
577
.hostConfig(hostConfig)
578
.labels(Map.of("app", "demo", "env", "test"))
579
.build();
580
581
// 2. Create container
582
ContainerCreation creation = docker.createContainer(config, "demo-nginx");
583
String containerId = creation.id();
584
System.out.println("Created container: " + containerId);
585
586
try {
587
// 3. Start container
588
docker.startContainer(containerId);
589
System.out.println("Started container");
590
591
// 4. Wait for startup
592
Thread.sleep(2000);
593
594
// 5. Check container status
595
ContainerInfo info = docker.inspectContainer(containerId);
596
System.out.println("Container running: " + info.state().running());
597
598
// 6. Execute command
599
ExecCreation exec = docker.execCreate(containerId,
600
new String[]{"nginx", "-v"},
601
ExecCreateParam.attachStdout());
602
603
try (LogStream output = docker.execStart(exec.id())) {
604
System.out.println("Nginx version: " + output.readFully());
605
}
606
607
// 7. Get logs
608
try (LogStream logs = docker.logs(containerId,
609
LogsParam.stdout(), LogsParam.tail(10))) {
610
System.out.println("Container logs:\n" + logs.readFully());
611
}
612
613
// 8. Get statistics
614
ContainerStats stats = docker.stats(containerId);
615
System.out.println("Memory usage: " + stats.memoryStats().usage());
616
617
} finally {
618
// 9. Stop and remove container
619
try {
620
docker.stopContainer(containerId, 5);
621
System.out.println("Stopped container");
622
} catch (Exception e) {
623
System.err.println("Error stopping container: " + e.getMessage());
624
}
625
626
try {
627
docker.removeContainer(containerId);
628
System.out.println("Removed container");
629
} catch (Exception e) {
630
System.err.println("Error removing container: " + e.getMessage());
631
}
632
}
633
}
634
}
635
```
636
637
This comprehensive container management system provides full lifecycle control with extensive configuration options, monitoring capabilities, and file operation support for production Docker deployments.