5. GitLab CI/CD Basics

Continuous Integration (CI) and Continuous Delivery (CD) are the core pillars of modern DevOps. GitLab includes an industry-leading, native CI/CD system. There are no plugins to install, no third-party servers to configure—just add a configuration file to your repository and push!

The Heart of the Pipeline: `.gitlab-ci.yml`

To activate GitLab CI/CD, you place a special file named .gitlab-ci.yml in the root directory of your project. This file is written in YAML syntax and defines the exact structure, order, and instructions of your pipeline.

Key Structural Concepts

  • Jobs: The smallest executable unit. A job defines *what* should be done (e.g. run a test suite, compile an application).
  • Stages: Groups of jobs that execute in sequential order. Standard stages are: `build`, `test`, and `deploy`.
  • Pipelines: The overall collection of jobs split across different stages. If any job in a stage fails, the pipeline halts (by default) and subsequent stages will not execute.

A Complete Example of a `.gitlab-ci.yml` File

Below is a professional, annotated GitLab CI/CD configuration file for a Node.js/React application:

# Define the default Docker image to run the jobs inside
default:
  image: node:18-alpine

# Define the sequence of stages
stages:
  - install
  - test
  - build
  - deploy

# Job 1: Install dependencies and save to cache
install_dependencies:
  stage: install
  script:
    - npm ci
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - node_modules/

# Job 2: Run Unit Tests
run_unit_tests:
  stage: test
  script:
    - npm test

# Job 3: Build application and save build folder as an artifact
build_app:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - build/
    expire_in: 1 week

# Job 4: Deploy to staging (executed only on the 'main' branch)
deploy_to_staging:
  stage: deploy
  script:
    - echo "Deploying build artifacts to staging server..."
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

Understanding Artifacts vs. Cache

It is easy to confuse these two critical concepts:

FeatureCache (`cache:`)Artifacts (`artifacts:`)
PurposeSpeed up pipeline execution (e.g., store downloaded packages like `node_modules`).Save files generated by a job to be passed to later stages or downloaded by users.
PersistenceBest-effort preservation. Can be deleted by the system at any time without pipeline failure.Guaranteed persistence. Uploaded to GitLab storage and accessible via the browser UI.
Transfer ScopeAvailable across different pipelines of the same project.Passed strictly from one stage to the next within the SAME pipeline.
YAML Linting Pro Tip: GitLab has a built-in CI/CD parser called CI Lint. You can find it under Build > Pipeline editor in the left sidebar of your repository. Use it to check for syntax errors before pushing changes to remote!