美文网首页
配置Gitlab CI 自动发布代码到生产环境

配置Gitlab CI 自动发布代码到生产环境

作者: Zeno00 | 来源:发表于2018-02-07 15:33 被阅读0次

    对于快速迭代的项目,经常发布版本是一个令人头痛的事情。
    Gitlab CI的功能和原理就不说了,网上可以找来看一看。
    这里只记录一下简单的步骤。:) 差点儿就成了从入门到放弃了。

    第一步:准备

    1.服务器生成ssh key,拷贝公钥


    gen_key.png

    2.在对应项目下添加部署密钥,填写上面的公钥,保存。


    ssh_pub_key.png

    3.在项目设置的【CI/CD流水线】配置页,记下CI的注册授权码和链接,如下

    2.png

    第二步:安装 Gitlab Runner

    由于目前使用的gitlab版本是8,所以下载的Gitlab CI Multi Runner
    下载地址 :Gitlab CI Multi Runner
    直接拷贝到服务器上,放在/usr/local/bin/路径下,开放执行权限chmod +x /usr/local/bin/gitlab-ci-multi-runner

    1.创建一个GitLab CI用户:

    sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash
    

    2.注册一个CI

    运行以下命令:

    sudo gitlab-ci-multi-runner register
    

    按照如下示例配置

    # 填写gitlab ci地址
    Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com )
    http://10.1.108.137/ci
    # 输入您获得的注册Runner的令牌:
    Please enter the gitlab-ci token for this runner
    8-zB8AX_*********_gF
    
    # 输入Runner的描述,你可以稍后在GitLab的UI中进行更改:
    Please enter the gitlab-ci description for this runner
    [hostame] my-runner
    
    # 输入与Runner关联的标签,稍后可以在GitLab的UI中进行更改:
    Please enter the gitlab-ci tags for this runner (comma separated):
    my-tag,another-tag
    deploy
    
    # 选择Runner是否应该选择没有标签的作业,可以稍后在GitLab的UI中进行更改(默认为false):
    Whether to run untagged jobs [true/false]:
    [false]: true
    
    
    选择是否将Runner锁定到当前项目,稍后可以在GitLab的UI中进行更改。Runner特定时有用(默认为true):
    
    Whether to lock Runner to current project [true/false]:
    [true]: true
    
    # 输入Runner执行者:
    Please enter the executor: ssh, docker+machine, docker-ssh+machine, kubernetes, docker, parallels, virtualbox, docker-ssh, shell:
    shell
    

    3.安装并作为服务运行

    sudo gitlab-ci-multi-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
    sudo gitlab-ci-multi-runner start
    

    4.开放执行权限给gitlab runner用户

    chown -hR gitlab-runner:gitlab-runner /app/software
    

    5.编写一个发布脚本deployuitp ,放在/usr/local/bin/目录下,

    # echo "更新代码...."
    cd `项目目录`
    git pull `接项目的gitlab地址`
    
    # build
    echo "构建前端...."
    cd frontend/
    cnpm install
    cnpm run build
    echo "构建成功...."
    # deploy
    echo "发布中...."
    cd .. && kill -9 `cat manage.pid`
    gunicorn manage:app -p manage.pid -w 4 -b 0.0.0.0:9000 -D
    
    echo "发布中成功!"
    

    添加脚本文件可执行权限chmod +x /usr/local/bin/deployuitp

    第三步:配置CI

    点击【项目】-【CI配置】,增加一个.gitlab-ci.yml文件,内容如下:

    stages:
      - deploy
    deploy:
        stage: deploy
        script:
          - deployuitp
        only:
          - master
        tags:
          - deploy
    

    OK,大工告成!以后每次master分支上有更新,就会自动触发CI来构建发布啦。

    sucess.png

    参考:
    [后端]gitlab之gitlab-ci自动部署
    官网指引
    使用.gitlab-ci.yml配置你的项目

    相关文章

      网友评论

          本文标题:配置Gitlab CI 自动发布代码到生产环境

          本文链接:https://www.haomeiwen.com/subject/sdaozxtx.html