Best Testcontainers-java code snippet using org.testcontainers.images.builder.ImageFromDockerfile
Source:ImageFromDockerfile.java
...24import java.util.*;25import java.util.zip.GZIPOutputStream;26@Slf4j27@Getter28public class ImageFromDockerfile extends LazyFuture<String> implements29 BuildContextBuilderTrait<ImageFromDockerfile>,30 ClasspathTrait<ImageFromDockerfile>,31 FilesTrait<ImageFromDockerfile>,32 StringsTrait<ImageFromDockerfile>,33 DockerfileTrait<ImageFromDockerfile> {34 private final String dockerImageName;35 private boolean deleteOnExit = true;36 private final Map<String, Transferable> transferables = new HashMap<>();37 private final Map<String, String> buildArgs = new HashMap<>();38 private Optional<String> dockerFilePath = Optional.empty();39 private Optional<Path> dockerfile = Optional.empty();40 private Set<String> dependencyImageNames = Collections.emptySet();41 public ImageFromDockerfile() {42 this("localhost/testcontainers/" + Base58.randomString(16).toLowerCase());43 }44 public ImageFromDockerfile(String dockerImageName) {45 this(dockerImageName, true);46 }47 public ImageFromDockerfile(String dockerImageName, boolean deleteOnExit) {48 this.dockerImageName = dockerImageName;49 this.deleteOnExit = deleteOnExit;50 }51 @Override52 public ImageFromDockerfile withFileFromTransferable(String path, Transferable transferable) {53 Transferable oldValue = transferables.put(path, transferable);54 if (oldValue != null) {55 log.warn("overriding previous mapping for '{}'", path);56 }57 return this;58 }59 @Override60 protected final String resolve() {61 Logger logger = DockerLoggerFactory.getLogger(dockerImageName);62 DockerClient dockerClient = DockerClientFactory.instance().client();63 try {64 if (deleteOnExit) {65 ResourceReaper.instance().registerImageForCleanup(dockerImageName);66 }67 BuildImageResultCallback resultCallback = new BuildImageResultCallback() {68 @Override69 public void onNext(BuildResponseItem item) {70 super.onNext(item);71 if (item.isErrorIndicated()) {72 logger.error(item.getErrorDetail().getMessage());73 } else {74 logger.debug(StringUtils.chomp(item.getStream(), "\n"));75 }76 }77 };78 // We have to use pipes to avoid high memory consumption since users might want to build really big images79 @Cleanup PipedInputStream in = new PipedInputStream();80 @Cleanup PipedOutputStream out = new PipedOutputStream(in);81 BuildImageCmd buildImageCmd = dockerClient.buildImageCmd(in);82 configure(buildImageCmd);83 Map<String, String> labels = new HashMap<>();84 if (buildImageCmd.getLabels() != null) {85 labels.putAll(buildImageCmd.getLabels());86 }87 labels.putAll(DockerClientFactory.DEFAULT_LABELS);88 buildImageCmd.withLabels(labels);89 prePullDependencyImages(dependencyImageNames);90 BuildImageResultCallback exec = buildImageCmd.exec(resultCallback);91 long bytesToDockerDaemon = 0;92 // To build an image, we have to send the context to Docker in TAR archive format93 try (TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(new GZIPOutputStream(out))) {94 tarArchive.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);95 tarArchive.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);96 for (Map.Entry<String, Transferable> entry : transferables.entrySet()) {97 Transferable transferable = entry.getValue();98 final String destination = entry.getKey();99 transferable.transferTo(tarArchive, destination);100 bytesToDockerDaemon += transferable.getSize();101 }102 tarArchive.finish();103 }104 log.info("Transferred {} to Docker daemon", FileUtils.byteCountToDisplaySize(bytesToDockerDaemon));105 if (bytesToDockerDaemon > FileUtils.ONE_MB * 50) // warn if >50MB sent to docker daemon106 log.warn("A large amount of data was sent to the Docker daemon ({}). Consider using a .dockerignore file for better performance.",107 FileUtils.byteCountToDisplaySize(bytesToDockerDaemon));108 exec.awaitImageId();109 return dockerImageName;110 } catch(IOException e) {111 throw new RuntimeException("Can't close DockerClient", e);112 }113 }114 protected void configure(BuildImageCmd buildImageCmd) {115 buildImageCmd.withTag(this.getDockerImageName());116 this.dockerFilePath.ifPresent(buildImageCmd::withDockerfilePath);117 this.dockerfile.ifPresent(p -> {118 buildImageCmd.withDockerfile(p.toFile());119 dependencyImageNames = new ParsedDockerfile(p).getDependencyImageNames();120 if (dependencyImageNames.size() > 0) {121 // if we'll be pre-pulling images, disable the built-in pull as it is not necessary and will fail for122 // authenticated registries123 buildImageCmd.withPull(false);124 }125 });126 this.buildArgs.forEach(buildImageCmd::withBuildArg);127 }128 private void prePullDependencyImages(Set<String> imagesToPull) {129 final DockerClient dockerClient = DockerClientFactory.instance().client();130 imagesToPull.forEach(imageName -> {131 try {132 log.info("Pre-emptively checking local images for '{}', referenced via a Dockerfile. If not available, it will be pulled.", imageName);133 DockerClientFactory.instance().checkAndPullImage(dockerClient, imageName);134 } catch (Exception e) {135 log.warn("Unable to pre-fetch an image ({}) depended upon by Dockerfile - image build will continue but may fail. Exception message was: {}", imageName, e.getMessage());136 }137 });138 }139 public ImageFromDockerfile withBuildArg(final String key, final String value) {140 this.buildArgs.put(key, value);141 return this;142 }143 public ImageFromDockerfile withBuildArgs(final Map<String, String> args) {144 this.buildArgs.putAll(args);145 return this;146 }147 /**148 * Sets the Dockerfile to be used for this image.149 *150 * @param relativePathFromBuildContextDirectory relative path to the Dockerfile, relative to the image build context directory151 * @deprecated It is recommended to use {@link #withDockerfile} instead because it honors .dockerignore files and152 * will therefore be more efficient. Additionally, using {@link #withDockerfile} supports Dockerfiles that depend153 * upon images from authenticated private registries.154 */155 @Deprecated156 public ImageFromDockerfile withDockerfilePath(String relativePathFromBuildContextDirectory) {157 this.dockerFilePath = Optional.of(relativePathFromBuildContextDirectory);158 return this;159 }160 /**161 * Sets the Dockerfile to be used for this image. Honors .dockerignore files for efficiency.162 * Additionally, supports Dockerfiles that depend upon images from authenticated private registries.163 *164 * @param dockerfile path to Dockerfile on the test host.165 */166 public ImageFromDockerfile withDockerfile(Path dockerfile) {167 this.dockerfile = Optional.of(dockerfile);168 return this;169 }170}...
Source:OpenSearchContainer.java
1package net.javacrumbs.container;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;4import org.testcontainers.images.builder.ImageFromDockerfile;5import org.testcontainers.utility.Base58;6import java.time.Duration;7import static java.net.HttpURLConnection.HTTP_OK;8import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;9public class OpenSearchContainer extends GenericContainer<OpenSearchContainer> {10 static final int OPENSEARCH_DEFAULT_PORT = 9200;11 static final int OPENSEARCH_DEFAULT_TCP_PORT = 9300;12 public OpenSearchContainer(String dockerImageName) {13 super(dockerImageName);14 }15 private ImageFromDockerfile prepareImage(String imageName) {16 return new ImageFromDockerfile()17 .withDockerfileFromBuilder(builder -> {18 builder.from(imageName);19 });20 }21 @Override22 protected void configure() {23 withNetworkAliases("opensearch-" + Base58.randomString(6));24 withEnv("discovery.type", "single-node");25 addExposedPorts(OPENSEARCH_DEFAULT_PORT, OPENSEARCH_DEFAULT_TCP_PORT);26 setWaitStrategy(new HttpWaitStrategy()27 .forPort(OPENSEARCH_DEFAULT_PORT)28 .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED)29 .withStartupTimeout(Duration.ofMinutes(2)));30 setImage(prepareImage(getDockerImageName()));...
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.output.Slf4jLogConsumer;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6public class DockerfileImage {7 public static void main(String[] args) {8 Logger logger = LoggerFactory.getLogger(DockerfileImage.class);9 ImageFromDockerfile image = new ImageFromDockerfile()10 .withDockerfileFromBuilder(builder -> builder11 .from("alpine:3.5")12 .run("apk update && apk add curl")13 .run("curl -L
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.images.builder.ImageFromDockerfile;3public class ImageFromDockerfileExample {4 public static void main(String[] args) {5 ImageFromDockerfile image = new ImageFromDockerfile("testcontainers/ryuk", false)6 .withFileFromClasspath("ryuk-0.2.3.jar", "ryuk-0.2.3.jar")7 .withFileFromClasspath("Dockerfile", "ryuk/Dockerfile");8 try (GenericContainer container = new GenericContainer(image)) {9 container.start();10 System.out.println("Ryuk started");11 }12 }13}14import org.testcontainers.containers.GenericContainer;15import org.testcontainers.images.builder.ImageFromDockerfile;16public class ImageFromDockerfileExample {17 public static void main(String[] args) {18 ImageFromDockerfile image = new ImageFromDockerfile("testcontainers/ryuk", false)19 .withFileFromClasspath("ryuk-0.2.3.jar", "ryuk-0.2.3.jar")20 .withFileFromClasspath("Dockerfile", "ryuk/Dockerfile");21 try (GenericContainer container = new GenericContainer(image)) {22 container.start();23 System.out.println("Ryuk started");24 }25 }26}
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.images.builder.ImageFromDockerfile;3import org.testcontainers.utility.DockerImageName;4public class ImageFromDockerfileTest {5 public static void main(String[] args) {6 ImageFromDockerfile image = new ImageFromDockerfile()7 .withDockerfileFromBuilder(builder -> builder8 .from("openjdk:8-jdk-alpine")9 .run("apk add --no-cache curl")10 .build());11 try (GenericContainer container = new GenericContainer(image).withCommand("sh", "-c", "while true; do sleep 1; done")) {12 container.start();13 System.out.println("Result: " + result);14 }15 }16}
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2import org.testcontainers.utility.DockerImageName;3public class ImageFromDockerfileExample {4 public static void main(String[] args) {5 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()6 .withDockerfileFromBuilder(builder -> builder7 .from(DockerImageName.parse("alpine"))8 .run("apk add --no-cache curl")9 .build());10 System.out.println(imageFromDockerfile.getDockerfile());11 }12}13import org.testcontainers.images.builder.ImageFromDockerfile;14import org.testcontainers.utility.DockerImageName;15public class ImageFromDockerfileExample {16 public static void main(String[] args) {17 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()18 .withDockerfileFromBuilder(builder -> builder19 .from(DockerImageName.parse("alpine"))20 .run("apk add --no-cache curl")21 .build());22 System.out.println(imageFromDockerfile.getDockerfileAsString());23 }24}25import org.testcontainers.images.builder.ImageFromDockerfile;26import org.testcontainers.utility.DockerImageName;27public class ImageFromDockerfileExample {28 public static void main(String[] args) {29 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()30 .withDockerfileFromBuilder(builder -> builder31 .from(DockerImageName.parse("alpine"))32 .run("apk add --no-cache curl")33 .build());34 System.out.println(imageFromDockerfile.getBuildArgs());35 }36}37import org.testcontainers.images.builder.ImageFromDockerfile;38import org.testcontainers.utility.DockerImageName;39public class ImageFromDockerfileExample {40 public static void main(String[] args) {41 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()42 .withDockerfileFromBuilder(builder -> builder43 .from(Docker
ImageFromDockerfile
Using AI Code Generation
1package org.testcontainers.images.builder;2import org.testcontainers.images.builder.ImageFromDockerfile;3public class DockerFileImage {4 public static void main(String args[]) {5 ImageFromDockerfile image = new ImageFromDockerfile("testcontainers/ryuk:0.3.0")6 .withFileFromClasspath("Dockerfile", "Dockerfile");7 }8}9package org.testcontainers.images.builder;10import org.testcontainers.images.builder.Dockerfile;11public class DockerFileImage {12 public static void main(String args[]) {13 Dockerfile dockerfile = new Dockerfile().withDockerfileFromBuilder(builder -> builder14 .from("testcontainers/ryuk:0.3.0")15 .build());16 }17}
ImageFromDockerfile
Using AI Code Generation
1package org.testcontainers.images.builder;2import java.io.File;3import java.io.IOException;4import java.nio.file.Files;5import java.nio.file.Path;6import java.util.HashMap;7import java.util.Map;8import java.util.UUID;9import java.util.function.Consumer;10import org.apache.commons.io.FileUtils;11import org.apache.commons.lang.SystemUtils;12import org.testcontainers.images.builder.dockerfile.DockerfileBuilder;13import org.testcontainers.utility.DockerImageName;14import org.testcontainers.utility.MountableFile;15public class ImageFromDockerfile implements ImageFromDockerfileInterface {16 private final String imageName;17 private final boolean deleteOnExit;18 private final Map<String, String> envVars;19 private final Map<String, String> labels;20 private final DockerfileBuilder dockerfileBuilder;21 private final Consumer<MountableFile> fileConsumer;22 private ImageFromDockerfile(String imageName, boolean deleteOnExit, Map<String, String> envVars, Map<String, String> labels, DockerfileBuilder dockerfileBuilder, Consumer<MountableFile> fileConsumer) {23 this.imageName = imageName;24 this.deleteOnExit = deleteOnExit;25 this.envVars = envVars;26 this.labels = labels;27 this.dockerfileBuilder = dockerfileBuilder;28 this.fileConsumer = fileConsumer;29 }30 public static ImageFromDockerfile create() {31 return new ImageFromDockerfile(null, true, new HashMap<>(), new HashMap<>(), new DockerfileBuilder(), null);32 }33 public ImageFromDockerfile withDockerfileFromBuilder(Consumer<DockerfileBuilder> dockerfileBuilderConsumer) {34 dockerfileBuilderConsumer.accept(dockerfileBuilder);35 return this;36 }37 public ImageFromDockerfile withFileFromPath(String path, Path file) {38 return withFileFromPath(path, file, null);39 }40 public ImageFromDockerfile withFileFromPath(String path, Path file, Consumer<MountableFile> fileConsumer) {41 this.fileConsumer = fileConsumer;42 dockerfileBuilder.from("busybox").add(path, file.toString(), false);43 return this;44 }45 public ImageFromDockerfile withFileFromClasspath(String path, String classpathResource) {46 return withFileFromClasspath(path, classpathResource, null);47 }
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2public class ImageFromDockerfileDemo {3 public static void main(String[] args) {4 new ImageFromDockerfile("testcontainers/ryuk", "0.2.3")5 .withDockerfileFromBuilder(builder -> builder6 .from("alpine:3.10")7 .env("foo", "bar")8 .build())9 .withFileFromClasspath("test.txt", "file-in-resources.txt")10 .withFileFromString("hello.txt", "Hello world!")11 .withFileFromString("hello2.txt", "Hello world!")12 .withFileFromString("hello3.txt", "Hello world!")13 .withFileFromString("hello4.txt", "Hello world!")14 .withFileFromString("hello5.txt", "Hello world!")15 .withFileFromString("hello6.txt", "Hello world!")16 .withFileFromString("hello7.txt", "Hello world!")17 .withFileFromString("hello8.txt", "Hello world!")18 .withFileFromString("hello9.txt", "Hello world!")19 .withFileFromString("hello10.txt", "Hello world!")20 .withFileFromString("hello11.txt", "Hello world!")21 .withFileFromString("hello12.txt", "Hello world!")22 .withFileFromString("hello13.txt", "Hello world!")23 .withFileFromString("hello14.txt", "Hello world!")24 .withFileFromString("hello15.txt", "Hello world!")25 .withFileFromString("hello16.txt", "Hello world!")26 .withFileFromString("hello17.txt", "Hello world!")27 .withFileFromString("hello18.txt", "Hello world!")28 .withFileFromString("hello19.txt", "Hello world!")29 .withFileFromString("hello20.txt", "Hello world!")30 .withFileFromString("hello21.txt", "Hello world!")31 .withFileFromString("hello22.txt", "Hello world!")32 .withFileFromString("hello23.txt", "Hello world!")33 .withFileFromString("hello24.txt", "Hello world!")34 .withFileFromString("hello25.txt", "Hello world!")35 .withFileFromString("hello26.txt", "Hello world!")36 .withFileFromString("hello27.txt", "Hello world!")37 .withFileFromString("hello28.txt", "Hello world!")
ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2import org.testcontainers.utility.MountableFile;3ImageFromDockerfile image = new ImageFromDockerfile()4 .withFileFromFile("test.txt", new File("test.txt"))5 .withFileFromString("test2.txt", "test2");6ImageFromDockerfile image = new ImageFromDockerfile()7 .withFileFromFile("test.txt", new File("test.txt"))8 .withFileFromPath("test2.txt", Paths.get("test2.txt"))9 .withFileFromPath("test3.txt", Paths.get("test3.txt"));10ImageFromDockerfile image = new ImageFromDockerfile()11 .withFileFromFile("test.txt", new File("test.txt"))12 .withFileFromPath("test2.txt", Paths.get("test2.txt"))13 .withFileFromPath("test3.txt", Paths.get("test3.txt"))14 .withFileFromPath("test4.txt", Paths.get("test4.txt"))15 .withFileFromPath("test5.txt", Paths.get("test5.txt"))16 .withFileFromPath("test6.txt", Paths.get("test6.txt"));17ImageFromDockerfile image = new ImageFromDockerfile()18 .withFileFromFile("test.txt", new File("test.txt"))19 .withFileFromPath("test2.txt", Paths.get("test2.txt"))20 .withFileFromPath("test3.txt", Paths.get("test3.txt"))21 .withFileFromPath("test4.txt", Paths.get("test4.txt"))22 .withFileFromPath("test5.txt", Paths.get("test5.txt"))23 .withFileFromPath("test6.txt", Paths.get("test6.txt"))24 .withFileFromPath("test7.txt", Paths.get("test7.txt"));25ImageFromDockerfile image = new ImageFromDockerfile()26 .withFileFromFile("test.txt", new File("test.txt"))27 .withFileFromPath("test2.txt", Paths.get("test2.txt"))28 .withFileFromPath("test
ImageFromDockerfile
Using AI Code Generation
1package org.testcontainers.images.builder;2import org.testcontainers.images.builder.dockerfile.Dockerfile;3import org.testcontainers.images.builder.dockerfile.statement.CopyFileFromHost;4import org.testcontainers.images.builder.dockerfile.statement.RunCommand;5import org.testcontainers.images.builder.dockerfile.statement.Statement;6import org.testcontainers.images.builder.dockerfile.statement.WriteFile;7import org.testcontainers.utility.DockerImageName;8import java.io.File;9import java.util.Arrays;10import java.util.List;11public class ImageFromDockerfileExample {12 public static void main(String[] args) {13 List<Statement> statements = Arrays.asList(14 new CopyFileFromHost("src/main/resources/test.txt", "/home/test.txt"),15 new WriteFile("src/main/resources/test.txt", "test"),16 new RunCommand("echo \"test\" > /home/test.txt")17 );18 Dockerfile dockerfile = Dockerfile.builder()19 .from("ubuntu:latest")20 .withStatements(statements)21 .build();22 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()23 .withDockerfile(dockerfile)24 .withFileFromPath("test.txt", new File("src/main/resources/test.txt"))25 .withFileFromClasspath("test.txt", "test.txt");26 DockerImageName dockerImageName = imageFromDockerfile.build();27 System.out.println(dockerImageName);28 }29}30package org.testcontainers.images.builder;31import org.testcontainers.images.builder.dockerfile.Dockerfile;32import org.testcontainers.images.builder.dockerfile.statement.CopyFileFromHost;33import org.testcontainers.images.builder.dockerfile.statement.RunCommand;34import org.testcontainers.images.builder.dockerfile.statement.Statement;35import org.testcontainers.images.builder.dockerfile.statement.WriteFile;36import org.testcontainers.utility.DockerImageName;37import java.io.File;38import java.util.Arrays;39import java.util.List;40public class ImageFromDockerfileExample {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!