すべてのプロダクト
Search
ドキュメントセンター

:GitLab CIを使用してGitLabランナーを実行し、Kubernetesでパイプラインを実行する

最終更新日:Jan 23, 2025

このトピックでは、KubernetesクラスターにGitLabランナーをインストールして登録し、Kubernetesエグゼキュータを追加してアプリケーションを構築する方法について説明します。 このトピックでは、ソースコードのコンパイル、イメージのビルドとプッシュ、アプリケーションのデプロイなどのステージを含む継続的インテグレーション (CI)/継続的配信 (CD) パイプラインを実装するためのステップバイステップの例も提供します。

背景情報

次の例では、Javaプロジェクトがビルドされ、Container Service for Kubernetes (ACK) クラスターにデプロイされます。 この例では、GitLab CIを使用してGitLabランナーを実行し、Kubernetesエグゼキュータを設定し、CI/CDパイプラインを実行する方法を示します。

GitLabプロジェクトを作成してサンプルコードをアップロードする

  1. GitLabプロジェクトを作成します。
    この例では、作成されたGitLabプロジェクトのアドレス:
    http://xx.xx.xx.xx/demo/gitlab-java-demo.git
  2. 次のコマンドを実行してサンプルコードのコピーを作成し、そのコピーをGitLabにアップロードします。
    git clone https://github.com/haoshuwei/gitlab-ci-k8s-demo.git
    git remote add gitlab http://xx.xx.xx.xx/demo/gitlab-java-demo.git
    git push gitlab master

ACKクラスターにGitLab Runnerをインストールする

  1. GitLabランナーに関する登録情報を取得します。
    1. このプロジェクトのランナーに関する登録情報を取得します。
      1. GitLabコンソールにログインします。
      2. GitLabコンソールの上部ナビゲーションバーで、[プロジェクト] > [プロジェクト] を選択します。
      3. [プロジェクト] タブで、使用するプロジェクトを選択します。
      4. 左側のナビゲーションウィンドウで、[設定] > [CI / CD] を選択します。
      5. [Runners] の右側にある [Expand] をクリックします。
      6. URLと登録トークンをコピーします。
    2. グループランナーに関する登録情報を取得します。
      1. 上部のナビゲーションバーで、[グループ] > [グループ] を選択します。
      2. [グループ] タブで、必要なグループを選択します。
      3. 左側のナビゲーションウィンドウで、[設定] > [CI / CD] を選択します。
      4. [Runners] の右側にある [Expand] をクリックします。
      5. URLと登録トークンをコピーします。
    3. 共有ランナーに関する登録情報を取得します。
      説明 この手順を実行する権限を持つのは管理者だけです。
      1. 上部のナビゲーションバーで、をクリックして管理エリアページに移動します。
      2. 左側のナビゲーションウィンドウで、[概要] > [ランナー] を選択します。
      3. URLと登録トークンをコピーします。
  2. 次のコマンドを実行して、GitLab RunnerのHelmチャートのコピーを取得します。
    git clone https://github.com/haoshuwei/gitlab-runner.git
    次のコードに示すように、gitlabUrlフィールドとrunnerRegistrationTokenフィールドを置き換えます。
    ## GitLab Runner Image
    ##
    image: gitlab/gitlab-runner:alpine-v11.4.0
    
    ## Specify a imagePullPolicy
    ##
    imagePullPolicy: IfNotPresent
    
    ## Default container image to use for initcontainer
    init:
      image: busybox
      tag: latest
    
    ## The GitLab Server URL (with protocol) that want to register the runner against
    ##
    gitlabUrl: http://xx.xx.xx.xx/
    
    ## The Registration Token for adding new Runners to the GitLab Server. This must
    ## be retreived from your GitLab Instance.
    ##
    runnerRegistrationToken: "AMvEWrBTBu-d8czE****"
    ## Unregister all runners before termination
    ##
    unregisterRunners: true
    
    ## Configure the maximum number of concurrent jobs
    ##
    concurrent: 10
    
    ## Defines in seconds how often to check GitLab for a new builds
    ##
    checkInterval: 30
    
    ## For RBAC support:
    ##
    rbac:
      create: true
      clusterWideAccess: false
    
    ## Configure integrated Prometheus metrics exporter
    ##
    metrics:
      enabled: true
    
    ## Configuration for the Pods that that the runner launches for each new job
    ##
    runners:
      ## Default container image to use for builds when none is specified
      ##
      image: ubuntu:16.04
    
      ## Specify the tags associated with the runner. Comma-separated list of tags.
      ##
      tags: "k8s-runner"
    
      ## Run all containers with the privileged flag enabled
      ## This will allow the docker:dind image to run if you need to run Docker
      ## commands. Please read the docs before turning this on:
      ##
      privileged: true
    
      ## Namespace to run Kubernetes jobs in (defaults to the same namespace of this release)
      ##
      namespace: gitlab
    
      cachePath: "/opt/cache"
    
      cache: {}
      builds: {}
      services: {}
      helpers: {}
    
    resources: {}
  3. 次のコマンドを実行してGitLab Runnerをインストールします。
    • GitLab Runnerのヘルムチャートをパッケージ化します。
      helm package .

      期待される出力:

      Successfully packaged chart and saved it to: /root/gitlab/gitlab-runner/gitlab-runner-0.1.37.tgz
    • GitLab Runnerをインストールします。
      helm install --namespace gitlab gitlab-runner *.tgz
    関連するデプロイまたはポッドが開始されているかどうかを確認します。 関連するデプロイまたはポッドが開始されている場合、次の図に示すように、登録されたGitLabランナーがGitLabに表示されます。

