使用Docker+GitLab+Jenkins自动化构建并发布项目
- 创建 Gitlab + Jenkins自动化工程 
- 在Gitlab项目中新建 - Dockerfile文件- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23- # build stage 
 FROM node:10 as build-stage
 # 设置是谁在维护这个项目
 LABEL maintainer=dragon0072@outlook.com
 # 创建一个工作目录
 WORKDIR /app
 # 把当前文件目录中的文件,copy到镜像中
 COPY . .
 # 安装依赖
 RUN yarn install --registry=https://registry.npm.taobao.org
 # 编译项目
 RUN npm run build
 # production stage
 FROM nginx:stable-alpine as production-stage
 # 将生成的项目文件,拷贝到nginx目录中
 COPY --from=build-stage /app/dist /usr/share/nginx/html
 # 暴露一个端口
 EXPOSE 80
 # 运行nginx
 CMD ["nginx", "-g", "daemon off;"]
- 添加 - .dockerignore文件,将不必要文件,排除- 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- # Dependency directory 
 # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
 node_modules
 .DS_Store
 dist
 # node-waf configuration
 .lock-wscript
 # Compiled binary addons (http://nodejs.org/api/addons.html)
 build/Release
 .dockerignore
 Dockerfile
 *docker-compose*
 # Logs
 logs
 *.log
 # Runtime data
 .idea
 .vscode
 *.suo
 *.ntvs*
 *.njsproj
 *.sln
 *.sw*
 pids
 *.pid
 *.seed
 .git
 .hg
 .svn- 注意 - 如果需要本地化测试 - 1 
 2
 3
 4- # 首先,打包成镜像 
 docker build -t <自定义镜像名称> .
 # 然后,运行这个镜像
 docker run -itd --name <自定义容器名称> -p 10000:80
 
- 配置 - Jenkins自动化脚本- 进入 - Jenkins任务
- 进入配置页面 
- 来到 - 构建选项卡,选择- 执行shell,并录入脚本- 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- 指定当前为shell脚本 
 !/bin/bash
 自定义两个参数
 ${container_name} 在jenkins任务中配置
 CONTAINER=${container_name}
 PORT=${port}
 完成镜像的构建
 docker build --no-cache -t ${image_name}:${tag} .
 进行资源处理,判断是否有同名容器,正在运行
 RUNNING=$(docker inspect --format="{{ .State.Running }}" $CONTAINER)
 if [ ! -n $RUNNING ]; then
 echo "$CONTAINER does not exit"
 return 1
 fi
 if [ "$RUNNING" == "false" ]; then
 echo "$CONTAINER is not running."
 return 2
 else
 echo "$CONTAINER is running"
 #delete same name container
 matchingStarted=$(docker ps --filter="name=$CONTAINER" -q | xargs)
 if [ -n $matchingStarted ]; then
 docker stop $matchingStarted
 fi
 
 matching=$(docker ps -a --filter="name=$CONTAINER" -q | xargs)
 if [ -n $matching ]; then
 docker rm $matching
 fi
 fi
 echo "RUNNING IS ${RUNNING}"
 运行镜像
 docker run -itd --name $CONTAINER -p $PORT:10083 ${image_name}:${tag}- 注意- ${container_name},- ${port},- ${image_name},- ${tag}在- Jenkins任务配置中,进行配置
 
 
- 注意
- 来到 - General选项卡- 勾选参数化构建过程
- 选择添加参数 > 字符参数
- 根据shell脚本中使用到的参数,进行配置
 
- 勾选
 - 来到Gitlab项目,进行一次提交,此时,项目会自动发布到服务器