centos

CentOS与GitLab的持续集成实践

小樊
43
2025-05-06 21:06:16
栏目: 智能运维

在CentOS系统上结合GitLab实现持续集成(CI)和持续交付(CD)是一个常见的做法,可以大大提高软件开发的效率和质量。以下是一个详细的实践指南,涵盖了从环境准备到配置GitLab CI/CD管道的步骤。

环境准备

  1. 系统要求

    • CentOS 7.x 或更高版本
    • 2 GB 以上的RAM
    • 已安装 curlopenssh-server
  2. 安装必要的依赖

    sudo yum update -y
    sudo yum install -y curl policycoreutils-python openssh-server openssh-clients postfix wget vim
    
  3. 配置网络

    • 关闭防火墙和SELinux:

      sudo systemctl stop firewalld
      sudo sed -i 's/SELINUXenforcing/SELINUXdisabled/g' /etc/selinux/config
      sudo setenforce 0
      
    • 配置防火墙允许HTTP和HTTPS流量:

      sudo yum install firewalld -y
      sudo systemctl enable firewalld
      sudo systemctl start firewalld
      sudo firewall-cmd --permanent --add-service=http
      sudo firewall-cmd --permanent --add-service=https
      sudo firewall-cmd --reload
      
  4. 安装邮件服务(如Postfix),用于发送GitLab通知邮件:

    sudo yum install postfix -y
    sudo systemctl enable postfix
    sudo systemctl start postfix
    
  5. 配置GitLab

    • 添加GitLab的RPM镜像源并安装GitLab软件包:

      curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
      sudo yum install -y gitlab-ce
      
  6. 启动GitLab

    sudo gitlab-ctl reconfigure
    sudo gitlab-ctl start
    
  7. 访问GitLab

    通过浏览器访问GitLab管理界面,使用服务器IP地址和默认管理员账户(root)登录,首次登录会提示设置新密码。

配置GitLab CI/CD管道

  1. 创建 .gitlab-ci.yml 文件

    在项目根目录下创建 .gitlab-ci.yml 文件,定义CI/CD管道的各个阶段和作业。

    stages:
      - build
      - test
      - deploy
    
    build_job:
      stage: build
      script:
        - echo "Building the application..."
    
    test_job:
      stage: test
      script:
        - npm install
        - npm run test
    
    deploy_job:
      stage: deploy
      script:
        - scp -r ./build user@your_server_ip:/path/to/deploy
      only:
        - master
    
  2. 自动化测试

    .gitlab-ci.yml 文件中添加测试脚本,并配置测试报告生成:

    stages:
      - build
      - test
      - deploy
    
    test_job:
      stage: test
      script:
        - npm install
        - npm run test
      artifacts:
        reports:
          junit: test-results.xml
    

    使用测试报告生成工具(如Mochawesome)生成HTML测试报告:

    const mocha = require('mocha');
    const Mochawesome = require('mochawesome');
    const runner = new mocha({ reporter: Mochawesome, reporterOptions: { reportDir: 'report', reportFilename: 'index', quiet: true, }, });
    runner.addFile('test.js');
    runner.run();
    
  3. 触发CI/CD管道

    每次向Git仓库推送代码时,GitLab会自动触发CI/CD管道,执行定义的作业。

注意事项

通过以上步骤,您可以在CentOS系统上成功配置GitLab的持续集成和持续交付管道,实现高效的自动化软件开发流程。

0
看了该问题的人还看了