Linux GitLab如何实现自动化部署

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

在Linux上通过GitLab实现自动化部署,主要依赖于GitLab CI/CD(持续集成/持续部署)功能。以下是详细的步骤和说明:

1. 安装GitLab Runner

首先,需要在Linux服务器上安装GitLab Runner。以下是安装步骤:

  • CentOS
    1. 更新包列表:
      sudo yum update
      
    2. 安装依赖包:
      sudo yum install -y curl policycoreutils-python openssh-server
      
    3. 安装Postfix邮件服务器(用于邮件通知):
      sudo yum install postfix
      sudo systemctl enable postfix
      sudo systemctl start postfix
      
    4. 添加GitLab包仓库:
      curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
      
    5. 安装GitLab CE:
      sudo yum install -y gitlab-ce
      
    6. 自动配置GitLab:
      sudo gitlab-ctl reconfigure
      
    7. 启动GitLab服务:
      sudo gitlab-ctl start
      
    8. 注册GitLab Runner:
      curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh | sudo bash
      sudo yum install gitlab-runner
      
      安装完成后,需要将Runner的信息注册到GitLab中:
      sudo gitlab-runner register
      

2. 配置.gitlab-ci.yml文件

在项目根目录下创建或编辑.gitlab-ci.yml文件,定义自动化部署的流程。以下是一个简单的示例:

stages:
  - build
  - test
  - deploy

build_job:
  stage: build
  script:
    - mvn clean package

test_job:
  stage: test
  script:
    - mvn test

deploy_job:
  stage: deploy
  script:
    - scp target/*.jar user@your_server:/path/to/deploy
  only:
    - master

3. 配置免密登录

为了方便GitLab Runner通过SSH连接到目标服务器,需要配置免密登录:

  • 在GitLab Runner服务器上生成SSH密钥对:
    ssh-keygen
    
  • 将公钥复制到目标服务器:
    ssh-copy-id user@your_server
    
  • 将公钥添加到GitLab Runner的authorized_keys文件中:
    cat ~/.ssh/id_rsa.pub | ssh user@your_server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys"
    

4. 提交代码触发自动化部署

当在GitLab仓库中提交代码或合并请求时,GitLab CI/CD会自动触发Pipeline,按照.gitlab-ci.yml文件中定义的流程执行构建、测试和部署任务。

5. 注意事项

  • 确保防火墙允许GitLab使用的端口(默认是80和443)。
  • 在目标服务器上配置好Maven和JDK的环境变量。
  • 根据实际需求调整.gitlab-ci.yml文件中的配置。

通过以上步骤,你可以在Linux上通过GitLab实现自动化部署,大大提高开发和部署效率。

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

推荐阅读: linux集群服务器适用场景