### Build, Run, and Test Container Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Build a Docker image, start a container, run functional tests against it, and then stop the container. This automates testing of containerized applications. ```groovy task functionalTest(type: DockerBuildImage, dependsOn: ["build", "buildImage"]) task runTests(type: DockerCreateContainer, dependsOn: "buildImage") { targetImage = "my-app:latest" portBindings = ["8080:8080"] wait = true waitContainerPort = 8080 waitContainerTimeout = 10000 } task stopContainer(type: DockerRemoveContainer, dependsOn: "runTests") { targetContainerId = runTests.containerId } ``` ```kotlin tasks.register("functionalTest") { dependsOn(tasks.getByName("build"), tasks.getByName("buildImage")) } tasks.register("runTests") { dependsOn("buildImage") targetImage.set("my-app:latest") portBindings.set(listOf("8080:8080")) wait.set(true) waitContainerPort.set(8080) waitContainerTimeout.set(10000) } tasks.register("stopContainer") { dependsOn("runTests") targetContainerId.set(tasks.getByName("runTests").containerId) } ``` -------------------------------- ### Configure Spring Boot Plugin Extension (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/32-extension.adoc Configure the Spring Boot plugin extension in Kotlin. This example demonstrates setting various properties for building a Spring Boot Docker image. ```kotlin docker { springBootApplication { baseImage("openjdk:17-jdk-slim") maintainer = "\"My Name\" " user = "1001" ports.set(listOf(8080, 8081)) jvmArgs.set(listOf("-Xms512m", "-Xmx1024m")) mainClassName = "com.example.MyApplication" args.set(listOf("--server.port=8081")) } } ``` -------------------------------- ### Generated Dockerfile Example Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/24-dockerfile.adoc This is a typical Dockerfile generated by the plugin using default values. It specifies the base image, maintainer, working directory, copies application artifacts, sets the entrypoint to run the main class, and exposes the application port. ```dockerfile FROM openjdk:11-jre-slim LABEL maintainer=bmuschko WORKDIR /app COPY libs libs/ COPY classes classes/ ENTRYPOINT ["java", "-cp", "/app/resources:/app/classes:/app/libs/*", "com.bmuschko.gradle.docker.application.JettyMain"] EXPOSE 8080 ``` -------------------------------- ### Apply Plugin with buildscript Syntax (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/02-getting-started.adoc Apply the plugin using the buildscript syntax in a Groovy build file. This method is suitable for older Gradle versions or specific project setups. ```groovy buildscript { repositories { mavenCentral() } dependencies { classpath "com.github.gradle-docker-plugin:gradle-docker-plugin:1.2.0" } } apply plugin: "com.github.gradle-docker-plugin" ``` -------------------------------- ### Configure Spring Boot Plugin Extension (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/32-extension.adoc Configure the Spring Boot plugin extension in Groovy. This example shows how to set properties like base image, maintainer, ports, and JVM arguments. ```groovy docker { springBootApplication { baseImage = 'openjdk:17-jdk-slim' maintainer = '"My Name" ' user = '1001' ports = [8080, 8081] jvmArgs = ['-Xms512m', '-Xmx1024m'] mainClassName = 'com.example.MyApplication' args = ['--server.port=8081'] } } ``` -------------------------------- ### Print Docker Version Information Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Use the DockerVersion task to log the Docker client version and API version. This task is helpful for verifying Docker installation and compatibility. ```kotlin import com.bmuschko.gradle.docker.tasks.DockerVersion tasks.create("printDockerVersion", DockerVersion::class) { onNext { logger.quiet("Docker version: ${this.version}") logger.quiet("API version: ${this.apiVersion}") } } // Run: ./gradlew printDockerVersion // Output: Docker version: 26.1.4 API version: 1.45 ``` -------------------------------- ### Link Application Container to Database Container Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt This snippet shows how to link an application container to a database container using legacy container links and volume binds for Systemd compatibility. It defines tasks for building the application image, creating the database container, creating the application container with specific configurations, and starting the application container. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.container.* import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage val buildAppImage by tasks.creating(DockerBuildImage::class) { inputDir.set(file("docker/myapp")) images.add("test/myapp") } val createDbContainer by tasks.creating(DockerCreateContainer::class) { targetImageId("postgres:16") containerName.set("docker_auto") hostConfig.autoRemove.set(true) envVars.set(mapOf("POSTGRES_PASSWORD" to "secret")) } val createAppContainer by tasks.creating(DockerCreateContainer::class) { dependsOn(buildAppImage, createDbContainer) targetImageId(buildAppImage.imageId) hostConfig.portBindings.set(listOf("8080:8080")) hostConfig.autoRemove.set(true) hostConfig.links.set(listOf("docker_auto:database")) hostConfig.binds.set(mapOf("/sys/fs/cgroup" to "/sys/fs/cgroup")) tty.set(true) } val startAppContainer by tasks.creating(DockerStartContainer::class) { dependsOn(createAppContainer) targetContainerId(createAppContainer.containerId) } ``` -------------------------------- ### Link Containers Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Configure container linking for dependencies, such as databases, when starting a container. This establishes network connections between containers. ```groovy task runLinkedContainer(type: DockerCreateContainer) { targetImage = "my-app:latest" links = ["my-database:database"] portBindings = ["8080:8080"] } ``` ```kotlin tasks.register("runLinkedContainer") { targetImage.set("my-app:latest") links.set(listOf("my-database:database")) portBindings.set(listOf("8080:8080")) } ``` -------------------------------- ### Run Functional Tests Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/dev-guide/20-development.adoc Execute functional tests against a running Docker instance. Ensure Docker CE is installed and running. ```shell $ ./gradlew functionalTest ``` -------------------------------- ### Functional Testing Workflow with Container Lifecycle Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Orchestrate a full container lifecycle for functional testing: build an image, create and start a container with port bindings, run tests, and stop the container as a finalizer. `finalizedBy` ensures cleanup even if tests fail. ```kotlin import com.bmuschko.gradle.docker.tasks.container.* import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage val buildAppImage by tasks.creating(DockerBuildImage::class) { inputDir.set(file("docker/myapp")) images.add("test/myapp:latest") } val createAppContainer by tasks.creating(DockerCreateContainer::class) { dependsOn(buildAppImage) targetImageId(buildAppImage.imageId) hostConfig.portBindings.set(listOf("8080:8080")) hostConfig.autoRemove.set(true) } val startAppContainer by tasks.creating(DockerStartContainer::class) { dependsOn(createAppContainer) targetContainerId(createAppContainer.containerId) } val stopAppContainer by tasks.creating(DockerStopContainer::class) { targetContainerId(createAppContainer.containerId) } tasks.create("functionalTest", Test::class) { dependsOn(startAppContainer) finalizedBy(stopAppContainer) // guaranteed cleanup even on failure testClassesDirs = sourceSets["functionalTest"].output.classesDirs classpath = sourceSets["functionalTest"].runtimeClasspath systemProperty("app.host", "localhost") systemProperty("app.port", "8080") } ``` -------------------------------- ### Configure Docker for Spring Boot Application Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt This snippet configures the `docker-spring-boot-application` plugin for a Spring Boot project. It specifies the base image, ports, image names, and JVM arguments. It also provides an example of how to override runtime environment variables for Kubernetes. ```kotlin // build.gradle.kts plugins { java id("org.springframework.boot") version "2.7.18" id("com.bmuschko.docker-spring-boot-application") version "10.0.0" } version = "1.2.3" group = "com.example" repositories { mavenCentral() } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") } docker { springBootApplication { baseImage.set("openjdk:17-jre-slim") ports.set(listOf(8080)) images.set(setOf("myorg/my-spring-app:1.2.3", "myorg/my-spring-app:latest")) jvmArgs.set(listOf("-Dspring.profiles.active=production", "-Xmx2048m")) } } // Run: ./gradlew dockerBuildImage // Run: ./gradlew dockerPushImage // Kubernetes deployment runtime override (no rebuild needed): // $ docker run -e "SPRING_PROFILES_ACTIVE=prod" -p 8080:8080 myorg/my-spring-app:1.2.3 ``` -------------------------------- ### Load Dockerfile Instructions from Template Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Use `instructionsFromTemplate()` to generate a `Dockerfile` from a Mustache-style template file. This allows for more dynamic Dockerfile creation. ```kotlin import com.bmuschko.gradle.docker.tasks.image.Dockerfile tasks.named("dockerCreateDockerfile") { instructionsFromTemplate(file("Dockerfile.tmpl")) } ``` -------------------------------- ### Create Dockerfile and Build Image Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Define Dockerfile instructions and build a Docker image using the `Dockerfile` task. Ensure instructions are declared in the correct order. ```groovy task buildImage(type: Dockerfile) { instruction "FROM alpine:3.15" instruction "RUN apk add --no-cache curl" instruction "COPY src /app/src" instruction "CMD [ \"/app/src/main/bash/run.sh\" ]" targetImage = "my-app:latest" } ``` ```kotlin tasks.register("buildImage") { instruction("FROM alpine:3.15") instruction("RUN apk add --no-cache curl") instruction("COPY src /app/src") instruction("CMD [ \"/app/src/main/bash/run.sh\" ]") targetImage.set("my-app:latest") } ``` -------------------------------- ### Add Dockerfile Instructions using Template (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Use a template to define custom Dockerfile instructions with Groovy. ```groovy dockerDistTar.instructionTemplate = """ FROM openjdk:11-jdk-slim MAINTAINER "My Name " RUN apt-get update && apt-get install -y --no-install-recommends some-package && rm -rf /var/lib/apt/lists/* COPY ${jar.archivePath} /app WORKDIR /app CMD ["java", "-jar", "app.jar"] """ ``` -------------------------------- ### Add Dockerfile Instructions using Template (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Use a template to define custom Dockerfile instructions with Kotlin. ```kotlin dockerDistTar.instructionTemplate.set(""" FROM openjdk:11-jdk-slim MAINTAINER "My Name " RUN apt-get update && apt-get install -y --no-install-recommends some-package && rm -rf /var/lib/apt/lists/* COPY ${jar.archivePath} /app WORKDIR /app CMD ["java", "-jar", "app.jar"] """) ``` -------------------------------- ### Generate Dockerfile using DSL Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Create a `Dockerfile` using a type-safe DSL. Outputs default to `$buildDir/docker/Dockerfile`. Use `instruction()` for raw Dockerfile commands. ```kotlin import com.bmuschko.gradle.docker.tasks.image.Dockerfile tasks.create("createDockerfile", Dockerfile::class) { from("openjdk:jre-alpine") label(mapOf("maintainer" to "Jane Doe 'jane@example.com'")) workingDir("/app") copyFile("my-app-1.0.jar", "/app/my-app-1.0.jar") entryPoint("java") defaultCommand("-jar", "/app/my-app-1.0.jar") exposePort(8080) environmentVariable("JAVA_OPTS", "-Xmx512m") runCommand("apk add --no-cache bash") // Add a raw instruction when no typed method exists instruction("HEALTHCHECK CMD wget --quiet --tries=1 --spider http://localhost:8080/health || exit 1") } ``` -------------------------------- ### Configure Dockerfile for Java Application Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt This snippet demonstrates configuring the `docker-java-application` plugin for a Java project. It sets base image, maintainer, user, ports, image names, JVM arguments, and application arguments. It also shows how to customize the auto-generated Dockerfile with additional instructions and environment variables. ```kotlin // build.gradle.kts plugins { java id("com.bmuschko.docker-java-application") version "10.0.0" } version = "2.1.0" group = "com.example" repositories { mavenCentral() } dependencies { implementation("org.eclipse.jetty.aggregate:jetty-all:9.4.29.v20200521") } docker { javaApplication { baseImage.set("openjdk:17-jre-slim") maintainer.set("Jane Doe 'jane@example.com'") user.set("appuser") ports.set(listOf(8080, 8443)) images.set(setOf("myorg/myapp:2.1.0", "myorg/myapp:latest")) jvmArgs.set(listOf("-Xms256m", "-Xmx1024m", "-Djava.security.egd=file:/dev/./urandom")) args.set(listOf("--spring.config.location=/app/config/")) } } // Customize the auto-generated Dockerfile import com.bmuschko.gradle.docker.tasks.image.Dockerfile tasks.named("dockerCreateDockerfile") { instruction("RUN adduser --disabled-password appuser") environmentVariable("APP_HOME", "/app") } // Run: ./gradlew dockerBuildImage // Run: ./gradlew dockerPushImage ``` ```dockerfile FROM openjdk:17-jre-slim LABEL maintainer="Jane Doe 'jane@example.com'" WORKDIR /app COPY libs libs/ COPY classes classes/ ENTRYPOINT ["java", "-Xms256m", "-Xmx1024m", "-Djava.security.egd=file:/dev/./urandom", "-cp", "/app/resources:/app/classes:/app/libs/*", "com.example.Main"] EXPOSE 8080 8443 ``` -------------------------------- ### Add Dockerfile Instructions (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Extend the Dockerfile with custom instructions using the `dockerDistTar` task and Groovy DSL. ```groovy dockerDistTar.dockerfile { from 'openjdk:11-jdk-slim' maintainer '"My Name "' run 'apt-get update && apt-get install -y --no-install-recommends some-package && rm -rf /var/lib/apt/lists/*' copyApp jar.archivePath, '/app/' workingDir '/app' defaultCommand '["java", "-jar", "app.jar"]' } ``` -------------------------------- ### Docker Container Lifecycle Management Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Defines tasks for creating, starting, and stopping Docker containers. Ensure dependent tasks like image building are completed first. The `DockerCreateContainer` task can configure port mappings, auto-removal, and environment variables. ```kotlin import com.bmuschko.gradle.docker.tasks.container.* import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage val buildImage by tasks.creating(DockerBuildImage::class) { inputDir.set(file("docker")) images.add("test/myapp:latest") } val createContainer by tasks.creating(DockerCreateContainer::class) { dependsOn(buildImage) targetImageId(buildImage.imageId) containerName.set("myapp-container") hostConfig.portBindings.set(listOf("8080:8080")) hostConfig.autoRemove.set(true) envVars.set(mapOf("SPRING_PROFILES_ACTIVE" to "test")) tty.set(false) } val startContainer by tasks.creating(DockerStartContainer::class) { dependsOn(createContainer) targetContainerId(createContainer.containerId) } val stopContainer by tasks.creating(DockerStopContainer::class) { targetContainerId(createContainer.containerId) waitTime.set(30) } ``` -------------------------------- ### Add Dockerfile Instructions (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Extend the Dockerfile with custom instructions using the `dockerDistTar` task and Kotlin DSL. ```kotlin dockerDistTar.dockerfile { from("openjdk:11-jdk-slim") maintainer("My Name ") run("apt-get update && apt-get install -y --no-install-recommends some-package && rm -rf /var/lib/apt/lists/*") copyApp(jar.archivePath, "/app") workingDir("/app") defaultCommand(listOf("java", "-jar", "app.jar")) } ``` -------------------------------- ### Build Docker Image from Build Context Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Builds a Docker image from a specified build context directory. This task is incremental and cacheable, writing the resulting image ID to a file. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.Dockerfile import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage val createDockerfile by tasks.creating(Dockerfile::class) { from("ubuntu:22.04") label(mapOf("maintainer" to "dev@example.com")) runCommand("apt-get update && apt-get install -y curl") } tasks.create("buildImage", DockerBuildImage::class) { dependsOn(createDockerfile) inputDir.set(createDockerfile.destDir) // build/docker/ images.add("myorg/myapp:1.0.0") images.add("myorg/myapp:latest") buildArgs.put("APP_VERSION", "1.0.0") noCache.set(false) pull.set(true) // imageIdFile is written automatically to build/docker/imageId.txt } ``` -------------------------------- ### Add Dockerfile Instructions Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Add new instructions to a Dockerfile at a specific position, like appending a HEALTHCHECK. This allows customization of existing Dockerfiles. ```groovy tasks.withType(Dockerfile) { instruction "HEALTHCHECK --interval=5m --timeout=3s CMD curl -f http://localhost:8080 || exit 1", -1 } ``` ```kotlin tasks.withType { instruction("HEALTHCHECK --interval=5m --timeout=3s CMD curl -f http://localhost:8080 || exit 1", -1) } ``` -------------------------------- ### Configure Docker Extension with TLS and Credentials Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/12-extension.adoc Use this snippet to configure the Docker plugin for a TLS-enabled Docker instance and provide registry credentials. Ensure your TLS certificates are set up correctly. ```groovy docker { url = 'tcp://127.0.0.1:2376' certPath = file("${System.properties['user.home']}/.docker/certs/") registryCredentials { url = 'https://index.docker.io/v1/' username = 'test' password = 'password' email = 'test@example.com' } } ``` ```kotlin docker { url.set("tcp://127.0.0.1:2376") certPath.set(file("${System.properties["user.home"]}/.docker/certs/")) registryCredentials { url.set("https://index.docker.io/v1/") username.set("test") password.set("password") email.set("test@example.com") } } ``` -------------------------------- ### Push Docker Image to Registry Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Pushes a locally built Docker image to a specified registry. Requires registry credentials to be configured. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.DockerPullImage import com.bmuschko.gradle.docker.tasks.image.DockerPushImage tasks.create("pushAppImage", DockerPushImage::class) { images.set(setOf("myregistry.example.com/myorg/myapp:2.0.0")) registryCredentials { url.set("https://myregistry.example.com") username.set(project.findProperty("registryUser") as String? ?: "") password.set(project.findProperty("registryPass") as String? ?: "") } } ``` -------------------------------- ### Apply Plugin using Plugin DSL Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Apply the remote API plugin using the `plugins {}` block in `settings.gradle.kts` and `build.gradle.kts`. Ensure `mavenCentral()` is added as a repository. ```kotlin rootProject.name = "my-docker-project" // build.gradle.kts plugins { id("com.bmuschko.docker-remote-api") version "10.0.0" } repositories { mavenCentral() } ``` -------------------------------- ### Apply Plugin with buildscript Syntax (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/02-getting-started.adoc Apply the plugin using the buildscript syntax in a Kotlin build file. This is the Kotlin equivalent for applying plugins via the buildscript block. ```kotlin buildscript { repositories { mavenCentral() } dependencies { classpath("com.github.gradle-docker-plugin:gradle-docker-plugin:1.2.0") } } apply(plugin = "com.github.gradle-docker-plugin") ``` -------------------------------- ### Configure Repositories for Docker Library (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/11-usage.adoc Specify repositories to host the Docker Java library and its transitive dependencies using Groovy. Maven Central is a common choice. ```groovy repositories { mavenCentral() } ``` -------------------------------- ### Apply Plugin with Plugin DSL (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/02-getting-started.adoc Apply the plugin using the modern plugin DSL in a Groovy build file. This is the recommended approach for applying plugins in newer Gradle versions. ```groovy plugins { id "com.github.gradle-docker-plugin" version "1.2.0" } ``` -------------------------------- ### Generated Dockerfile Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/34-dockerfile.adoc This Dockerfile is generated by the plugin using default values. It sets up a Java runtime, copies application artifacts, and defines the entry point for the application. ```dockerfile FROM openjdk:11-jre-slim LABEL maintainer=bmuschko WORKDIR /app COPY libs libs/ COPY classes classes/ ENTRYPOINT ["java", "-cp", "/app/resources:/app/classes:/app/libs/*", "com.bmuschko.gradle.docker.springboot.Application"] EXPOSE 8080 ``` -------------------------------- ### Configure Docker Extension for Google Cloud Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/12-extension.adoc Configure the Docker plugin to connect to a Docker instance using Google Cloud authentication, typically involving a key file. ```groovy docker { url = 'tcp://127.0.0.1:2375' certPath = file("${System.properties['user.home']}/.docker/certs/") registryCredentials { url = 'https://gcr.io' username = '_json_key' password = file("${System.properties['user.home']}/.gcloud/key.json") email = 'test@example.com' } } ``` ```kotlin docker { url.set("tcp://127.0.0.1:2375") certPath.set(file("${System.properties["user.home"]}/.docker/certs/")) registryCredentials { url.set("https://gcr.io") username.set("_json_key") password.set(file("${System.properties["user.home"]}/.gcloud/key.json")) email.set("test@example.com") } } ``` -------------------------------- ### Configure Docker Remote API Extension Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Configure the Docker daemon URL, TLS certificates, API version, and registry credentials using the `docker` extension. Properties are lazy `Provider`-based. Defaults are auto-detected. ```kotlin // build.gradle.kts — TLS-secured daemon with Docker Hub credentials docker { url.set("https://192.168.59.103:2376") certPath.set(File(System.getProperty("user.home"), ".boot2docker/certs/boot2docker-vm")) registryCredentials { url.set("https://index.docker.io/v1/") username.set("myuser") password.set("mysecret") email.set("myuser@example.com") } } // Non-TLS daemon (plain TCP) docker { url.set("tcp://192.168.59.103:2375") } // Google Container Registry using a service-account key file docker { registryCredentials { url.set("https://gcr.io") username.set("_json_key") password.set(file("keyfile.json").readText()) } } ``` -------------------------------- ### Run Application on Jetty with Docker (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Configure the Gradle build to run a Java application on Jetty within a Docker container using Kotlin. ```kotlin docker { application("my-app") { mainClassName = "com.example.MyApplication" jvmArgs.set(listOf("-Xms512m", "-Xmx1024m")) args.set(listOf("--server.port=8080")) images.set(listOf("my-app:latest")) portMappings.set(listOf("8080:8080")) } } ``` -------------------------------- ### Apply Plugin with Plugin DSL (Kotlin) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/02-getting-started.adoc Apply the plugin using the modern plugin DSL in a Kotlin build file. This is the recommended approach for applying plugins in newer Gradle versions with Kotlin. ```kotlin plugins { id("com.github.gradle-docker-plugin") version "1.2.0" } ``` -------------------------------- ### Apply Plugin using buildscript Syntax Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Alternatively, apply the plugin via the legacy `buildscript` block in `build.gradle.kts`. This method requires explicitly adding the plugin as a classpath dependency. ```kotlin buildscript { repositories { gradlePluginPortal() } dependencies { classpath("com.bmuschko:gradle-docker-plugin:10.0.0") } } apply(plugin = "com.bmuschko.docker-remote-api") ``` -------------------------------- ### Pull Docker Image from Registry Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Pulls a Docker image from a specified registry. Ensure the image name is correctly formatted. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.DockerPullImage import com.bmuschko.gradle.docker.tasks.image.DockerPushImage tasks.create("pullBaseImage", DockerPullImage::class) { image.set("openjdk:17-jre-slim") } ``` -------------------------------- ### Implement Custom Docker Client Task Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Create a custom Gradle task extending `AbstractDockerRemoteApiTask` for direct Docker client interaction. This provides full control over Docker operations. ```groovy abstract class CustomDockerTask extends AbstractDockerRemoteApiTask { @TaskAction void executeTask() { dockerClient.info().print() } } tasks.register("customDocker", CustomDockerTask) ``` ```kotlin abstract class CustomDockerTask : AbstractDockerRemoteApiTask() { @TaskAction fun executeTask() { dockerClient.info().print() } } tasks.register("customDocker") ``` -------------------------------- ### Stream Docker Container Logs Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Attaches to a container's standard output and error streams, forwarding logs to the Gradle console. The `follow` option keeps the stream open, and `tailAll` ensures all logs are captured. ```kotlin import com.bmuschko.gradle.docker.tasks.container.DockerLogsContainer tasks.create("tailLogs", DockerLogsContainer::class) { targetContainerId("myapp-container") follow.set(true) tailAll.set(true) onNext { // 'this' is a Frame object; toString() renders the log line logger.quiet(this.toString()) } } ``` -------------------------------- ### Apply Plugin from Script Plugin (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/02-getting-started.adoc Apply the plugin from a script plugin using the fully-qualified class name in a Groovy build file. This method is necessary due to a Gradle core bug and does not support the plugin DSL for applying binary plugins. ```groovy apply from: "gradle/docker.gradle" ``` -------------------------------- ### Build Spring Boot WAR for Tomcat with Gradle Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/35-examples.adoc Apply the 'war' plugin and declare container-related dependencies to generate a WAR file for a Spring Boot application to run on Tomcat. ```groovy plugins { id "groovy" id "com.bmuschko.docker-spring-boot" id "war" } dockerSpringBoot { imageName = "my-spring-boot-app" mainClassName = "com.example.Application" } dependencies { implementation "org.springframework.boot:spring-boot-starter-web" providedRuntime "org.springframework.boot:spring-boot-starter-tomcat" } ``` ```kotlin plugins { groovy id("com.bmuschko.docker-spring-boot") war } dockerSpringBoot { imageName.set("my-spring-boot-app") mainClassName.set("com.example.Application") } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-tomcat") } ``` -------------------------------- ### Custom Task Type Usage in Groovy Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Demonstrates how to define and use a custom task type in Groovy for Docker-related operations. Ensure the necessary plugin is applied. ```groovy import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage task customBuildImage(type: DockerBuildImage) { inputDir = file("src/main/docker") images.set(["my-custom-image:latest"]) } ``` -------------------------------- ### Run Application on Jetty with Docker (Groovy) Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/25-examples.adoc Configure the Gradle build to run a Java application on Jetty within a Docker container using Groovy. ```groovy docker { application("my-app") { mainClassName = "com.example.MyApplication" jvmArgs = [ "-Xms512m", "-Xmx1024m" ] args = [ "--server.port=8080" ] images = [ "my-app:latest" ] portMappings = [ "8080:8080" ] } } ``` -------------------------------- ### Copy Files to and From Docker Container Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Facilitates file transfers between the host and a Docker container. Use `withFile` for single files and `withTarFile` for archives. `DockerCopyFileFromContainer` extracts files from the container to a specified host path. ```kotlin import com.bmuschko.gradle.docker.tasks.container.DockerCopyFileToContainer import com.bmuschko.gradle.docker.tasks.container.DockerCopyFileFromContainer tasks.create("copyConfig", DockerCopyFileToContainer::class) { dependsOn("startContainer") targetContainerId("myapp-container") // Copy a single file withFile("src/main/resources/application-prod.yml", "/app/config/application.yml") // Copy a tar archive withTarFile(file("bundle.tar"), "/app/assets") } tasks.create("extractReport", DockerCopyFileFromContainer::class) { dependsOn("runTests") targetContainerId("myapp-container") remotePath.set("/app/reports/test-results.xml") hostPath.set("$buildDir/reports/") } ``` -------------------------------- ### Modify Dockerfile Instructions Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/15-examples.adoc Modify existing Dockerfile instructions, such as replacing the base image. This is useful when you don't control the Dockerfile's creation directly. ```groovy tasks.withType(Dockerfile) { instruction "FROM alpine:3.15" } ``` ```kotlin tasks.withType { instruction("FROM alpine:3.15") } ``` -------------------------------- ### Print Docker Daemon Information Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Use the DockerInfo task to log details about the Docker daemon, such as its operating system, running containers, and available images. Ensure the Docker daemon is accessible. ```kotlin import com.bmuschko.gradle.docker.tasks.DockerInfo tasks.create("printDockerInfo", DockerInfo::class) { onNext { logger.quiet("Docker OS: ${this.operatingSystem}") logger.quiet("Containers running: ${this.containersRunning}") logger.quiet("Images: ${this.images}") } } ``` -------------------------------- ### Configure Docker Extension in Groovy Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/22-extension.adoc Configure the Docker extension properties like base image, maintainer, ports, and JVM arguments using Groovy. ```groovy docker { javaApplication { baseImage = 'openjdk:17-jdk-slim' maintainer = 'My Name' user = '1000' ports = [8080, 8081] images = ['my-app:latest', 'my-app:v1.0'] jvmArgs = ['-Xms512m', '-Xmx1024m'] mainClassName = 'com.example.MyMainClass' args = ['--verbose'] } } ``` -------------------------------- ### Load Docker Image from Archive Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Loads a Docker image from a tar archive file. This is the counterpart to `DockerSaveImage` and is useful for restoring images. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.DockerSaveImage import com.bmuschko.gradle.docker.tasks.image.DockerLoadImage tasks.create("loadImage", DockerLoadImage::class) { imageFile.set(layout.buildDirectory.file("distributions/myapp-1.0.0.tar")) } ``` -------------------------------- ### Configure Docker Extension in Kotlin Source: https://github.com/bmuschko/gradle-docker-plugin/blob/master/src/docs/asciidoc/user-guide/22-extension.adoc Configure the Docker extension properties like base image, maintainer, ports, and JVM arguments using Kotlin. ```kotlin docker { javaApplication { baseImage.set("openjdk:17-jdk-slim") maintainer.set("My Name") user.set("1000") ports.set(listOf(8080, 8081)) images.set(setOf("my-app:latest", "my-app:v1.0")) jvmArgs.set(listOf("-Xms512m", "-Xmx1024m")) mainClassName.set("com.example.MyMainClass") args.set(listOf("--verbose")) } } ``` -------------------------------- ### Modify Dockerfile Instructions Programmatically Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Mutate the instruction list of an existing Dockerfile task. Useful for overriding base images or appending instructions after a convention plugin has created the task. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.Dockerfile import com.bmuschko.gradle.docker.tasks.image.Dockerfile.FromInstruction import com.bmuschko.gradle.docker.tasks.image.Dockerfile.From // Replace the FROM instruction with a different base image tasks { "createDockerfile"(Dockerfile::class) { val originalInstructions = instructions.get().toMutableList() val fromIndex = originalInstructions.indexOfFirst { it.keyword == FromInstruction.KEYWORD } originalInstructions.removeAt(fromIndex) originalInstructions.add(0, FromInstruction(From("eclipse-temurin:17-jre-alpine"))) instructions.set(originalInstructions) } } // Append a HEALTHCHECK at the end tasks { "createDockerfile"(Dockerfile::class) { instruction("HEALTHCHECK CMD curl --fail http://localhost:8080/actuator/health || exit 1") } } ``` -------------------------------- ### Tag Docker Image Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Assigns a new tag to an existing Docker image, identified by its ID. Useful for versioning or creating aliases. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.DockerTagImage import com.bmuschko.gradle.docker.tasks.image.DockerRemoveImage val buildImage by tasks.existing(com.bmuschko.gradle.docker.tasks.image.DockerBuildImage::class) tasks.create("tagImage", DockerTagImage::class) { dependsOn(buildImage) targetImageId(buildImage.get().imageId) repository.set("myregistry.example.com/myorg/myapp") tag.set("stable") } ``` -------------------------------- ### Save Docker Image to Archive Source: https://context7.com/bmuschko/gradle-docker-plugin/llms.txt Exports a Docker image to a tar archive file. Supports compression and is useful for air-gapped environments or artifact handoff. ```kotlin // build.gradle.kts import com.bmuschko.gradle.docker.tasks.image.DockerSaveImage import com.bmuschko.gradle.docker.tasks.image.DockerLoadImage tasks.create("saveImage", DockerSaveImage::class) { images.set(setOf("myorg/myapp:1.0.0")) destFile.set(layout.buildDirectory.file("distributions/myapp-1.0.0.tar")) useCompression.set(true) } ```