MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

GitLab CI/CD Getting Started Guide: Build Your First Automated Pipeline

1. Introduction: Your First Step Into GitLab CI/CD

Software development becomes significantly slower and more error-prone when teams rely on manual steps to build, test, and release code. Every time a developer copies files to a server by hand, forgets to run a test suite before merging changes, or struggles with environment mismatches between their laptop and a staging server, valuable engineering time is lost. Continuous Integration and Continuous Delivery (CI/CD) solve these challenges by automating the path from code commit to working software.

GitLab CI/CD is a built-in automation engine integrated directly into the GitLab platform. Rather than stitching together separate version control tools, external build servers, and third-party deployment scripts, GitLab allows you to define your entire software delivery workflow inside your repository. Whether you are exploring DevOps practices independently or building foundational automation skills through structured learning resources like DevOpsSchool, mastering GitLab CI/CD is one of the most practical ways to understand modern software engineering.

In this GitLab CI/CD Getting Started Guide, you will move from basic concepts to a complete, working automation workflow. By following the steps in this tutorial, you will prepare a sample Node.js web application, verify runner availability, write your first .gitlab-ci.yml configuration file, automate unit tests, save build outputs, manage environment variables, and simulate a deployment to a staging environment.

2. Get Familiar With the GitLab Environment

Before writing configuration files, it helps to understand where CI/CD lives inside the GitLab user interface. GitLab organizes software projects around repositories and surrounds them with collaboration, security, and automation tools.

Key Areas of a GitLab Project

  • GitLab Projects and Repositories: A project is the top-level container for your work. Inside it sits your Git repository, which stores your application source code, documentation, and CI/CD configuration files.
  • Branches and Commits: Branches isolate lines of development, such as a main branch for stable code and feature branches for new work. Every commit pushed to a branch acts as a potential trigger for automated checks.
  • Merge Requests (MRs): When a developer finishes work on a feature branch, they open a merge request to propose merging those changes into main. GitLab displays pipeline test results directly inside the merge request so reviewers know whether the new code breaks existing functionality.
  • Pipeline Interface: Located under Build > Pipelines in the left sidebar, this dashboard lists every automated workflow run, who triggered it, which branch it ran on, and whether it passed or failed.
  • CI/CD Configuration: Under Build > Pipeline editor, GitLab provides a browser-based YAML editor with built-in syntax validation and visual pipeline previews.
  • Project Settings: Located under Settings > CI/CD, this section lets you configure runners, manage secret variables, set artifact retention rules, and control pipeline permissions.

GitLab CI/CD vs. GitLab Runner

A common point of confusion for beginners is the difference between GitLab CI/CD and GitLab Runner. Although they work together tightly, they perform distinct roles:

ComponentPrimary RoleWhere It Lives
GitLab CI/CDThe coordinator and brain. It reads your .gitlab-ci.yml file, decides which jobs need to run, schedules them in order, and displays logs and statuses in the web interface.Inside the GitLab server/platform itself.
GitLab RunnerThe worker agent. It polls GitLab for queued jobs, checks out your code, executes the shell commands defined in your jobs, and reports the results back to GitLab.On separate compute machines (cloud VMs, containers, or dedicated servers) managed by GitLab or your team.

Think of GitLab CI/CD as the project manager assigning tasks and GitLab Runner as the technician executing those tasks on a workstation. Without an active runner, GitLab CI/CD can schedule a pipeline, but no jobs will ever execute.

3. Understand the Building Blocks Before Starting

GitLab CI/CD uses a clear hierarchy of concepts to organize automation. Understanding these eight terms will make reading and writing pipeline configurations straightforward.

  • Pipeline: The top-level automated workflow triggered by an event, such as pushing a commit or opening a merge request.
  • Stages: Logical phases within a pipeline that execute sequentially. Common stages include build, test, and deploy. All jobs in one stage must succeed before the next stage begins.
  • Jobs: Individual units of work defined inside a stage. For example, a test stage might contain two jobs running in parallel: unit_tests and lint_check.
  • Scripts: The actual command-line instructions (such as npm install or npm test) executed by the runner inside a job.
  • Runners: The agents that pick up jobs and execute their scripts inside isolated environments.
  • Artifacts: Files or directories generated by a job (such as compiled binaries, packaged archives, or test reports) that GitLab saves and passes to subsequent stages or makes available for download.
  • Cache: Temporary storage used to speed up future pipeline runs by preserving downloaded dependencies (like node_modules or Python virtual environments) between executions.
  • CI/CD Variables: Key-value pairs injected into job environments at runtime, allowing you to store configuration values, API endpoints, and secret credentials outside your source code.

