由于自己的服务器普遍配置较低,在jenkins构建时会出现内存溢出的情况,这样的直接后果就是jenkins直接跪掉重启,项目构建失败。
对于普通的小项目,似乎够用,但是我有个项目,包含大约500MB静态图片,需要通过img-loader的几个插件进行图片压缩,压缩过程十分占用内存和cpu,使得服务器压力过大,于是在码云仓库爆仓(大于500MB)之际,我打算将仓库转移到github,并且jenkins+gitee的插件使用起来也不是那么清真,于是打算利用github actions的工作流引擎来实现项目自动构建部署,这里记录一下过程。
项目情况
- umijs3 的前端项目
- 项目中已存在dockerfile,docker-compose.yml文件
实现目标
- 代码提交后,自动下拉代码
- 下拉代码后执行yarn install 、yarn build 打包命令
- 使用docker将dist产物打包成docker镜像,内含nginx
- 将打包好的镜像push到远程私有仓库
- 将镜像通过docker- compose下拉最新镜像,并创建容器运行在远程服务器上
实现步骤
- 在根目录创建
.github/workflows
文件夹,创建build.yml
文件 - 创建如下内容
# This is a basic workflow to help you get started with Actions
name: Build
# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ master ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Build
uses: actions/setup-node@v2
with:
node-version: '14'
- run: yarn
- run: yarn build
- name: Login to DockerHub
uses: docker/login-action@v1
with:
registry: xxx.xxx.xxx
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Docker Build
uses: docker/[email protected]
with:
context: .
tags: xxx.xxx.xxx/1zilc/web:1.0.0
push: true
- name: Docker Compose Run
uses: wshihadeh/docker-deployment-action@v2
with:
remote_docker_host: [email protected]
ssh_public_key: ${{ secrets.SSH_PUBLIC_KEY }}
ssh_private_key: ${{ secrets.SSH_PRIVATE_KEY }}
args: up -d
这里用到5个关键actions
- actions/checkout@v2
github出品的action,用于获取源码
- actions/setup-node@v2
用于创建node环境,自带yarn等管理工具,使用此action,指定node版本,用于webpack构建
- docker/login-action@v1
docker官方出品,用来登录docker registry,如果指定registry则登录私有仓库
- docker/[email protected]
docker官方出品,使用此action,指定docker运行时上下文,用于docker镜像构建,默认配置为当前context下的dockerfile文件
同样也可以指定tags,是否push等更多信息
- wshihadeh/docker-deployment-action@v2
实现docker-compose各项功能的action,其中最重要的是指定参数
此时会在 ~/.ssh/known_hosts
中生成一条记录,此条记录作为ssh_public_key内容即可