0
# Images and Files
1
2
Docker image name parsing and manipulation capabilities, along with file mounting utilities for transferring files between host and containers, and image building from Dockerfiles.
3
4
## Capabilities
5
6
### Docker Image Name Handling
7
8
Comprehensive Docker image name parsing, validation, and manipulation with support for registries, repositories, tags, and digests.
9
10
```java { .api }
11
/**
12
* Immutable representation of Docker image names with parsing and manipulation
13
*/
14
public final class DockerImageName {
15
16
/** Parse a Docker image name string into structured representation */
17
public static DockerImageName parse(String fullImageName);
18
19
/** Create image name with registry, repository and tag */
20
public static DockerImageName of(String registry, String repository, String tag);
21
22
/** Create image name from repository and tag */
23
public static DockerImageName of(String repository, String tag);
24
25
/** Modify image name with new tag */
26
public DockerImageName withTag(String tagName);
27
28
/** Modify image name with new registry */
29
public DockerImageName withRegistry(String registryUrl);
30
31
/** Declare this image as compatible substitute for another */
32
public DockerImageName asCompatibleSubstituteFor(String otherImageName);
33
public DockerImageName asCompatibleSubstituteFor(DockerImageName otherImageName);
34
35
/** Get canonical string representation */
36
public String asCanonicalNameString();
37
38
/** Get unversioned canonical name (without tag/digest) */
39
public String getUnversionedPart();
40
41
/** Get repository name */
42
public String getRepository();
43
44
/** Get registry (null if using Docker Hub) */
45
public String getRegistry();
46
47
/** Get tag or digest */
48
public String getVersionPart();
49
50
/** Check if image uses specific registry */
51
public boolean isCompatibleWith(DockerImageName other);
52
53
/** Assert compatibility with other image names */
54
public void assertCompatibleWith(DockerImageName... anyOfThese);
55
56
/** Validate image name format */
57
public void assertValid();
58
59
/** Convert to string representation */
60
@Override
61
public String toString();
62
}
63
```
64
65
**Usage Examples:**
66
67
```java
68
import org.testcontainers.utility.DockerImageName;
69
70
// Parse various image name formats
71
DockerImageName nginx = DockerImageName.parse("nginx:alpine");
72
DockerImageName postgres = DockerImageName.parse("postgres");
73
DockerImageName customImage = DockerImageName.parse("myregistry.com/myorg/myapp:v1.2.3");
74
75
// Manipulate image names
76
DockerImageName nginxLatest = nginx.withTag("latest");
77
DockerImageName privateNginx = nginx.withRegistry("private-registry.company.com");
78
79
// Image compatibility declarations
80
DockerImageName customPostgres = DockerImageName.parse("my-postgres:latest")
81
.asCompatibleSubstituteFor("postgres");
82
83
// Using with containers
84
GenericContainer<?> container = new GenericContainer<>(
85
DockerImageName.parse("postgres:13")
86
.asCompatibleSubstituteFor("postgres")
87
);
88
```
89
90
### File Mounting and Transfer
91
92
Utilities for mounting host files and directories into containers, and transferring files between host and containers.
93
94
```java { .api }
95
/**
96
* Represents a file that can be mounted into a container
97
*/
98
public class MountableFile implements Transferable {
99
100
/** Create from host filesystem path */
101
public static MountableFile forHostPath(String path);
102
public static MountableFile forHostPath(Path path);
103
public static MountableFile forHostPath(String path, Integer mode);
104
public static MountableFile forHostPath(Path path, Integer mode);
105
106
/** Create from classpath resource */
107
public static MountableFile forClasspathResource(String resourcePath);
108
public static MountableFile forClasspathResource(String resourcePath, Integer mode);
109
110
/** Get resolved filesystem path */
111
public String getResolvedPath();
112
113
/** Get filesystem path for mounting */
114
public String getFilesystemPath();
115
116
/** Get file permissions mode */
117
public int getFileMode();
118
119
/** Transfer content to destination */
120
@Override
121
public void transferTo(Transferable.TransferableContainer destination, String destinationPath);
122
123
/**
124
* Interface for content that can be transferred to containers
125
*/
126
public interface Transferable {
127
void transferTo(TransferableContainer destination, String destinationPath);
128
129
interface TransferableContainer {
130
void copyFileToContainer(Transferable transferable, String containerPath);
131
}
132
}
133
}
134
```
135
136
**Usage Examples:**
137
138
```java
139
import org.testcontainers.utility.MountableFile;
140
141
// Mount host files and directories
142
GenericContainer<?> container = new GenericContainer<>("myapp:latest")
143
// Mount configuration file from host
144
.withFileSystemBind("/host/path/config.yml", "/app/config.yml", BindMode.READ_ONLY)
145
146
// Copy file from classpath to container
147
.withCopyFileToContainer(
148
MountableFile.forClasspathResource("application.properties"),
149
"/app/application.properties"
150
)
151
152
// Mount executable script with permissions
153
.withCopyFileToContainer(
154
MountableFile.forClasspathResource("startup.sh", 0755),
155
"/app/startup.sh"
156
);
157
158
// Runtime file operations
159
container.start();
160
container.copyFileToContainer(
161
MountableFile.forHostPath("/local/data.txt"),
162
"/app/data.txt"
163
);
164
```
165
166
### Image Pull Policies
167
168
Configurable policies for when to pull Docker images, providing control over image freshness and network usage.
169
170
```java { .api }
171
/**
172
* Factory for image pull policies
173
*/
174
public class PullPolicy {
175
176
/** Default pull policy - pull if image not present locally */
177
public static ImagePullPolicy defaultPolicy();
178
179
/** Always pull latest version of image */
180
public static ImagePullPolicy alwaysPull();
181
182
/** Never pull images - use only local images */
183
public static ImagePullPolicy neverPull();
184
185
/** Pull images older than specified duration */
186
public static ImagePullPolicy ageBased(Duration maxAge);
187
}
188
189
/**
190
* Interface for image pull policy implementations
191
*/
192
public interface ImagePullPolicy {
193
194
/** Determine if image should be pulled */
195
boolean shouldPull(DockerImageName imageName);
196
}
197
```
198
199
**Usage Examples:**
200
201
```java
202
import org.testcontainers.images.PullPolicy;
203
204
// Configure pull policy on containers
205
GenericContainer<?> container = new GenericContainer<>("nginx:latest")
206
.withImagePullPolicy(PullPolicy.alwaysPull());
207
208
// Age-based pulling for CI environments
209
GenericContainer<?> dbContainer = new GenericContainer<>("postgres:13")
210
.withImagePullPolicy(PullPolicy.ageBased(Duration.ofHours(24)));
211
212
// Never pull in offline environments
213
GenericContainer<?> localContainer = new GenericContainer<>("local-image:latest")
214
.withImagePullPolicy(PullPolicy.neverPull());
215
```
216
217
### Image Building
218
219
Build Docker images from Dockerfiles and directory contexts for use in tests.
220
221
```java { .api }
222
/**
223
* Build Docker images from Dockerfiles for use in containers
224
*/
225
public class ImageFromDockerfile extends LazyFuture<String> implements DockerImageName {
226
227
/** Create builder from Dockerfile in classpath */
228
public ImageFromDockerfile();
229
public ImageFromDockerfile(String dockerImageName);
230
public ImageFromDockerfile(String dockerImageName, boolean deleteOnExit);
231
232
/** Add Dockerfile content directly */
233
public ImageFromDockerfile withDockerfile(Path dockerfile);
234
public ImageFromDockerfile withDockerfileContent(String dockerfileContent);
235
236
/** Add files to build context */
237
public ImageFromDockerfile withFileFromPath(String containerPath, Path filePath);
238
public ImageFromDockerfile withFileFromString(String containerPath, String fileContent);
239
public ImageFromDockerfile withFileFromClasspath(String containerPath, String classpathResource);
240
public ImageFromDockerfile withFileFromTransfer(String containerPath, Transferable transferable);
241
242
/** Configure build context */
243
public ImageFromDockerfile withBuildContext(Path buildContext);
244
245
/** Configure build arguments */
246
public ImageFromDockerfile withBuildArg(String key, String value);
247
public ImageFromDockerfile withBuildArgs(Map<String, String> args);
248
249
/** Get image name after building */
250
@Override
251
public String asCanonicalNameString();
252
253
/** Force image build */
254
public String getImageId();
255
}
256
```
257
258
**Usage Examples:**
259
260
```java
261
import org.testcontainers.images.builder.ImageFromDockerfile;
262
263
// Build from inline Dockerfile
264
ImageFromDockerfile customImage = new ImageFromDockerfile()
265
.withDockerfileContent("""
266
FROM openjdk:11-jre-slim
267
COPY app.jar /app.jar
268
EXPOSE 8080
269
CMD ["java", "-jar", "/app.jar"]
270
""")
271
.withFileFromClasspath("app.jar", "target/myapp.jar");
272
273
GenericContainer<?> container = new GenericContainer<>(customImage)
274
.withExposedPorts(8080);
275
276
// Build from external Dockerfile
277
ImageFromDockerfile webApp = new ImageFromDockerfile()
278
.withDockerfile(Paths.get("docker/Dockerfile"))
279
.withFileFromPath("config.yml", Paths.get("src/main/resources/config.yml"))
280
.withBuildArg("VERSION", "1.0.0");
281
282
// Build with full context directory
283
ImageFromDockerfile complexApp = new ImageFromDockerfile()
284
.withBuildContext(Paths.get("./"))
285
.withDockerfile(Paths.get("Dockerfile"))
286
.withBuildArgs(Map.of(
287
"BUILD_VERSION", "1.2.3",
288
"ENVIRONMENT", "test"
289
));
290
```
291
292
### Dockerfile Builder
293
294
Programmatically create Dockerfiles using a fluent API.
295
296
```java { .api }
297
/**
298
* Fluent API for building Dockerfile content programmatically
299
*/
300
public class DockerfileBuilder {
301
302
public DockerfileBuilder();
303
304
/** Add FROM instruction */
305
public DockerfileBuilder from(String baseImage);
306
307
/** Add RUN instruction */
308
public DockerfileBuilder run(String command);
309
310
/** Add COPY instruction */
311
public DockerfileBuilder copy(String source, String destination);
312
313
/** Add ADD instruction */
314
public DockerfileBuilder add(String source, String destination);
315
316
/** Add ENV instruction */
317
public DockerfileBuilder env(String key, String value);
318
319
/** Add EXPOSE instruction */
320
public DockerfileBuilder expose(int... ports);
321
322
/** Add WORKDIR instruction */
323
public DockerfileBuilder workDir(String path);
324
325
/** Add USER instruction */
326
public DockerfileBuilder user(String user);
327
328
/** Add VOLUME instruction */
329
public DockerfileBuilder volume(String... paths);
330
331
/** Add CMD instruction */
332
public DockerfileBuilder cmd(String... command);
333
334
/** Add ENTRYPOINT instruction */
335
public DockerfileBuilder entryPoint(String... entrypoint);
336
337
/** Add LABEL instruction */
338
public DockerfileBuilder label(String key, String value);
339
340
/** Add ARG instruction */
341
public DockerfileBuilder arg(String name);
342
public DockerfileBuilder arg(String name, String defaultValue);
343
344
/** Build final Dockerfile content */
345
public String build();
346
}
347
```
348
349
**Usage Examples:**
350
351
```java
352
import org.testcontainers.images.builder.dockerfile.DockerfileBuilder;
353
354
// Programmatically build Dockerfile
355
String dockerfileContent = new DockerfileBuilder()
356
.from("openjdk:11-jre-slim")
357
.arg("VERSION", "latest")
358
.env("JAVA_OPTS", "-Xmx512m")
359
.workDir("/app")
360
.copy("app.jar", "app.jar")
361
.expose(8080, 8081)
362
.cmd("java", "$JAVA_OPTS", "-jar", "app.jar")
363
.build();
364
365
ImageFromDockerfile image = new ImageFromDockerfile()
366
.withDockerfileContent(dockerfileContent)
367
.withFileFromClasspath("app.jar", "target/myapp.jar")
368
.withBuildArg("VERSION", "1.0.0");
369
```
370
371
## Advanced File and Image Patterns
372
373
### Multi-Stage Builds
374
375
```java
376
String multiStageDockerfile = """
377
FROM maven:3.8-openjdk-11 AS builder
378
WORKDIR /app
379
COPY pom.xml .
380
COPY src ./src
381
RUN mvn clean package -DskipTests
382
383
FROM openjdk:11-jre-slim
384
WORKDIR /app
385
COPY --from=builder /app/target/app.jar app.jar
386
EXPOSE 8080
387
CMD ["java", "-jar", "app.jar"]
388
""";
389
390
ImageFromDockerfile multiStageImage = new ImageFromDockerfile()
391
.withDockerfileContent(multiStageDockerfile)
392
.withFileFromClasspath("pom.xml", "pom.xml")
393
.withFileFromPath("src", Paths.get("src"));
394
```
395
396
### Dynamic File Generation
397
398
```java
399
// Generate configuration files dynamically
400
String configContent = generateTestConfiguration();
401
402
ImageFromDockerfile dynamicImage = new ImageFromDockerfile()
403
.withDockerfileContent("""
404
FROM nginx:alpine
405
COPY nginx.conf /etc/nginx/nginx.conf
406
COPY static/ /usr/share/nginx/html/
407
""")
408
.withFileFromString("nginx.conf", configContent)
409
.withFileFromPath("static", Paths.get("src/test/resources/web"));
410
```
411
412
### Build Context Management
413
414
```java
415
// Exclude files from build context
416
ImageFromDockerfile optimizedImage = new ImageFromDockerfile()
417
.withBuildContext(Paths.get("./"))
418
.withDockerfile(Paths.get("Dockerfile"))
419
// Only include specific files to reduce build context size
420
.withFileFromPath("app.jar", Paths.get("target/app.jar"))
421
.withFileFromPath("config/", Paths.get("config/"));
422
```