GitLab CI/CD Best Practices: From Beginner to Production-Grade Pipelines

GitLab CI/CD is a core component of the DevOps toolchain. This article shares GitLab CI/CD best practices.

1. Pipeline Structure Design

stages:
  - lint
  - test
  - build
  - deploy

variables:
  DOCKER_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA

lint:
  stage: lint
  image: node:20
  script:
    - npm ci
    - npm run lint

test:
  stage: test
  image: node:20
  script:
    - npm ci
    - npm run test:ci
  coverage: '/Lines\s*:\s*(\d+\.\d+%)/'

2. Caching Strategy

cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - node_modules/
    - .npm/
  policy: pull-push

3. Multi-Environment Deployment

deploy-review:
  stage: deploy
  only:
    - merge_requests
  environment:
    name: review/$CI_MERGE_REQUEST_IID
    url: https://$CI_MERGE_REQUEST_IID.example.com
  script:
    - ./deploy-review.sh

deploy-production:
  stage: deploy
  only:
    - main
  when: manual
  environment:
    name: production
    url: https://example.com
  script:
    - ./deploy.sh

4. Security Scanning

include:
  - template: Jobs/SAST.gitlab-ci.yml
  - template: Jobs/Dependency-Scanning.gitlab-ci.yml
  - template: Jobs/Secret-Detection.gitlab-ci.yml