1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| //docker 配置信息 ext { docker = [ registry : 'xx.xxx.xxx', projectName: 'hello', imageName : project.name, apiUsername: 'xxx', apiPassword: 'xxx' ]
} /** * 构建 镜像 */ task buildImage(dependsOn: build) { ext.image = "${project.docker.registry}/${project.docker.projectName}/${project.docker.imageName}" doLast { println '执行开始' File buildDir = new File(".") //复制生成的文件 File source = jar.outputs.files.getFiles()[0] File target = new File(buildDir, source.name) target << source.bytes
//生成Dockerfile文件 def data = """FROM openjdk:8-jdk-alpine MAINTAINER lilei VOLUME /tmp ADD ${source.name} app.jar ENV JAVA_OPTS=\'\' ENTRYPOINT exec java \$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar """ println data
File file = new File(buildDir, 'Dockerfile') file.withWriter('utf-8') { writer -> writer.writeLine data }
//docker build -t ${IMAGE}:${VERSION} . //docker tag ${IMAGE}:${VERSION} ${IMAGE}:latest def cmdLine = ['docker', 'build', '-t', "${buildImage.image}:${project.docker.tag}", buildDir.toString()]
//清理文件 target.delete() file.delete()
//生成latest版本 cmdLine = ['docker', 'tag', "${buildImage.image}:${project.version}", "${buildImage.image}:latest"] executeAndWait(cmdLine)
//清理空版本号的镜像 //获取none版本镜像 try { Process process = "docker images -f dangling=true -q".execute() String useless = process.in.text if (!useless.isEmpty()) { cmdLine = ['docker', 'rmi'] cmdLine.addAll(useless.split("\n")) //执行删除 executeAndWait(cmdLine) } } catch (Exception e) { println '清理none版本镜像出错' } println '执行完成' }
} /** * 推送镜像 */ task pushImage(dependsOn: buildImage) { doLast { //登录
def cmdLine = ['docker', 'login', project.docker.registry, "-u", project.docker.apiUsername, '-p', project.docker.apiPassword] executeAndWait(cmdLine) def image = buildImage.image
//推送 cmdLine = ['docker', 'push', "${image}:${project.version}"] executeAndWait(cmdLine) //推送latest版本 cmdLine = ['docker', 'push', "${image}:latest"] executeAndWait(cmdLine) }
} /** * 执行命令 * @param cmdLine * @return */ private static String executeAndWait(List<String> cmdLine) { println("命令行:${cmdLine}") println '------------shell输出------------' def process = cmdLine.execute() process.waitForProcessOutput(System.out, System.err) println '-------------输出结束--------------' if (process.exitValue()) { throw new GradleException("执行命令出错 \nCommand line [${cmdLine}]") } return "success" }
|