How Code Moves Through a Pipeline

Imagine a developer fixes a bug in a web application and pushes the commit to GitLab:

  1. Build Stage: GitLab triggers a pipeline. A runner picks up the build_app job, installs dependencies, compiles the code, and saves the compiled output as an artifact.
  2. Test Stage: Because the build succeeded, GitLab moves to the test stage. A runner downloads the build artifact and runs automated unit tests using CI/CD variables to configure the test database connection.
  3. Deploy Stage: Once all tests pass, GitLab starts the deploy stage. A runner takes the verified artifact and deploys it to a staging server.

4. Prepare Your First Practice Project

To make this tutorial easy to follow and reproduce, we will use a lightweight Node.js task-tracker API as our consistent sample application throughout the guide. Even if you primarily work with Python, Java, or Go, the GitLab CI/CD concepts remain identical.

Step 1: Access GitLab and Create a New Project

  1. Log in to your GitLab account (either on GitLab.com or your organization’s self-managed GitLab instance).
  2. Click the + icon in the top navigation bar or select New project from your dashboard.
  3. Choose Create blank project.
  4. Name the project gitlab-cicd-starter.
  5. Set the Visibility Level to Private.
  6. Ensure Initialize repository with a README is checked, which automatically sets main as your default branch.
  7. Click Create project.

Step 2: Understand Basic Repository Permissions

In GitLab, your project role determines what actions you can take with pipelines:

  • Developer: Can push code to non-protected branches, trigger pipelines, and view job logs.
  • Maintainer: Can modify CI/CD settings, configure runners, manage protected branches, and create protected CI/CD variables.

Because you created this practice project, you automatically hold the Owner role, giving you full administrative access.

Step 3: Add Sample Application Code

Create three small files in the root of your repository (either via the GitLab web IDE or by cloning the repository locally and pushing):

1. package.json (defines project metadata, dependencies, and scripts):

JSON

{
  "name": "gitlab-cicd-starter",
  "version": "1.0.0",
  "description": "Sample application for learning GitLab CI/CD",
  "main": "app.js",
  "scripts": {
    "test": "node --test app.test.js",
    "build": "node build.js"
  }
}

2. app.js (our core application module):

JavaScript

function formatTask(title, completed = false) {
  if (!title || typeof title !== 'string') {
    throw new Error('Task title must be a non-empty string');
  }
  return {
    title: title.trim(),
    status: completed ? 'DONE' : 'PENDING'
  };
}

module.exports = { formatTask };

3. app.test.js (automated unit tests using Node’s built-in test runner):

JavaScript

const test = require('node:test');
const assert = require('node:assert');
const { formatTask } = require('./app');

test('formats a pending task properly', () => {
  const result = formatTask('  Learn GitLab CI/CD  ');
  assert.deepStrictEqual(result, {
    title: 'Learn GitLab CI/CD',
    status: 'PENDING'
  });
});

test('throws an error when title is empty', () => {
  assert.throws(() => formatTask(''), /Task title must be a non-empty string/);
});

4. build.js (a simple build script that packages our application into a dist/ folder):

JavaScript

const fs = require('node:fs');
const path = require('node:path');

const distDir = path.join(__dirname, 'dist');
if (!fs.existsSync(distDir)) {
  fs.mkdirSync(distDir);
}

fs.copyFileSync(path.join(__dirname, 'app.js'), path.join(distDir, 'app.js'));
fs.writeFileSync(
  path.join(distDir, 'build-info.json'),
  JSON.stringify({ builtAt: new Date().toISOString(), version: '1.0.0' }, null, 2)
);

console.log('Build completed successfully. Output written to dist/.');

Notice that this sample project requires zero external third-party packages yet supports realistic npm run build and npm test workflows.

5. Check Runner Availability

Before creating your pipeline configuration, verify that your project has access to an active GitLab Runner.

