I am still new to Docker and Gradle, but I am trying to setup a Gradle build that builds a Docker image.
I just finished setting up a Dockerfile
which locally deploys and runs the jar as expected. I have this in my build.gradle
:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'se.transmode.gradle:gradle-docker:1.2'
}
}
plugins {
id 'com.github.johnrengelman.shadow' version '1.2.3'
}
apply plugin: 'docker'
jar {
manifest {
attributes 'Main-Class': 'com.myapp.Main'
}
}
task buildDocker(type: Docker, dependsOn: shadowJar) {
push = false
applicationName = jar.baseName
tagVersion = 'latest'
dockerfile = file('src/main/docker/Dockerfile')
copy {
from shadowJar
into stageDir
}
}
I run ./gradlew build buildDocker
to build the image. I am happy with this so far.
Usually I create a throwaway class (e.g. Playground.java
) with a main
method that I can run and disregard. Usually I just run this in the IDE, but now I would like to be able to connect to the other Docker containers that I know will be running.
I know I could try changing the sourceSets
I'm using by excluding com.myapp.Main
, but I was imagining there might be a more elegant solution resembling this:
task buildDockerPlayground(type: Docker, dependsOn: shadowJar) {
main = 'com.myapp.Playground'
push = false
applicationName = jar.baseName
tagVersion = 'latest'
dockerfile = file('src/main/docker/Dockerfile')
copy {
from shadowJar
into stageDir
}
}
Another approach might be to have another task that I use to replace build
when I call ./gradlew build buildDocker
, e.g. ./gradlew playground buildDocker
. Is this more practical?
I would suggest replacing your hard coded main class with a gradle project property.
jar {
manifest {
attributes 'Main-Class': main
}
}
Set that default property in your gradle.properties
file.
main=com.myapp.Main
Finally, when you need to build your docker container that uses a jar running
com.myapp.Playground
you can invoke gradle with:
./gradlew buildDocker -Pmain=com.myapp.Playground
Edit: To achieve the same thing in a task
project.ext.main = 'com.myapp.Main'
task play(){
project.main = 'com.myapp.Playground'
finalizedBy buildDocker
}
jar {
manifest {
attributes 'Main-Class': project.main
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With