Best Testcontainers-java code snippet using org.testcontainers.images.builder.ImageFromDockerfile.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:OpenldapTestContainerIntegrationTestExtension.java  
...6import org.slf4j.LoggerFactory;7import org.testcontainers.containers.GenericContainer;8import org.testcontainers.containers.output.Slf4jLogConsumer;9import org.testcontainers.containers.wait.strategy.Wait;10import org.testcontainers.images.builder.ImageFromDockerfile;11import org.testcontainers.junit.jupiter.Container;12import java.nio.file.Path;13// Inspired by https://www.baeldung.com/spring-dynamicpropertysource#an-alternative-test-fixtures14public class OpenldapTestContainerIntegrationTestExtension implements BeforeAllCallback, AfterAllCallback {15    private static final Logger LOG = LoggerFactory.getLogger(OpenldapTestContainerIntegrationTestExtension.class);16    protected static final int OPENLDAP_EXPOSED_PORT = 1389;17    @Container18    protected GenericContainer<?> openldapContainer;19    @Override20    public void beforeAll(ExtensionContext context) {21        final var imageFromDockerfile = new ImageFromDockerfile()22                .withFileFromPath(".", Path.of("src", "main", "docker"));23        openldapContainer = new GenericContainer<>(imageFromDockerfile)24                .withExposedPorts(OPENLDAP_EXPOSED_PORT)25                .withLogConsumer(new Slf4jLogConsumer(LOG))26                .waitingFor(Wait.forLogMessage(".*slapd starting.*", 1));27        openldapContainer.start();28        String openldapUrl = String.format("ldap://%s:%s", openldapContainer.getHost(), openldapContainer.getMappedPort(OPENLDAP_EXPOSED_PORT));29        System.setProperty("spring.ldap.urls", openldapUrl);30    }31    @Override32    public void afterAll(ExtensionContext context) {33        // do nothing, Testcontainers handles container shutdown34    }35}...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
1package org.testcontainers.images.builder;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.images.builder.ImageFromDockerfile;4public class TestImageFromDockerfile {5    public static void main(String[] args) {6        ImageFromDockerfile image = new ImageFromDockerfile()7                .withFileFromClasspath("Dockerfile", "Dockerfile")8                .withFileFromClasspath("test.txt", "test.txt");9        GenericContainer container = new GenericContainer(image);10        container.start();11    }12}ImageFromDockerfile
Using AI Code Generation
1package org.testcontainers.images.builder;2import org.testcontainers.images.builder.ImageFromDockerfile;3public class ImageFromDockerfileTest {4   public static void main(String[] args) {5      ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile();6      imageFromDockerfile.withDockerfileFromBuilder(builder -> builder.from("ubuntu:latest"));7      System.out.println(imageFromDockerfile);8   }9}10ImageFromDockerfile{dockerfile=FROM ubuntu:latest, dockerfileLines=[FROM ubuntu:latest], dockerfileTemplate=Optional.empty, dockerfilePath=Optional.empty, dockerfileName=Optional.empty, dockerfileDirectory=Optional.empty, dockerfileMode=Optional.empty, dockerfileTarget=Optional.empty, dockerfileArgs=Optional.empty, dockerfileLabels=Optional.empty, dockerfileComment=Optional.empty, dockerfileCopy=Optional.empty, dockerfileAdd=Optional.empty, dockerfileRun=Optional.empty, dockerfileEntrypoint=Optional.empty, dockerfileCmd=Optional.empty, dockerfileHealthcheck=Optional.empty, dockerfileExpose=Optional.empty, dockerfileEnv=Optional.empty, dockerfileUser=Optional.empty, dockerfileVolume=Optional.empty, dockerfileWorkdir=Optional.empty, dockerfileOnbuild=Optional.empty, dockerfileStopsignal=Optional.empty, dockerfileShell=Optional.empty, dockerfileFrom=Optional.empty, dockerfileMaintainer=Optional.empty, dockerfileArg=Optional.empty, dockerfileLabel=Optional.empty, dockerfileCommentLine=Optional.empty, dockerfileCopyLine=Optional.empty, dockerfileAddLine=Optional.empty, dockerfileRunLine=Optional.empty, dockerfileEntrypointLine=Optional.empty, dockerfileCmdLine=Optional.empty, dockerfileHealthcheckLine=Optional.empty, dockerfileExposeLine=Optional.empty, dockerfileEnvLine=Optional.empty, dockerfileUserLine=Optional.empty, dockerfileVolumeLine=Optional.empty, dockerfileWorkdirLine=Optional.empty, dockerfileOnbuildLine=Optional.empty, dockerfileStopsignalLine=Optional.empty, dockerfileShellLine=Optional.empty, dockerfileFromLine=Optional.empty, dockerfileMaintainerLine=Optional.empty, dockerfileFromImage=Optional.empty, dockerfileFromAlias=Optional.empty, dockerfileFromStage=Optional.empty, dockerfileFromPlatform=Optional.empty, dockerfileFromPlatformArgs=Optional.empty, dockerfileImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.images.builder.ImageFromDockerfile;3import java.util.List;4public class 1 {5    public static void main(String[] args) {6        ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()7                .withFileFromClasspath("Dockerfile", "Dockerfile");8        List<String> tags = imageFromDockerfile.getTags();9        System.out.println("The tags are: " + tags);10        GenericContainer container = new GenericContainer(imageFromDockerfile);11        container.start();12    }13}ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2import org.testcontainers.utility.MountableFile;3import java.io.File;4import java.nio.file.Paths;5import java.util.stream.Stream;6import org.testcontainers.containers.GenericContainer;7import org.testcontainers.images.builder.Transferable;8import org.testcontainers.utility.MountableFile;9public class Test {10    public static void main(String[] args) {ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.images.builder.ImageFromDockerfile;2public class ImageFromDockerfileDemo {3    public static void main(String[] args) {4        ImageFromDockerfile image = new ImageFromDockerfile("myimage", false);5        System.out.println(image);6    }7}8ImageFromDockerfile(imageName=myimage, dockerFile=Dockerfile, dockerFileDirectory=/tmp/testcontainers-0.0.0, forcePull=false)ImageFromDockerfile
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.images.builder.ImageFromDockerfile;3import java.io.File;4import java.io.IOException;5public class 1 {6    public static void main(String[] args) throws IOException {7        File dockerfile = new File("Dockerfile");8        ImageFromDockerfile image = new ImageFromDockerfile("my-image", false)9                .withDockerfile(dockerfile);10        GenericContainer container = new GenericContainer(image)11                .withExposedPorts(8080);12        container.start();13        int mappedPort = container.getMappedPort(8080);14        String containerIp = container.getContainerIpAddress();15        System.out.println("The container is running at " + containerIp + ":" + mappedPort);16    }17}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!!