Runner Options and Executors

  • GitLab-Hosted Runners (Instance Runners): If you use GitLab.com, pre-configured runners are already available to execute your jobs immediately. They run inside fresh, isolated virtual machines or containers for each job.
  • Self-Managed Runners: Organizations hosting their own GitLab instances—or teams needing access to internal networks, specialized hardware, or custom software—install the GitLab Runner binary on their own servers.
  • Executors: Every runner uses an executor to determine how jobs run. The Docker executor is the most common because it launches a clean container image (such as node:20-alpine) for every job, ensuring reproducible environments. Other executors include Shell (runs directly on the host machine) and Kubernetes (spins up pods in a cluster).

How to Check Runner Status

  1. Inside your gitlab-cicd-starter project, navigate to Settings > CI/CD.
  2. Expand the Runners section.
  3. Look under Instance runners (or Project runners / Group runners).
  4. Confirm that at least one runner displays a green circle next to its name, indicating it is online and ready to accept jobs.

When a Project Needs Its Own Runner

You typically rely on shared or instance runners for standard builds and tests. You should register a dedicated project runner when:

  • Your jobs require access to firewalled internal databases or staging servers.
  • Your builds demand high CPU, memory, or GPU resources not available on shared pools.
  • Compliance policies prohibit running build workloads on shared infrastructure.

If no green runner appears in your project settings, any pipeline you trigger will remain stuck in a Pending state until a runner is enabled or registered.

6. Create the First .gitlab-ci.yml File

GitLab CI/CD looks for a single file named .gitlab-ci.yml in the root directory of your repository. Note the leading dot in the filename and the .yml extension.

Step-by-Step Creation

  1. In your GitLab project, go to Code > Repository.
  2. Click the + dropdown next to your branch name (main) and choose New file.
  3. Enter .gitlab-ci.yml as the Filename.
  4. Paste the following minimal working configuration into the editor:

YAML

default:
  image: node:20-alpine

stages:
  - build
  - test

build_application:
  stage: build
  script:
    - echo "Starting application build..."
    - npm run build

test_application:
  stage: test
  script:
    - echo "Running automated unit tests..."
    - npm test
  1. Scroll down, enter a commit message such as Add initial .gitlab-ci.yml pipeline, and click Commit changes.

How This Configuration Works

  • default: image: node:20-alpine: Tells the Docker runner to pull a lightweight Node.js 20 container image for every job in the pipeline so node and npm commands are available.
  • stages: Declares the sequential order of execution. GitLab will run all jobs assigned to build first, followed by all jobs assigned to test.
  • build_application and test_application: These are custom job names. You can name jobs descriptively to reflect what they do.
  • stage: Links each job to one of the declared stages.
  • script: A YAML list (indicated by - ) of shell commands executed in order. YAML relies strictly on 2-space indentation—never use tab characters, or GitLab will reject the file as invalid.

As soon as you commit .gitlab-ci.yml, GitLab automatically detects the file and triggers your first pipeline.

7. Follow the Pipeline From Start to Finish

Navigate to Build > Pipelines in the left sidebar to watch your pipeline run in real time.

