gitlab-ci
Configures GitLab CI/CD pipelines with stages, jobs, and GitLab Runner. Use for Git-native automation and deployment.
GitLab CI/CD
Git-integrated CI/CD with powerful pipeline orchestration.
Quick Start
stages:
- test
- build
- deploy
test:
stage: test
image: node:20
script:
- npm ci
- npm test
build:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/When to Use
- GitLab-hosted repositories
- Auto DevOps deployments
- Multi-project pipelines
- Container registry integration
Best Practices
- Name jobs clearly and keep each stage single-purpose.
- Cache dependencies and use `needs` for fast pipelines.
- Store secrets in CI/CD variables, masked and scoped.
- Use rules (not only/except) for branch-based triggers.
- Upload artifacts and reports for visibility.
- Reuse logic with `include` and templates.
Step-by-Step
1. Add `.gitlab-ci.yml` to repo root
2. Configure stages and jobs
3. Set up GitLab Runner
4. Push to trigger pipeline
5. Add caching and rules
6. Secure variables and deploy
Dependencies
# Local runner
gitlab-runner registerExamples
# Job with caching and rules
test:
stage: test
image: node:20
cache:
key: npm
paths: [node_modules/]
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
script:
- npm ci
- npm test# Reusable template via include
include:
- template: Security/SAST.gitlab-ci.yml
- local: /ci/deploy.gitlab-ci.yml
build-push:
stage: deploy
image:
name: gcr.io/kaniko-project/executor:debug
entrypoint: [""]
only:
- main
script:
# Rootless image build - no privileged docker:24-dind service needed,
# the executor runs inside an unprivileged container (Map 03 standard).
- /kaniko/executor
--context "$CI_PROJECT_DIR"
--dockerfile "$CI_PROJECT_DIR/Dockerfile"
--destination "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
--destination "$CI_REGISTRY_IMAGE:latest"
--cache=true
environment: productionResources
- [GitLab CI Docs](https://docs.gitlab.com/ee/ci)
Troubleshooting
- **Job stuck in pending** — runner has no tag match. Add `tags: [docker]`
to the job or register the runner with matching tags.
- **Pipeline fails on `npm ci`** — cache is stale. Clear the cache from
*CI/CD → Pipelines → Run pipeline* or bump the cache `key`.
- **Deploy stage skipped** — `only: [main]` blocks feature branches;
use `rules: [if: '$CI_COMMIT_BRANCH == "main"']` for finer control.
- **Runner runs as `sh`, not `bash`** — set `image` per job or use
POSIX-compatible script lines (`|| true`, no `set -o pipefail`).
Validation
1. Pipeline starts on commit
2. All stages execute in order
3. Deployments succeed
GitLab CI/CD
Git-интегрированный CI/CD с мощной оркестрацией пайплайнов.
Быстрый старт
stages:
- test
- build
- deploy
test:
stage: test
image: node:20
script:
- npm ci
- npm test
build:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/Когда использовать
- Репозитории на GitLab
- Auto DevOps деплой
- Мультипроектные пайплайны
- Интеграция с Container Registry
Лучшие практики
- Ясные имена jobs; одна задача на стадию.
- Кэшируйте зависимости и используйте `needs` для скорости.
- Секреты в CI/CD variables, masked и scoped.
- `rules` вместо only/except для триггеров по веткам.
- Загружайте артефакты и отчёты для видимости.
- Переиспользуйте логику через `include` и шаблоны.
Пошаговое руководство
1. Добавьте `.gitlab-ci.yml` в корень репозитория
2. Настройте стадии и jobs
3. Настройте GitLab Runner
4. Запушьте, чтобы запустить пайплайн
5. Добавьте кэш и rules
6. Обезопасьте переменные и деплой
Зависимости
# Локальный runner
gitlab-runner registerПримеры
# Job с кэшем и rules
test:
stage: test
image: node:20
cache:
key: npm
paths: [node_modules/]
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
script:
- npm ci
- npm test# Переиспользуемый шаблон через include
include:
- template: Security/SAST.gitlab-ci.yml
- local: /ci/deploy.gitlab-ci.yml
deploy:
stage: deploy
image: docker:24
services: [docker:24-dind]
only:
- main
script:
- docker build -t $CI_REGISTRY_IMAGE .
- docker push $CI_REGISTRY_IMAGE
environment: productionРесурсы
- [GitLab CI Docs](https://docs.gitlab.com/ee/ci)
Устранение неполадок
- **Job завис в статусе pending** — у runner не совпали теги. Добавьте
`tags: [docker]` в job или зарегистрируйте runner с нужными тегами.
- **Падение на `npm ci`** — устаревший кэш. Очистите кэш через
*CI/CD → Pipelines → Run pipeline* или обновите `key` у кэша.
- **Deploy-стадия пропущена** — `only: [main]` блокирует ветки;
используйте `rules: [if: '$CI_COMMIT_BRANCH == "main"']` для гибкости.
- **Runner работает на `sh`, а не `bash`** — задайте `image` каждому job
или пишите POSIX-совместимые команды (`|| true`, без `set -o pipefail`).
Валидация
1. Пайплайн стартует на коммит
2. Все стадии выполняются по порядку
3. Деплой проходит успешно