Skip to content

Commit 66bcd39

Browse files
Adds the ability to set a target build stage to a Dockerfile (#4810)
Co-authored-by: Eddú Meléndez <[email protected]>
1 parent 13e4293 commit 66bcd39

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

core/src/main/java/org/testcontainers/images/builder/ImageFromDockerfile.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ public class ImageFromDockerfile
6060

6161
private Optional<Path> dockerfile = Optional.empty();
6262

63+
private Optional<String> target = Optional.empty();
64+
6365
private Set<String> dependencyImageNames = Collections.emptySet();
6466

6567
public ImageFromDockerfile() {
@@ -177,6 +179,7 @@ protected void configure(BuildImageCmd buildImageCmd) {
177179
});
178180

179181
this.buildArgs.forEach(buildImageCmd::withBuildArg);
182+
this.target.ifPresent(buildImageCmd::withTarget);
180183
}
181184

182185
private void prePullDependencyImages(Set<String> imagesToPull) {
@@ -211,6 +214,16 @@ public ImageFromDockerfile withBuildArgs(final Map<String, String> args) {
211214
return this;
212215
}
213216

217+
/**
218+
* Sets the target build stage to use.
219+
*
220+
* @param target the target build stage
221+
*/
222+
public ImageFromDockerfile withTarget(String target) {
223+
this.target = Optional.of(target);
224+
return this;
225+
}
226+
214227
/**
215228
* Sets the Dockerfile to be used for this image.
216229
*
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.testcontainers.containers;
2+
3+
import org.junit.Test;
4+
import org.testcontainers.images.builder.ImageFromDockerfile;
5+
6+
import java.io.IOException;
7+
import java.nio.file.Paths;
8+
9+
import static org.assertj.core.api.Assertions.assertThat;
10+
11+
public class MultiStageBuildTest {
12+
13+
@Test
14+
public void testDockerMultistageBuild() throws IOException, InterruptedException {
15+
try (
16+
GenericContainer<?> container = new GenericContainer<>(
17+
new ImageFromDockerfile()
18+
.withDockerfile(Paths.get("src/test/resources/Dockerfile-multistage"))
19+
.withTarget("builder")
20+
)
21+
.withCommand("/bin/sh", "-c", "sleep 10")
22+
) {
23+
container.start();
24+
assertThat(container.execInContainer("pwd").getStdout()).contains("/my-files");
25+
assertThat(container.execInContainer("ls").getStdout()).contains("hello.txt");
26+
}
27+
}
28+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
FROM alpine:3.14 AS builder
2+
3+
WORKDIR /my-files
4+
5+
RUN echo 'Hello World' > hello.txt
6+
7+
FROM alpine:3.14
8+
9+
COPY --from=builder /my-files/hello.txt hello.txt

0 commit comments

Comments
 (0)