Reading the Pipeline Interface

  • Pipeline Status: Displayed as a badge on the left of each row. Common statuses include:
    • Pending: Waiting for an available runner.
    • Running: Currently executing jobs on a runner.
    • Passed (green checkmark): Every required job succeeded.
    • Failed (red X): At least one job exited with a non-zero error code.
  • Pipeline Graph: Click the pipeline status badge (e.g., #1049281) to open the visual pipeline graph. You will see columns representing your stages (build on the left, test on the right) with job pills inside each column.
  • Stage Order Execution: Observe that test_application stays in a Created or Waiting state until build_application turns green. If build_application fails, GitLab stops the pipeline immediately and skips the test stage.
  • Inspecting Job Logs: Click directly on the build_application job pill to open its terminal log. You will see the runner pulling the node:20-alpine image, cloning your repository at the exact commit SHA, executing npm run build, and printing Job succeeded at the bottom.

How to Identify the First Failing Job

When a larger pipeline fails, avoid guessing what broke:

  1. Open the failed pipeline graph.
  2. Scan from left to right across the stages to locate the earliest red Failed job badge.
  3. Click that job to open its terminal output and scroll to the bottom (or search for ERROR or exit code 1) to see the exact command that failed.

8. Add Automated Testing to the Workflow

Running unit tests automatically on every commit catches bugs before they reach shared branches. Let’s enhance our test stage so it installs dependencies cleanly (when a package-lock.json is present), runs tests, and generates a machine-readable test report that GitLab can display directly in merge requests.

Update your app.test.js and .gitlab-ci.yml so Node outputs JUnit XML test reports, which GitLab parses natively:

YAML

default:
  image: node:20-alpine

stages:
  - build
  - test

build_application:
  stage: build
  script:
    - npm run build

unit_tests:
  stage: test
  script:
    - node --test --test-reporter=junit --test-reporter-destination=junit.xml app.test.js
  artifacts:
    when: always
    reports:
      junit: junit.xml

Key Testing Concepts Explained

  • Installing Dependencies: In projects with third-party libraries in package.json, add npm ci (clean install from package-lock.json) before running your test command. npm ci is faster and stricter than npm install in CI environments.
  • Handling Test Failures: Whenever a test assertion fails, the test runner exits with a non-zero exit code (such as 1). GitLab immediately marks the unit_tests job as Failed and prevents subsequent stages (such as deploy) from running.
  • Publishing Test Reports: Adding artifacts: reports: junit: junit.xml with when: always ensures that even if a test fails, GitLab uploads the XML report. You can then click the Tests tab on the pipeline page to inspect individual test pass/fail counts and error stack traces without digging through raw console logs.

9. Save and Reuse Build Outputs

Each job in GitLab CI/CD starts in a clean workspace. That means the dist/ directory generated by build_application disappears as soon as that job finishes unless you explicitly preserve it. GitLab provides two distinct mechanisms for managing files across jobs: Artifacts and Cache.

Artifacts vs. Cache: Understanding the Difference

Beginners often confuse artifacts and caches because both store files. However, they serve opposite purposes:

FeatureArtifactsCache
PurposePass build outputs (compiled code, binaries, reports) between stages within the same pipeline.Speed up future pipelines by reusing downloaded dependencies (node_modules, .pip) across separate pipeline runs.
ReliabilityGuaranteed delivery to downstream jobs in later stages.Best-effort optimization; jobs must still work if a cache is missing or cleared.
Downloadable in UI?Yes, users can download artifacts from the pipeline interface.No, caches are internal to runners.
ExpirationControlled via expire_in (e.g., 1 week or 30 days).Managed automatically by runner cache keys and policies.

Sharing Build Artifacts Between Jobs

Here is how to configure build_application to save the dist/ directory as an artifact and verify its presence in a downstream job:

YAML

default:
  image: node:20-alpine

stages:
  - build
  - test

build_application:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 week

unit_tests:
  stage: test
  script:
    - ls -la dist/
    - node --test app.test.js

When unit_tests starts, GitLab automatically downloads all artifacts from the preceding build stage before running script. Running ls -la dist/ confirms that app.js and build-info.json created during the build stage are ready for testing or packaging. Setting expire_in: 1 week keeps your GitLab storage clean by automatically removing temporary practice artifacts after seven days.

10. Manage Pipeline Settings and Variables

Hardcoding server addresses, environment names, or API keys directly inside .gitlab-ci.yml is both inflexible and dangerous—anyone with read access to your repository could view your credentials in Git history. CI/CD variables solve this problem by injecting values dynamically at runtime.

Types of CI/CD Variables

  • Predefined Variables: GitLab automatically injects dozens of built-in variables into every job, such as $CI_COMMIT_BRANCH (the current branch name), $CI_COMMIT_SHORT_SHA (the 8-character commit hash), and $CI_PROJECT_NAME.
  • Project and Group Variables: Custom variables configured in the GitLab UI under Settings > CI/CD > Variables. Group variables are inherited by all projects inside a GitLab group.

Protecting and Masking Sensitive Credentials

When creating custom variables in Settings > CI/CD > Variables, GitLab provides two critical security flags:

  • Protected: The variable is only exposed to pipelines running on protected branches (like main) or protected tags. Feature branches cannot access production secrets.
  • Masked: GitLab automatically scrubs the variable’s value from job logs, replacing it with [MASKED] so sensitive tokens are never printed in terminal output.

Example: Using Variables Safely in a Job

Suppose you add a custom variable named STAGING_API_TOKEN (marked Protected and Masked) in your project settings. You can reference it alongside predefined variables in .gitlab-ci.yml:

YAML

check_environment:
  stage: test
  variables:
    APP_ENV: "staging"
  script:
    - echo "Deploying project $CI_PROJECT_NAME on branch $CI_COMMIT_BRANCH"
    - echo "Target environment is $APP_ENV"
    - echo "Token length check passed"

Notice that APP_ENV is defined directly in YAML because "staging" is non-sensitive, while STAGING_API_TOKEN stays safely stored in GitLab’s encrypted project settings.

11. Introduce Deployment With GitLab CI/CD

Once your application builds cleanly and passes automated tests, the final phase of a basic CI/CD pipeline is deploying the build artifact to a target environment.

Learning Lab vs. Production Deployments

In a practice lab, you often do not have a live cloud server connected to GitLab, so you simulate deployment steps (or deploy to an isolated test directory/container) to verify artifact handoff and environment tracking. In a production environment, deployments involve SSH keys, cloud provider credentials (such as AWS OIDC or Kubernetes service accounts), zero-downtime rolling updates, and automated rollback strategies.

Illustrative Staging Deployment Configuration

Add a deploy stage to your pipeline that runs only on the main branch, tracks the deployment in GitLab’s Operate > Environments dashboard, and performs a post-deployment check:

YAML

stages:
  - build
  - test
  - deploy

# ... build_application and unit_tests jobs from earlier ...

deploy_staging:
  stage: deploy
  environment:
    name: staging
    url: https://staging.example.internal
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - echo "Preparing deployment for commit $CI_COMMIT_SHORT_SHA..."
    - mkdir -p /tmp/staging_server
    - cp -r dist/* /tmp/staging_server/
    - echo "Verifying deployed files..."
    - test -f /tmp/staging_server/app.js
    - cat /tmp/staging_server/build-info.json
    - echo "Staging deployment verified successfully."

How These Deployment Controls Work

  • environment: Registers staging inside GitLab’s Environments dashboard so your team can see which commit is currently deployed to staging.
  • rules: - if: $CI_COMMIT_BRANCH == "main": Ensures deployments happen only when code lands on the main branch, preventing experimental feature branches from overwriting your staging environment.
  • Manual Deployment Controls: If you want human approval before deploying (common for production releases), add when: manual to the job. GitLab will pause the pipeline before deployment and display a Play button in the UI.
  • Post-Deployment Verification: Checking that app.js exists and reading build-info.json (or running a curl health check against a live URL) confirms the deployment actually succeeded rather than silently failing.

12. Explore Useful GitLab CI/CD Features

After mastering your first three-stage pipeline, GitLab offers several powerful features to make workflows faster, cleaner, and easier to maintain:

  • rules: Replaces older only/except keywords with flexible if expressions that control when jobs run based on branch names, merge requests, file changes, or custom variables.
  • needs: Creates a Directed Acyclic Graph (DAG) allowing a job to start as soon as a specific earlier job finishes, rather than waiting for an entire stage to complete.
  • Parallel Jobs: Runs multiple jobs in the same stage simultaneously (such as unit_tests, lint_code, and security_audit), cutting total pipeline duration dramatically.
  • Manual Jobs (when: manual): Pauses execution until a team member explicitly triggers the job, ideal for production releases or destructive database migrations.
  • Scheduled Pipelines: Runs pipelines automatically on a cron schedule (configured under Build > Pipeline schedules) for nightly regression suites or dependency updates.
  • Merge Request Pipelines: Runs dedicated validation checks on the combined result of a source branch and target branch before code is merged.
  • Reusable Configuration (include): Splits large .gitlab-ci.yml files into smaller, modular YAML templates stored locally or in a shared central repository.
  • Parent-Child Pipelines: Triggers downstream sub-pipelines from a main pipeline, useful for monorepos where frontend and backend services live in the same repository.

13. Fix Common Problems During Your First Pipeline

Even experienced engineers encounter pipeline errors. Knowing where to look turns frustrating failures into quick fixes.

1. Invalid YAML Syntax or Incorrect Indentation

  • Symptom: GitLab displays a red banner saying Pipeline cannot be run: yaml invalid immediately after committing.
  • Where to Look: Open Build > Pipeline editor and click the Validate tab. GitLab highlights the exact line number with the syntax error.
  • How to Verify: Replace any tab characters with 2 spaces, ensure every list item starts with - , and confirm the Pipeline Editor shows Simulation completed successfully.

2. No Active Runner Available

  • Symptom: The pipeline stays stuck in Pending with a message stating This job is stuck because you don’t have any active runners that can run this job.
  • Where to Look: Go to Settings > CI/CD > Runners.
  • How to Verify: Enable instance runners or verify that your project runner service is online (green indicator).

3. Missing Dependencies or Command Not Found

  • Symptom: Job fails with sh: npm: not found or Cannot find module '...'.
  • Where to Look: Check the top of the job log to see which Docker image the runner used.
  • How to Verify: Ensure image: node:20-alpine (or your required language runtime) is specified and that npm ci runs before scripts requiring third-party libraries.

4. Incorrect Script Commands

  • Symptom: Job fails with npm ERR! Missing script: "test" or No such file or directory.
  • Where to Look: Inspect the exact command echoed in green inside the job log right before the error message.
  • How to Verify: Test the exact command locally in your terminal and ensure file paths match your repository’s folder structure (Linux runners are case-sensitive).

5. Permission Errors

  • Symptom: Job fails with Permission denied when executing a shell script (such as ./deploy.sh).
  • Where to Look: Check file permissions in your repository or the job log output.
  • How to Verify: Run chmod +x deploy.sh locally and commit the executable permission, or invoke it with sh deploy.sh.

6. Missing Environment Variables

  • Symptom: Deployment or API scripts fail because a variable resolves to an empty string.
  • Where to Look: Check Settings > CI/CD > Variables to see if the variable is marked Protected.
  • How to Verify: If you are testing on a feature branch, a Protected variable will not be injected. Either uncheck Protected for non-sensitive variables or test on a protected branch.

7. Failed Test Commands

  • Symptom: The test stage turns red and downstream deploy jobs are skipped.
  • Where to Look: Open the failing test job log or click the Tests tab on the pipeline summary page.
  • How to Verify: Fix the failing application logic or test assertion, push a new commit, and confirm the test job turns green.

8. Missing Artifacts

  • Symptom: A job in test or deploy fails because dist/ does not exist.
  • Where to Look: Check the end of the build job log for the line Uploading artifacts for successful job.
  • How to Verify: Confirm the paths: entry under artifacts: matches the exact directory created by your build script.

9. Unexpected Pipeline Execution Conditions

  • Symptom: A job you expected to run did not appear in the pipeline graph at all.
  • Where to Look: Review the rules: block on that job and check which branch or event triggered the pipeline.
  • How to Verify: Confirm $CI_COMMIT_BRANCH matches your rule condition (for instance, "main" vs "master").

14. Hands-On Challenge: Build a Complete Starter Pipeline

Put everything you have learned together by building a complete end-to-end starter pipeline in your gitlab-cicd-starter repository.

Challenge Requirements

Update your .gitlab-ci.yml file so a single push to main executes the following seven-step workflow:

  1. Retrieve application code: Automatically handled by the GitLab Runner when each job starts.
  2. Install required dependencies: Run npm install --ignore-scripts (or npm ci if you generate a package-lock.json) during preparation.
  3. Run automated tests: Execute app.test.js in the test stage and generate a JUnit report.
  4. Build the application: Run npm run build in the build stage to create the dist/ directory.
  5. Save the build output as an artifact: Preserve dist/ for 1 day.
  6. Deploy to a test environment: Copy the dist/ artifact into /tmp/test_env inside a deploy_test job restricted to the main branch.
  7. Verify the deployment result: Confirm app.js and build-info.json exist in /tmp/test_env and print the deployed version.

Reference Solution

Compare your solution against this complete configuration:

YAML

default:
  image: node:20-alpine

stages:
  - build
  - test
  - deploy

build_job:
  stage: build
  script:
    - npm install --ignore-scripts
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 day

test_job:
  stage: test
  script:
    - node --test --test-reporter=junit --test-reporter-destination=junit.xml app.test.js
  artifacts:
    when: always
    reports:
      junit: junit.xml

deploy_test:
  stage: deploy
  environment:
    name: testing
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - mkdir -p /tmp/test_env
    - cp -r dist/* /tmp/test_env/
    - test -f /tmp/test_env/app.js
    - test -f /tmp/test_env/build-info.json
    - cat /tmp/test_env/build-info.json
    - echo "Deployment verification complete."

Expected Stage Outcomes & Verification Checklist

  • Build Stage (build_job): Exits with status 0 and displays Uploading artifacts for successful job in the job log.
  • Test Stage (test_job): Runs both unit tests, passes, and populates the Tests tab in the GitLab pipeline view.
  • Deploy Stage (deploy_test): Executes only on main, verifies both files exist in /tmp/test_env, and registers a deployment under Operate > Environments > testing.

Use this checklist to confirm your pipeline is working properly:

  • [ ] .gitlab-ci.yml passes validation in the GitLab Pipeline Editor.
  • [ ] All three stages (build, test, deploy) appear in sequential order in the pipeline graph.
  • [ ] You can download dist/ directly from the build_job artifacts panel in the GitLab UI.
  • [ ] Intentionally breaking an assertion in app.test.js causes test_job to fail and blocks deploy_test from running.
  • [ ] Reverting the broken test restores a green pipeline across all stages.

15. Develop Your GitLab CI/CD Skills Further

Once you feel comfortable writing basic YAML pipelines, you can expand your automation capabilities step by step rather than trying to adopt every advanced tool on day one:

  1. Pipeline Optimization and Caching: Add dependency caching (cache:) and use needs: to run independent lint, test, and build jobs concurrently so feedback reaches developers faster.
  2. Container Image Builds: Learn how to build Docker images inside GitLab CI/CD and push them to the built-in GitLab Container Registry tagged with $CI_COMMIT_SHORT_SHA.
  3. Automated Security Scanning: Integrate Static Application Security Testing (SAST), dependency scanning, and secret detection templates to catch vulnerabilities before code is merged.
  4. Reusable Templates (include): Refactor repeated job definitions across multiple repositories into centralized CI/CD templates so teams maintain one standard pipeline definition.
  5. Infrastructure as Code (IaC): Automate Terraform or OpenTofu plan-and-apply workflows inside GitLab pipelines with manual approval gates for infrastructure changes.
  6. Kubernetes Deployments: Connect GitLab to a Kubernetes cluster using the GitLab Agent for Kubernetes to perform automated rolling deployments and review apps for every merge request.

16. Conclusion: Turn Your First Pipeline Into a Learning Foundation

Building your first working pipeline is a major milestone in understanding modern DevOps practices. In this GitLab CI/CD Getting Started Guide, you learned how GitLab CI/CD orchestrates workflows while GitLab Runners execute jobs, how to structure .gitlab-ci.yml using stages and scripts, how to automate unit tests, how to pass build outputs via artifacts, and how to secure configurations with protected and masked CI/CD variables. Every complex enterprise delivery pipeline is built from these exact same primitives. Keep experimenting with your starter repository—try adding a code linting job, creating a feature branch to see how rules behave on merge requests, or intentionally breaking a step to practice reading job logs. Consistent hands-on practice is the fastest way to turn basic YAML files into reliable, production-ready automation.

Related Posts

How NoOps Is Changing the Way Modern IT Teams Manage Infrastructure

Modern information technology moves at a pace that often leaves traditional operational structures struggling to keep up. For a growing technology company, success brings rapid user adoption,…

Read More

How to Use GitHub Actions for DevOps Automation & Pipelines

In modern software engineering, moving code from a local branch to production traditionally requires a series of manual builds, tests, security checks, and deployments that slow delivery…

Read More

How to Use Jenkins for CI/CD: A Step-by-Step Guide

In modern software development, writing code is only half the journey. Getting that code safely, quickly, and reliably into the hands of users is where the real…

Read More

Navigating the Pulse: A Comprehensive Guide to Mumbai Local Train Commuting and Urban Transit

Few urban experiences match the sheer momentum of Mumbai during peak hours. The city moves to a relentless, rhythmic heartbeat dictated by its suburban railway network, a…

Read More

How Agile and DevOps Work Together for Continuous Delivery

Imagine a company hiring a DevOps freelancer to manage CI/CD pipelines and cloud infrastructure, only for a Friday night server outage to spark immediate tension over uncommunicated…

Read More

CI/CD with Docker Containers: A Step-by-Step DevOps Guide

Every development team eventually faces a frustrating scenario: an application runs flawlessly on a developer’s laptop, but immediately breaks when deployed to staging or production. Traditional deployment…

Read More
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x