Overview and What You Will Learn
GitLab CI/CD runs pipelines defined in a .gitlab-ci.yml file at the root of a repository. GitLab creates a pipeline for each push or merge request, splits it into ordered stages, and hands each job to a runner, which executes it and reports back. Source code, pipelines, container registry, and deployment tracking all live in one platform.
GitLab is common in organisations that self-manage their source control for compliance or data residency, and in teams that want the whole delivery toolchain under one roof.
By the end of this lab you will be able to:
- Write a complete
.gitlab-ci.ymlwith stages, reusable jobs, andrules - Avoid duplicate pipelines with
workflow:rules - Pass test results, coverage, and files between jobs with artifacts, and speed up jobs with cache
- Build and scan a container image, then deploy to Kubernetes with Helm and tracked environments
- Register and tune a self-hosted runner with the current token workflow
- Compare GitLab CI with GitHub Actions concept by concept
Why This Matters in Production
A pipeline definition that lives beside the code is reviewed, versioned, and rolled back like any other change. In GitLab, the pipeline also appears inside the merge request, so reviewers see test results, coverage, and security findings before they approve.
Where jobs run is a production decision as well. A runner inside the same network as your cluster can deploy to private endpoints, and a runner that is shared with every team cannot be trusted with production credentials. Platform teams at companies like Atlassian or Spotify design runner pools, protected variables, and environment rules as carefully as the pipeline itself.
Core Principles
A pipeline is a set of jobs grouped into stages. Jobs in the same stage run in parallel, and the next stage starts when all jobs of the previous one succeed. The needs keyword lets a job start as soon as the jobs it names finish, which turns stages into a faster directed graph.
How the main GitLab CI ideas map to GitHub Actions:
| GitLab CI | GitHub Actions |
|---|---|
.gitlab-ci.yml |
.github/workflows/*.yaml |
stages plus needs |
jobs.<id>.needs |
rules |
if conditions and on filters |
extends, include |
Reusable workflows, composite actions |
$CI_COMMIT_SHA, $CI_REGISTRY_IMAGE |
github.sha, registry env vars |
| Runners with tags | Runners with labels |
Detailed Step-by-Step Practical Lab
Step 1 - Define Stages, Workflow Rules, and a Reusable Base Job
Start with the order of stages, the workflow rules that decide when a pipeline exists at all, and a hidden job whose settings other jobs inherit with extends. Test comes first, so a broken change never reaches a build.
Without workflow:rules, a branch with an open merge request gets two pipelines for the same push: a branch pipeline and a merge request pipeline. The rules below keep one.
stages: - test - build - scan - deploy workflow: rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS when: never # the merge request pipeline covers this push - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH variables: IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA # Hidden job (starts with a dot): never runs, only provides settings.node-base: image: node:22-alpine cache: key: files: - package-lock.json # new cache only when dependencies change paths: - .npm/ before_script: - npm ci --cache .npm --prefer-offline # Run code jobs on the default branch, or when relevant files change.code-rules: rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH - changes: - src/**/* - package.json - package-lock.json - Dockerfile - .gitlab-ci.ymlCommon MistakeWriting
changes: ['**/*.md']withwhen: neverto "skip docs-only changes". Thechangesrule matches if any listed file changed, so any merge request that touches one Markdown file would skip the tests. List the paths that should trigger the job instead, as above.
Step 2 - Add Tests, Artifacts, and Coverage
Artifacts are files a job uploads for later jobs or for people. Cache is a best-effort speed-up that is not guaranteed to exist. The reports keys make GitLab show test results and coverage inside the merge request.
unit-tests: extends: [.node-base, .code-rules] stage: test script: - npm test -- --coverage --coverageReporters=text-summary --coverageReporters=cobertura coverage: '/Lines\s*:\s*(\d+\.?\d*)%/' # parsed from the job log artifacts: when: always # keep results even when tests fail expire_in: 1 week paths: - coverage/ reports: junit: junit.xml coverage_report: coverage_format: cobertura path: coverage/cobertura-coverage.xml lint: extends: [.node-base, .code-rules] stage: test script: - npm run lint - npm run format:checkTo make low coverage fail the job, set a threshold in the test runner's own config rather than a hand-written script. In Jest, add coverageThreshold to the Jest config, and the test command itself exits non-zero when coverage drops below it.
Step 3 - Build the Container Image
Docker-in-Docker (dind) lets a job run Docker commands inside a container. It requires a runner with privileged = true, and it works best with TLS left on. Pin the image versions, and pass the registry password on standard input so it is not visible in process lists.
build-image: extends: .code-rules stage: build image: docker:27 services: - docker:27-dind variables: DOCKER_TLS_CERTDIR: "/certs" script: - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY" - docker build -t "$IMAGE_NAME" . - docker push "$IMAGE_NAME"SecurityDo not bind-mount
/var/run/docker.sockinto job containers and usedindat the same time, and avoid the socket where you can. A job with the host's Docker socket can control the host. Prefer rootless BuildKit or a similar daemonless builder on shared runners.
Step 4 - Scan the Image for Vulnerabilities
The scan job pulls the image from the registry, so it needs registry credentials and must wait for the build. GIT_STRATEGY: none skips the repository checkout, which this job does not need.
trivy-scan: extends: .code-rules stage: scan image: name: aquasec/trivy:<pinned-version> entrypoint: [""] needs: [build-image] variables: GIT_STRATEGY: none TRIVY_USERNAME: $CI_REGISTRY_USER TRIVY_PASSWORD: $CI_REGISTRY_PASSWORD TRIVY_NO_PROGRESS: "true" script: - > trivy image --exit-code 1 --severity HIGH,CRITICAL --format json --output trivy-report.json "$IMAGE_NAME" artifacts: when: always expire_in: 1 week paths: - trivy-report.jsonStep 5 - Deploy to Kubernetes with Tracked Environments
An environment makes GitLab record every deployment, show it under Deploy > Environments, and link to its URL. The recommended way to reach a cluster is the GitLab agent for Kubernetes, which avoids storing a kubeconfig in a variable. The job selects the agent's context, then runs Helm.
.deploy-base: image: alpine/k8s:<pinned-version> # includes kubectl and helm stage: deploy script: - kubectl config use-context "$KUBE_CONTEXT" - > helm upgrade --install payment-api ./charts/payment-api --namespace "$NAMESPACE" --create-namespace --values "./charts/values-$CI_ENVIRONMENT_NAME.yaml" --set image.repository="$CI_REGISTRY_IMAGE" --set image.tag="$CI_COMMIT_SHA" --atomic --timeout 5m rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH deploy-staging: extends: .deploy-base needs: [trivy-scan] variables: KUBE_CONTEXT: payments/infra:staging-agent NAMESPACE: payment-api-staging environment: name: staging url: https://staging-api.razorpay.in deploy-production: extends: .deploy-base needs: [deploy-staging] resource_group: production # one production deploy at a time variables: KUBE_CONTEXT: payments/infra:production-agent NAMESPACE: payment-api-production environment: name: production url: https://api.razorpay.in rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH when: manual # a person clicks to release allow_failure: false # pipeline waits as blocked until then--atomic rolls the release back automatically if the upgrade fails, and resource_group serialises deploys so two pipelines never run Helm against production at once.
Step 6 - Add Review Environments for Merge Requests
A review environment gives each merge request its own temporary deployment. The stop job is linked through on_stop, and both jobs must use the same environment name.
deploy-review: stage: deploy script: - ./scripts/deploy-review.sh "$CI_MERGE_REQUEST_IID" environment: name: review/$CI_COMMIT_REF_SLUG url: https://review-$CI_MERGE_REQUEST_IID.razorpay.in on_stop: stop-review auto_stop_in: 1 week rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" stop-review: stage: deploy script: - ./scripts/teardown-review.sh "$CI_MERGE_REQUEST_IID" environment: name: review/$CI_COMMIT_REF_SLUG action: stop rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" when: manualStep 7 - Register a Self-Hosted Runner
Runner registration tokens are deprecated. The current flow creates the runner in GitLab first, which fixes its tags and settings there, and gives you an authentication token starting with glrt-. In the project, open Settings > CI/CD > Runners > New project runner, set tags such as docker and payment-vpc, then register with that token.
# Install GitLab Runner (review the repository script before running it)curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bashsudo apt install gitlab-runner # Register with the authentication token created in the UIsudo gitlab-runner register \ --non-interactive \ --url https://gitlab.company.in \ --token "$RUNNER_AUTH_TOKEN" \ --executor docker \ --docker-image alpine:3.20 \ --description payment-api-runner sudo gitlab-runner verifysudo gitlab-runner list# /etc/gitlab-runner/config.tomlconcurrent = 4 # jobs this host runs at once [[runners]] name = "payment-api-runner" url = "https://gitlab.company.in" executor = "docker" [runners.docker] image = "alpine:3.20" privileged = true # needed only for docker:dind jobs volumes = ["/cache"]Target the runner from a job with tags. Only runners that have all listed tags can pick the job up:
build-image: tags: - docker - payment-vpcProduction Best Practices & Common Pitfalls
| Mistake | Problem | Fix |
|---|---|---|
Using only and except |
Less capable, and not for new work | Use rules |
| Defining one job name twice | The last definition silently replaces the first | Use extends and unique job names |
No expire_in on artifacts |
Storage fills up | Set it on every artifact |
| Shared runner deploying to production | No network access, wide blast radius | Dedicated runner or the cluster agent |
| Cache key never changes | Stale dependencies | Key on the lockfile with cache:key:files |
latest image tags |
Pipeline changes without a commit | Pin image versions |
- Protect production variables. Mark them Protected so only protected branches and tags can read them, and Masked so they are redacted from logs.
- Prefer short-lived cloud credentials. Use the
id_tokenskeyword for OIDC federation with your cloud instead of stored keys. - Use
includeto share pipelines. Put common jobs in a shared project and include them, so a fix reaches every repository at once. - Set
interruptible: trueon test jobs. New pushes can then cancel outdated merge request pipelines. - Set job timeouts. A hung job should not hold a runner for the default hour.
TipValidate changes before pushing. Open the pipeline editor's Validate tab in the project, or run
glab ci lint. It reports syntax errors and unknown keywords, and shows which jobs a given pipeline would create.
RememberPredefined variables need no setup.
$CI_COMMIT_SHAis the commit,$CI_REGISTRY_IMAGEis the project's registry path, and$CI_DEFAULT_BRANCHis the default branch name. Use them instead of hardcoding.
Common MistakeLeaving
GIT_STRATEGYat its default on jobs that only need artifacts or an external image. Every job clones the repository, so setGIT_STRATEGY: nonewhere the source is not needed.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| View the current pipeline | glab ci view |
| Show a job's log | glab ci trace <job-id> |
| Retry a job | glab ci retry <job-id> |
| Check pipeline status | glab ci status |
| Validate the CI file | glab ci lint |
| Trigger via API | curl --request POST --header "PRIVATE-TOKEN: $TOKEN" "https://gitlab.company.in/api/v4/projects/<id>/pipeline?ref=main" |
| List runners on a host | sudo gitlab-runner list |
| Symptom | Likely Cause | Fix |
|---|---|---|
| Job stays "pending" | No runner matches the tags | Check tags and that the runner is online |
| Two pipelines per push | No workflow:rules |
Add the merge request rules from Step 1 |
dind fails to start |
Runner not privileged | Set privileged = true or change the builder |
| Pull fails in scan job | Registry credentials missing | Set TRIVY_USERNAME and TRIVY_PASSWORD |
| Tests skipped on docs edits only | Intended, via changes rules |
Confirm the paths list is correct |
--tag-list rejected at register |
Token type is the new glrt- token |
Set tags in the GitLab UI instead |