GitLab CI/CD – Complete Practical Guide

1. What is CI/CD?

CI/CD stands for:

  • CI – Continuous Integration
  • CD – Continuous Delivery / Continuous Deployment

Continuous Integration (CI)

Continuous Integration is a development practice where developers frequently push their code changes to a shared repository.

Whenever code is pushed, an automated pipeline can:

  1. Fetch the latest source code.
  2. Build or compile the application.
  3. Execute automated tests.
  4. Perform code quality and security checks.
  5. Report whether the changes passed or failed.

Example:

A team has three developers working on the same application.

  • Developer 1 pushes frontend changes.
  • Developer 2 pushes backend changes.
  • Developer 3 pushes database-related changes.

GitLab automatically triggers CI pipelines to validate these changes.

The objective is to identify problems early instead of discovering them after deployment.

Continuous Delivery

Continuous Delivery ensures that application code is automatically built, tested and prepared for release.

The final production deployment may require manual approval.

Continuous Deployment

Continuous Deployment automatically deploys successfully validated code to the target environment without requiring manual approval.


2. What is GitLab CI/CD?

GitLab CI/CD is a built-in automation feature of GitLab.

It helps developers automate application building, testing, security scanning and deployment.

GitLab uses a YAML configuration file to define the pipeline.

Default configuration filename:

.gitlab-ci.yml

Example project structure:

my-project/
│
├── index.html
├── install.sh
└── .gitlab-ci.yml

Whenever developers push changes to GitLab, the pipeline can be triggered automatically.


3. What is a Pipeline?

A pipeline is a collection of automated jobs executed in a defined sequence.

For example:

Developer pushes code
        |
        v
    GitLab
        |
        v
     Pipeline
        |
        v
      Build
        |
        v
       Test
        |
        v
     Security
        |
        v
      Deploy

Each stage performs a specific activity.


4. What are Stages?

Stages represent different phases of a pipeline.

Example:

stages:
  - build
  - test
  - security
  - deploy

Here we have four stages.

StagePurpose
buildCompile or build the application
testExecute automated tests
securityPerform security checks
deployDeploy the application

Important points

  1. Stages execute sequentially by default.
  2. The next stage starts after the previous stage succeeds.
  3. If a job fails, subsequent stages are skipped by default.
  4. Multiple jobs within the same stage can execute in parallel, depending on runner availability and configuration.

5. What are Jobs?

Jobs are individual tasks executed inside a pipeline.

Example:

stages:
  - build
  - test

build_frontend:
  stage: build
  script:
    - echo "Building frontend"

build_backend:
  stage: build
  script:
    - echo "Building backend"

test_application:
  stage: test
  script:
    - echo "Testing application"

Here we have:

StageJobs
buildbuild_frontend
buildbuild_backend
testtest_application

Important difference:

  • Stage = Logical phase.
  • Job = Actual task.
  • Script = Commands executed by the job.

Frontend and backend builds can execute in parallel because they belong to the same stage.


6. What is GitLab Runner?

GitLab Runner is an application that executes CI/CD jobs.

GitLab itself manages repositories and pipeline orchestration, while GitLab Runner executes the commands.

For example:

build_job:
  script:
    - echo "Building application"
    - mkdir dist
    - cp index.html dist/

Who executes these commands?

GitLab Runner.

GitLab CI/CD architecture

Developer
    |
    | Git Push
    v
GitLab Server
    |
    | Pipeline created
    v
GitLab Runner
    |
    | Executes jobs
    v
Build / Test / Security
    |
    v
Deployment

GitLab Runner communicates with GitLab to request jobs and report execution results.


7. Types of GitLab Runners

There are two common runner ownership models.

A. GitLab-hosted / Shared Runners

GitLab provides hosted runner infrastructure.

You don’t need to install or maintain your own runner machine.

Example:

build_job:
  script:
    - echo "Running on GitLab-hosted runner"

If an eligible hosted runner is enabled for your project, it can execute this job.

B. Self-hosted Runners

You install GitLab Runner on your own infrastructure.

Examples:

  • Ubuntu server
  • Rocky Linux server
  • Docker container
  • Virtual machine
  • Kubernetes environment

Advantages:

  1. Control over execution environment.
  2. Ability to install custom dependencies.
  3. Control over runner infrastructure.
  4. Useful for private network access.
  5. Can support specialized workloads.

8. What is an Executor?

An executor determines how and where GitLab Runner executes commands.

Common executors:

ExecutorExecution location
ShellDirectly on the runner machine
DockerInside a Docker container
KubernetesInside Kubernetes pods
SSHOn a remote machine over SSH

A. Shell Executor

If you register a runner with Shell executor:

Executor: shell

Commands execute directly on the Linux runner machine.

Example:

build_job:
  script:
    - hostname
    - whoami
    - echo "Building application"

If the runner is installed inside an Ubuntu Docker container, these commands execute inside that Ubuntu container.

B. Docker Executor

If you register a runner with Docker executor, jobs execute inside Docker containers.

Example:

build_job:
  image: ubuntu:latest
  script:
    - hostname
    - echo "Building application"

