GitLab CI/CD在Linux环境下如何搭建

451
2025/4/15 18:32:51
栏目: 智能运维
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Linux环境下搭建GitLab CI/CD涉及几个主要步骤,包括安装GitLab、配置GitLab Runner以及设置.gitlab-ci.yml文件。以下是详细的步骤指南:

安装GitLab

CentOS 7

  1. 下载GitLab CE安装包

    curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
    
  2. 安装依赖包

    sudo yum install -y curl policycoreutils-python openssh-serversudo systemctl enable sshdsudo systemctl start sshdsudo firewall-cmd --permanent --add-service=httpsudo systemctl reload firewalldsudo yum install postfixsudo systemctl enable postfixsudo systemctl start postfix
    
  3. 配置外部URL

    curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
    sudo EXTERNAL_URL="http://gitlab.example.com" yum install -y gitlab-ce
    
  4. 重启服务

    sudo gitlab-ctl reconfigure
    sudo gitlab-ctl start
    

CentOS 6

  1. 下载GitLab CE安装包

    curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
    
  2. 安装依赖包

    sudo yum install -y curl policycoreutils-python openssh-server cronieyum install lokkitsudo lokkit -s http -s sshsudo yum install postfixsudo service postfix startsudo chkconfig postfix on
    
  3. 配置外部URL

    curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
    sudo EXTERNAL_URL="http://gitlab.example.com" yum -y install gitlab-ce
    
  4. 重启服务

    sudo gitlab-ctl reconfigure
    sudo gitlab-ctl start
    

配置GitLab Runner

  1. 下载并安装GitLab Runner

    curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
    sudo apt-get install gitlab-runner
    
  2. 注册Runner

    sudo gitlab-runner register
    

设置.gitlab-ci.yml文件

在项目根目录下创建.gitlab-ci.yml文件,定义CI/CD流程:

stages:
  - build
  - test
  - deploy

build-job:
  stage: build
  script:
    - echo "编译构建中..."
    - mkdir -p build
    - touch build/info.txt

test-job:
  stage: test
  script:
    - echo "测试运行中..."
    - test -f build/info.txt

deploy-job:
  stage: deploy
  script:
    - echo "部署应用中..."
  only:
    - master

使用Docker优化CI环境

GitLab CI可以使用Docker容器来运行任务,这样可以避免为每个项目配置不同的环境:

test:
  image: node:14
  services:
    - postgres:13
  script:
    - npm test

防火墙配置

确保开放必要的端口,如SSH(默认22)、HTTP(默认80)和HTTPS(默认443):

sudo firewall-cmd --add-service=ssh --permanent
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-service=https --permanent
sudo firewall-cmd --reload

通过以上步骤,你可以在Linux环境下成功搭建GitLab CI/CD环境。初次登录时需要为GitLab的root用户设置密码。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Linux hostname中特殊字符处理方法