[英]Gradle task for Java playground
I am still new to Docker and Gradle, but I am trying to setup a Gradle build that builds a Docker image. 我仍然是Docker和Gradle的新手,但我正在尝试设置构建Docker镜像的Gradle构建。
I just finished setting up a Dockerfile
which locally deploys and runs the jar as expected. 我刚刚设置了一个
Dockerfile
,它在本地部署并按预期运行jar。 I have this in my build.gradle
: 我在
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. 我运行
./gradlew build buildDocker
来构建映像。 I am happy with this so far. 到目前为止,我很满意。
Usually I create a throwaway class (eg Playground.java
) with a main
method that I can run and disregard. 通常我创建一个一次性类(例如
Playground.java
),使用我可以运行和忽略的main
方法。 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. 通常我只是在IDE中运行它,但现在我希望能够连接到我知道将运行的其他Docker容器。
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: 我知道我可以尝试改变
sourceSets
我使用排除com.myapp.Main
,但我想象有可能是一个更优雅的解决方案类似这样的:
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
, eg ./gradlew playground buildDocker
. 另一种方法可能是在我调用
./gradlew build buildDocker
时使用另一个替换build
任务,例如./gradlew playground buildDocker
。 Is this more practical? 这更实用吗?
I would suggest replacing your hard coded main class with a gradle project property. 我建议用gradle项目属性替换你的硬编码主类。
jar {
manifest {
attributes 'Main-Class': main
}
}
Set that default property in your gradle.properties
file. 在
gradle.properties
文件中设置该默认属性。
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: 最后,当您需要构建使用运行
com.myapp.Playground
的jar的com.myapp.Playground
容器时,您可以使用以下com.myapp.Playground
调用gradle:
./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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.