The Runner uses Docker to create the job’s execution container.

Shell vs Docker Executor

FeatureShellDocker
Docker requiredNoYes
IsolationLimitedBetter
ExecutionDirectly on LinuxInside container
SetupSimpleRequires Docker
EnvironmentRunner machineConfigured container image

Remember: The executor is configured when registering the runner. The image: keyword does not convert a Shell executor into a Docker executor.


9. How to Install GitLab Runner on Ubuntu

Update packages:

sudo apt update
sudo apt install -y curl

Add the official GitLab Runner repository:

curl -L \
  https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh \
  | sudo bash

Install:

sudo apt install -y gitlab-runner

Start service:

sudo systemctl enable --now gitlab-runner

Verify:

gitlab-runner --version
sudo systemctl status gitlab-runner

Register Runner

Go to:

GitLab Project → Settings → CI/CD → Runners → Create project runner.

Generate an authentication token.

On Ubuntu:

sudo gitlab-runner register

Enter the following:

GitLab URL:
https://gitlab.com

Token:
YOUR_RUNNER_TOKEN

Description:
ubuntu-runner

Tags:
linux-shell

Executor:
shell

Configuration is stored in:

/etc/gitlab-runner/config.toml

Verify:

sudo gitlab-runner list
sudo gitlab-runner verify

10. How Does GitLab Decide Which Runner Executes a Job?

GitLab uses runner eligibility and tags to select a runner.

Suppose you have three runners:

RunnerExecutorTag
Runner 1Shelllinux
Runner 2Dockerdocker
Runner 3Shellproduction

Example 1: Select Linux Runner

build_job:
  tags:
    - linux
  script:
    - echo "Running on Linux runner"

Example 2: Select Docker Runner

build_job:
  tags:
    - docker
  script:
    - echo "Running on Docker runner"

Example 3: Select Production Runner

deploy_job:
  tags:
    - production
  script:
    - echo "Running on production runner"

What if we don’t specify tags?

build_job:
  script:
    - echo "Hello World"

Any eligible runner configured to accept untagged jobs can execute it.

There is no guaranteed priority for self-hosted runners over shared runners.

Important: All tags specified in a job must match tags available on the selected runner.


11. First CI Pipeline – Hello World

Let’s create our first pipeline.

Create .gitlab-ci.yml:

stages:
  - build
  - test

build_job:
  stage: build
  script:
    - echo "Starting build..."
    - echo "Application built successfully"

test_job:
  stage: test
  script:
    - echo "Starting tests..."
    - echo "All tests passed"

Push to GitLab:

git add .
git commit -m "First CI pipeline"
git push origin main

Open:

GitLab → Build → Pipelines.

You should see:

Pipeline
   |
   v
Build Job
   |
   v
Test Job

12. Understanding Script Execution

Example:

test_job:
  stage: test
  script:
    - echo "Starting tests..."
    - exit 1
    - echo "Tests passed"

What happens?

  1. First command executes.
  2. Second command returns exit code 1.
  3. Job fails.
  4. Third command does not execute.

Understanding exit codes

Exit codeMeaning
0Success
1General failure
Non-zeroCommand failed

By default, GitLab treats a non-zero script exit status as a failed job.


13. Shell Scripting in CI/CD

We can execute shell scripts directly from GitLab pipelines.

Example project:

my-project/
│
├── index.html
├── install.sh
└── .gitlab-ci.yml

install.sh

#!/bin/bash

set -eo pipefail

echo "Hello World From install.sh"

cp index.html /tmp/

echo "Installed successfully"

Understanding Bash flags

set -e

Exit when a command fails.

set -o pipefail

A pipeline of commands fails if any command in the pipeline fails.

Combined:

set -eo pipefail

Execute from GitLab

build_job:
  stage: build
  tags:
    - linux-shell
  script:
    - chmod +x install.sh
    - ./install.sh

Important: Where does index.html go?

GitLab Runner checks out the repository into its job workspace.

The script copies:

cp index.html /tmp/

If using Shell executor, the file is copied into /tmp on the runner machine.

If the runner is installed inside an Ubuntu container, the file is copied into that container’s /tmp.


14. How to Control Pipeline Execution by Branch

Sometimes we want a job to execute only when code is pushed to a particular branch.

Use rules.

Example:

deploy_job:
  stage: deploy
  script:
    - echo "Deploying application"

  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

This job runs only for the main branch.

Multiple branches

test_job:
  stage: test
  script:
    - echo "Running tests"

  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
    - if: '$CI_COMMIT_BRANCH == "develop"'

15. What Happens When a Job Fails?

Suppose the pipeline has four stages:

stages:
  - build
  - test
  - security
  - deploy

Execution:

Build       SUCCESS
   |
   v
Test        FAILED
   |
   X
Security    SKIPPED
   |
   X
Deploy      SKIPPED

By default, later stages do not execute when an earlier stage fails.

This prevents unvalidated code from reaching deployment.


16. What are Artifacts?

Artifacts are files generated by one job that GitLab stores so that other jobs can use them.