キャッシュ設定

GitLab Runnerのキャッシュ容量は限られています。 キャッシュデータを保存するには、ボリュームをマウントする必要があります。 上記の例では、GitLab Runnerのインストール後、/opt/cacheディレクトリがデフォルトのキャッシュディレクトリとして使用されます。 values.yamlファイルのrunners.caのchePathフィールドを変更して、キャッシュディレクトリを変更できます。

たとえば、Apache Mavenのキャッシュを作成するには、MAVEN_OPTS変数をvariablesフィールドに追加し、ローカルキャッシュディレクトリを指定します。 次のコードは例です。
variables:
  KUBECONFIG: /etc/deploy/config
  MAVEN_OPTS: "-Dmaven.repo.local=/opt/cache/.m2/repository"
templates/configmap.yamlファイルの次のフィールドを変更して、docker.sockとキャッシュデータを保存するボリュームをマウントします。
cat >>/home/gitlab-runner/.gitlab-runner/config.toml <<EOF
            [[runners.kubernetes.volumes.pvc]]
              name = "gitlab-runner-cache"
              mount_path = "{{ .Values.runners.cachePath }}"
            [[runners.kubernetes.volumes.host_path]]
              name = "docker"
              mount_path = "/var/run/docker.sock"
              read_only = true
              host_path = "/var/run/docker.sock"
    EOF

グローバル変数の設定

  1. 上部のナビゲーションバーで、[プロジェクト] > [プロジェクト] を選択します。
  2. [プロジェクト] タブで、使用するプロジェクトを選択します。
  3. 左側のナビゲーションウィンドウで、[設定] > [CI / CD] を選択します。
  4. [変数] の右側にある [展開] をクリックします。 GitLab Runnerの環境変数を追加します。 この例では、次の変数を追加します。
    • REGISTRY_USERNAME: イメージリポジトリにログオンするためのユーザー名。
    • REGISTRY_PASSWORD: イメージリポジトリにログインするためのパスワード。
    • kube_config: エンコードされた文字列としてのKubeConfig。
    次のコマンドを実行して、KubeConfigをエンコードされた文字列に変換します。
    echo $(cat ~/.kube/config | base64) | tr -d " "

を編集します。gitlab-ci.ymlファイル

を使用します。Use the. gitlab-ci.ymlファイルを使用して、ソースコードをコンパイルし、イメージをビルドし、イメージをプッシュし、Javaデモプロジェクトのアプリケーションをデプロイします。 詳細については、を参照してください。gitlabci-java-demoプロジェクトのgitlab-ci.yml.example。

次のテンプレートは、. gitlab-ci.ymlファイル:
image: docker:stable
stages:
  - package
  - docker_build
  - deploy_k8s
variables:
  KUBECONFIG: /etc/deploy/config
  MAVEN_OPTS: "-Dmaven.repo.local=/opt/cache/.m2/repository"
mvn_build_job:
  image: maven:3.6.2-jdk-14
  stage: package
  tags:
    - k8s-runner
  script:
    - mvn package -B -DskipTests
    - cp target/demo.war /opt/cache
