以 egg.js 为例的持续集成(CI)、持续部署(CD)

2,763 阅读1分钟

poster

看这里

如何操作请看这里 视频分享链接地址
所有代码在这个地方 代码仓库

使用 TravisCI 配合 Shipit.js 进行自动化部署

  • TravisCI: 进行测试,代码覆盖率
  • Shipit:基于 JS 的部署引擎

这里贴出来一些关键性代码

创建 shipitfile.js

'use strict';

module.exports = function(shipit) {
  require('shipit-deploy')(shipit);

  shipit.initConfig({
    default: {
      workspace: '/tmp/github-monitor',
      deployTo: '/home/nono/app',
      repositoryUrl: 'https://github.com/MiYogurt/deploy-egg-sample.git',
      ignores: [ '.git', 'node_modules' ],
      rsync: [ '--del' ],
      keepReleases: 2,
      key: './scripts/source.key',
      shallowClone: true,
    },
    staging: {
      servers: 'root@139.199.227.41',
    },
  });

  shipit.task('docker', function() {
    return shipit.start([ 'build', 'remove', 'create' ]);
  });

  shipit.blTask('build', function() {
    return shipit.remote('docker build -t nodelover:v1 .', {
      cwd: '/home/nono/app/current',
    });
  });

  shipit.blTask('create', function() {
    return shipit.remote('docker run -d --name app -p 8080:7001 nodelover:v1', {
      cwd: '/home/nono/app/current',
    });
  });

  shipit.blTask('remove', function() {
    return shipit.remote('docker stop app', {
          cwd: '/home/nono/app/current',
        }).then(o => shipit.remote('docker rm app', {
          cwd: '/home/nono/app/current',
        })).catch(err => console.log("no need stop"))
    });
};

其实写 Shell 脚本也用不了几行,反而更简单些,只是需要一定的 linux 技能。

Dockerfile 容器化你的应用。

from node:9.2.0

add . /app

expose 7001

workdir /app

run npm i

cmd npm run start

.travis.yml

sudo: false
language: node_js
addons:
  ssh_known_hosts: xxx.xxx.xxx.xx
node_js:
  - '9'
before_install:
  - openssl aes-256-cbc -K $encrypted_b8bda4515144_key -iv $encrypted_b8bda4515144_iv -in scripts/source.key.enc -out scripts/source.key -d
install:
  - npm i npminstall && npminstall
# script:
#   - npm run ci
after_script:
  # - npminstall codecov && codecov
  - chmod 600 scripts/source.key
  - shipit staging deploy
  - shipit staging docker

就这 3 个核心文件,不花一分钱就可以实现基于 Docker 的 CI/CD, 当然普通的。

当然假如没有使用 Docker 的能力,回退到 PR 的那一个版本就可以了。