Example:

Build job creates a dist directory.

build_job:
  stage: build
  script:
    - mkdir -p dist
    - cp index.html dist/

  artifacts:
    paths:
      - dist/
    expire_in: 1 day

Test job:

test_job:
  stage: test
  script:
    - ls -l dist/
    - cat dist/index.html

The test job receives the artifact from the build job.

Why do we need artifacts?

Jobs have separate workspaces. Files created by one job are not automatically available in another job.

Artifacts provide a mechanism to transfer build output between jobs.


17. Can We Create Multiple YAML Files?

Yes.

GitLab uses one main .gitlab-ci.yml file by default.

However, we can split the configuration into multiple files using include.

Example:

project/
│
├── .gitlab-ci.yml
│
└── pipelines/
    ├── build.yml
    ├── test.yml
    ├── security.yml
    └── deploy.yml

Main .gitlab-ci.yml:

include:
  - local: pipelines/build.yml
  - local: pipelines/test.yml
  - local: pipelines/security.yml
  - local: pipelines/deploy.yml

This improves maintainability for larger projects.


18. What is Deployment?

Deployment means releasing an application to a target environment.

Common environments:

  • Development
  • QA
  • Staging
  • Production

A simple deployment process:

Developer pushes code
       |
       v
GitLab CI Pipeline
       |
       v
Build Application
       |
       v
Run Tests
       |
       v
Security Checks
       |
       v
Deploy to Server
       |
       v
Application Available

Common deployment methods:

  1. SSH + SCP
  2. SSH + rsync
  3. Docker image deployment
  4. Kubernetes deployment
  5. Cloud deployment services

19. What is a Deploy Token?

A GitLab Deploy Token is a credential used by automation to access GitLab resources.

It can provide access to:

  • Private repositories
  • Container Registry
  • Package Registry

Create it from:

Project → Settings → Repository → Deploy Tokens.

Example scopes:

ScopePurpose
read_repositoryRead private repository
read_registryPull Docker images
write_registryPush Docker images
read_package_registryDownload packages
write_package_registryUpload packages

Using Deploy Token

Store credentials in:

Settings → CI/CD → Variables.

Example:

DEPLOY_USER
DEPLOY_TOKEN

Use them in your pipeline:

clone_job:
  stage: build
  script:
    - git clone https://${DEPLOY_USER}:${DEPLOY_TOKEN}@gitlab.com/USERNAME/PROJECT.git

Never hardcode secrets in your repository.

Important: Deploy Tokens are different from Runner Authentication Tokens, Personal Access Tokens and SSH keys.


20. GitLab CI/CD vs GitHub Actions

Both platforms provide CI/CD automation.

FeatureGitLab CI/CDGitHub Actions
Configuration.gitlab-ci.yml.github/workflows/*.yml
Execution agentGitLab RunnerGitHub Actions Runner
Hosted executionShared / instance runnersGitHub-hosted runners
Self-hosted executionYesYes
Runner selectionTagsLabels
Pipeline organizationStages and jobsWorkflows and jobs
Reusable configurationInclude / ComponentsReusable workflows / Actions

GitLab example

stages:
  - build
  - test

build_job:
  stage: build
  script:
    - echo "Building"

GitHub Actions example

name: CI Pipeline

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Build
        run: echo "Building"

21. Industry Best Practices

  1. Use separate build, test, security and deployment stages.
  2. Use appropriate runner tags to control execution.
  3. Use protected branches for production deployments.
  4. Store credentials in CI/CD variables.
  5. Never commit passwords, API keys or private keys.
  6. Use artifacts to transfer build output between jobs.
  7. Keep pipeline configurations modular as projects grow.
  8. Add automated tests before deployment.
  9. Implement rollback mechanisms.
  10. Use manual approvals where required for production.

22. Practical Assignments for the Team

Create a GitLab repository and complete the following exercises.

Basic CI Assignments

  1. Create a pipeline with build and test stages.
  2. Create two jobs inside the build stage.
  3. Execute a shell script from a GitLab pipeline.
  4. Intentionally fail a job using exit 1.
  5. Execute a job only on the main branch.
  6. Create a pipeline that runs on both main and develop branches.

Runner Assignments

  1. Install GitLab Runner on Ubuntu.
  2. Register a runner using Shell executor.
  3. Register a runner using Docker executor.
  4. Create two runners with different tags.
  5. Execute jobs using specific runner tags.
  6. Compare GitLab-hosted and self-hosted runners.

Advanced Assignments

  1. Pass build output between jobs using artifacts.
  2. Split pipeline configuration using multiple YAML files.
  3. Implement a basic security scanning stage.
  4. Create a Deploy Token and access a private repository.
  5. Build a Docker image and push it to GitLab Container Registry.
  6. Deploy a sample application to an Ubuntu server.

23. Useful References

Conclusion

GitLab CI/CD helps automate software development workflows. By using pipelines, stages, jobs and runners, development teams can build, test, validate and deploy applications consistently.

Start with a simple CI pipeline and gradually introduce automated testing, security scanning, Docker and deployment automation.