docker_build_job:
  image: docker:latest
  stage: docker_build
  tags:
    - k8s-runner
  script:
    - docker login -u $REGISTRY_USERNAME -p $REGISTRY_PASSWORD registry.cn-beijing.aliyuncs.com
    - mkdir target
    - cp /opt/cache/demo.war target/demo.war
    - docker build -t registry.cn-beijing.aliyuncs.com/haoshuwei24/gitlabci-java-demo:$CI_PIPELINE_ID .
    - docker push registry.cn-beijing.aliyuncs.com/haoshuwei24/gitlabci-java-demo:$CI_PIPELINE_ID
deploy_k8s_job:
  image: registry.cn-hangzhou.aliyuncs.com/haoshuwei24/kubectl:1.16.6
  stage: deploy_k8s
  tags:
    - k8s-runner
  script:
    - mkdir -p /etc/deploy
    - echo $kube_config |base64 -d > $KUBECONFIG
    - sed -i "s/IMAGE_TAG/$CI_PIPELINE_ID/g" deployment.yaml
    - cat deployment.yaml
    - kubectl apply -f deployment.yaml
. gitlab-ci.ymlファイルは、次のステージで構成されるパイプラインを定義します。
image: docker:stable  # By default, if no image is specified for each stage of the pipeline, the docker:stable image is used.
stages:
  - package                # Package the source code.
  - docker_build         # Build, package, and push the image.
  - deploy_k8s           # Deploy the application.
variables:
  KUBECONFIG: /etc/deploy/config   # Define the global variable KUBECONFIG.
  • Apache Mavenを使用してソースコードをパッケージ化します。
    mvn_build_job:     # The job name.
      image: maven:3.6.2-jdk-14  # The image that is used in this stage.
      stage: package      # The name of the stage.
      tags:                     # The tag of the GitLab Runner image.
        - k8s-runner
      script:
        - mvn package -B -DskipTests  # Run the build script.
        - cp target/demo.war /opt/cache  # Save the build output to cache.
  • 画像をビルド、パッケージ化、プッシュします。
    docker_build_job:  # The job name.
      image: docker:latest # The image that is used in this stage.
      stage: docker_build   # The name of the stage.
      tags:                      # The tag of the GitLab Runner image.
        - k8s-runner
      script:
        - docker login -u $REGISTRY_USERNAME -p $REGISTRY_PASSWORD registry.cn-beijing.aliyuncs.com   # Log on to the image repository.
        - mkdir target
        - cp /opt/cache/demo.war target/demo.war
        - docker build -t registry.cn-beijing.aliyuncs.com/haoshuwei24/gitlabci-java-demo:$CI_PIPELINE_ID .     # Package the Docker image. Use the pipeline ID as its tag.
        - docker push registry.cn-beijing.aliyuncs.com/haoshuwei24/gitlabci-java-demo:$CI_PIPELINE_ID      # Push the Docker image.
  • アプリケーションをデプロイします。
    deploy_k8s_job:   # The job name.
      image: registry.cn-hangzhou.aliyuncs.com/haoshuwei24/kubectl:1.16.6   # The image that is used in this stage.
      stage: deploy_k8s  # The name of the stage.
      tags:                      # The tag of the GitLab Runner image.
        - k8s-runner
      script:
        - mkdir -p /etc/deploy
        - echo $kube_config |base64 -d > $KUBECONFIG   # Configure the config file that is used to connect to the Kubernetes cluster.
        - sed -i "s/IMAGE_TAG/$CI_PIPELINE_ID/g" deployment.yaml  # Dynamically replace the image tag in the deployment file.
        - cat deployment.yaml
        - kubectl apply -f deployment.yaml

パイプラインの実行

を送信した後、. gitlab-ci.ymlファイルを使用すると、次の図に示すように、gitlab-java-demoプロジェクトがこのファイルを自動的に検出し、パイプラインを実行します。

アプリケーションへのアクセス

デフォルトでは、デプロイメントファイルに名前空間が指定されていない場合、アプリケーションはGitLab名前空間にデプロイされます。

 kubectl -n gitlab get svc 

期待される出力:

NAME        TYPE           CLUSTER-IP     EXTERNAL-IP      PORT(S)        AGE
java-demo   LoadBalancer   172.19.9.252   xx.xx.xx.xx   80:32349/TCP   1m

ブラウザを使用してxx.xx.xx.xx/demoにアクセスし、アプリケーションにアクセスします。

ACKの詳細については、「Container Service For Kubernetes」をご参照ください。

GitLab CIの詳細については、「GitLab CI」をご参照ください。