devops项目开发过程中,为了统一前后端docker镜像的生成过程,统一用gradle构建。
依赖的软件:npm,gradle,harbor,jdk
本文介绍使用gradle构建前端应用需要的配置:
项目根目录添加以下四个文件
- settings.gradle
rootProject.name = 'devops-portal'//自行修改
ext{
//优先级低,各模块docker-build时会覆写该参数
dockerTag = "dev"
dockerGroup = "devops"
}
- build.gradle
buildscript {
repositories {
maven { url "http://.../repository/aliyun/" }
mavenCentral()
}
dependencies {
classpath "com.bmuschko:gradle-docker-plugin:3.2.1"
}
}
plugins {
id "com.moowork.node" version "1.1.1"
id 'java'
}
apply plugin: 'com.bmuschko.docker-java-application'
dependencies{
compile group: 'org.gradle', name: 'gradle-tooling-api', version: '4.3'
}
buildDir="frontend"
//调用npm run build命令的Gradle任务
task npmBuild(type: NpmTask, dependsOn: npmInstall) {
group = 'node'
args = ['run', 'build']
}
//调用npm run dev
task npmDev(type: NpmTask, dependsOn: npmInstall) {
group = 'node'
args = ['run', 'dev']
}
task cleanDocker(type: Delete) {
delete fileTree("${buildDir}/docker") {
include '**/*'
}
}
task copyDockerfile(type: Copy) {
group = "docker"
dependsOn cleanDocker,npmBuild
from "./dist","Dockerfile","default.conf"
into "${project.buildDir}/docker"
}
docker{
registryCredentials {
url = 'http://docker-daemon:5678'
username = 'devops-user'
password = 'devops-user-passwd'
}
}
import com.bmuschko.gradle.docker.tasks.image.*
task buildImage(type: DockerBuildImage) {
dependsOn copyDockerfile
def destFile = file("frontend/docker/Dockerfile")
group = "docker"
inputDir = destFile.parentFile
tags = [
"harbor.anji-allways.com/${dockerGroup}/${project.name}:${dockerTag}".toString()
]
}
task tagImage(type: DockerTagImage,dependsOn: buildImage){
imageId = ''
repository = "harbor.anji-allways.com/${dockerGroup}/${project.name}"
tag = "${dockerTag}"
doFirst{
imageId = buildImage.getImageId()
}
}
task pushImage(type: DockerPushImage,dependsOn: tagImage){
imageName = tagImage.repository
tag = tagImage.tag
}
- Dockerfile
FROM harbor.anji-allways.com/library/nginx:1.10
MAINTAINER owner@anji-allways.com.cn
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY ./ /data/work/devops/
COPY ./default.conf /etc/nginx/conf.d/
ENV PORT 80
CMD ["nginx","-g","daemon off;"]
- nginx-config: default.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
access_log /var/log/nginx/access.log main;
location / {
error_page 404 /index.html;
root /data/work/devops;
index index.html index.htm;
}
#error_page404/404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504/50x.html;
location = /50x.html {
root html;
}
}
开发环境 docker部署应用
1、生成镜像并上传:
gradle pushImage -xTest -PdockerTag=dev1.0.3 -PdockerGroup=devops
2、在开发服务器上执行如下命令:
docker stop devops-portal && docker rm devops-portal
docker run -p 8081:80 --name devops-portal harbor.anji-allways.com/devops/devops-portal:dev1.0.3 &
3、访问 http://ip:8081/