Skip to content

Commit

Permalink
Adds the ability to set a target build stage to a Dockerfile (#4810)
Browse files Browse the repository at this point in the history
Co-authored-by: Eddú Meléndez <eddu.melendez@gmail.com>
  • Loading branch information
GenghisChen and eddumelendez committed Nov 8, 2022
1 parent 13e4293 commit 66bcd39
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
Expand Up @@ -60,6 +60,8 @@ public class ImageFromDockerfile

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

private Optional<String> target = Optional.empty();

private Set<String> dependencyImageNames = Collections.emptySet();

public ImageFromDockerfile() {
Expand Down Expand Up @@ -177,6 +179,7 @@ protected void configure(BuildImageCmd buildImageCmd) {
});

this.buildArgs.forEach(buildImageCmd::withBuildArg);
this.target.ifPresent(buildImageCmd::withTarget);
}

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

/**
* Sets the target build stage to use.
*
* @param target the target build stage
*/
public ImageFromDockerfile withTarget(String target) {
this.target = Optional.of(target);
return this;
}

/**
* Sets the Dockerfile to be used for this image.
*
Expand Down
@@ -0,0 +1,28 @@
package org.testcontainers.containers;

import org.junit.Test;
import org.testcontainers.images.builder.ImageFromDockerfile;

import java.io.IOException;
import java.nio.file.Paths;

import static org.assertj.core.api.Assertions.assertThat;

public class MultiStageBuildTest {

@Test
public void testDockerMultistageBuild() throws IOException, InterruptedException {
try (
GenericContainer<?> container = new GenericContainer<>(
new ImageFromDockerfile()
.withDockerfile(Paths.get("src/test/resources/Dockerfile-multistage"))
.withTarget("builder")
)
.withCommand("/bin/sh", "-c", "sleep 10")
) {
container.start();
assertThat(container.execInContainer("pwd").getStdout()).contains("/my-files");
assertThat(container.execInContainer("ls").getStdout()).contains("hello.txt");
}
}
}
9 changes: 9 additions & 0 deletions core/src/test/resources/Dockerfile-multistage
@@ -0,0 +1,9 @@
FROM alpine:3.14 AS builder

WORKDIR /my-files

RUN echo 'Hello World' > hello.txt

FROM alpine:3.14

COPY --from=builder /my-files/hello.txt hello.txt

0 comments on commit 66bcd39

Please sign in to comment.