Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the ability to set a target build stage to a Dockerfile #4810

Merged
merged 4 commits into from Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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