> For the complete documentation index, see [llms.txt](https://xu-min-chang.gitbook.io/caster-develop-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xu-min-chang.gitbook.io/caster-develop-note/gitlab/jian-jie-gitlab-cicd.md).

# 簡介 GitLab CI/CD

### 什麼是 GitLab CI/CD？

GitLab CI/CD 是 GitLab 提供的持續集成 (Continuous Integration) 和持續部署 (Continuous Deployment) 功能。它允許開發團隊自動化地將程式碼整合、測試和部署到目標環境中，從而加快軟體開發週期，提高效率。

### GitLab CI/CD 的核心概念

1. **Pipeline（流水線）**：Pipeline 是一個自動化的工作流程，由一系列稱為 job 的任務組成。Pipeline 可以自動執行各種操作，例如編譯程式碼、運行測試、構建 Docker 鏡像、部署應用程式等。
2. **Runner（執行器）**：Runner 是實際執行 Pipeline 中 job 的代理程式。Runner 可以是 GitLab 提供的共享 Runner，也可以是自定義的 Runner。
3. **Job（任務）**：Job 是 Pipeline 中的一個步驟，代表一個具體的操作，例如編譯程式碼、運行測試、構建 Docker 鏡像、部署應用程式等。
4. **Stage（階段）**：Stage 是一組相關聯的 job 的集合，代表 Pipeline 中的一個階段。例如，可以有一個編譯階段包含所有編譯相關的 job。

### GitLab CI/CD 範例

以下是一個簡單的 GitLab CI/CD 範例，用於自動測試、構建和部署一個 Web 應用程式：

```yaml
# .gitlab-ci.yml

# 定義 Pipeline 中的階段
stages:
  - build
  - test
  - deploy

# 定義各階段中的 job
# 在每個 job 中，我們可以定義 script 欄位來指定要執行的指令
# 我們也可以使用不同的 image 來執行不同的操作
jobs:
  # 編譯程式碼
  build:
    stage: build
    script:
      - npm install
      - npm run build
    artifacts:
      paths:
        - build/
  
  # 執行測試
  test:
    stage: test
    script:
      - npm test
  
  # 部署到生產環境
  deploy:
    stage: deploy
    script:
      - docker build -t myapp .
      - docker tag myapp registry.example.com/myapp
      - docker push registry.example.com/myapp
    only:
      - master  # 只有在 master 分支上提交時才執行部署操作
```
