以 egg.js 為例的持續整合(CI)、持續部署(CD)

nodelover發表於2019-03-04

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 的那一個版本就可以了。

相關文章