CI/CD and automation · Beginner · 16 min
Write your first GitLab CI/CD pipeline
By Padding · Updated 18 Nov 2026
GitLab 19.6 · Node.js 26 (node:26 image) · check-jsonschema 0.39.0
You will write a validated .gitlab-ci.yml for a small Node.js 26 project, with stages, a cached npm install, expiring artifacts, merge request and default-branch rules, a job that skips the stage queue with needs, and a test report that shows up in the merge request.
On this page
GitLab CI/CD reads one file at the root of your repository, .gitlab-ci.yml, and turns every push into a pipeline: a set of jobs, grouped into stages, each one run by a runner in a fresh container. There is no separate service to connect. If the file is in the repository and the project has a runner available (GitLab.com provides shared ones), pipelines start.
In this tutorial you build that file for a small Node.js 26 project called bill-split, which splits a bill between friends in whole cents or kobo. You start with three plain jobs, then add a cache, artifacts, rules and needs one at a time, and validate the file after each change, so a typo never costs you a pipeline run. Before you push, you run every job's commands on your own machine.
If you already know GitHub Actions, each step ends with a short list of the closest equivalents. Everything lives in ~/gitlab-ci-demo.
Step 1 · Create the project
If you have never made a commit with Git on this computer, tell Git who you are first, using your own name and email (GitLab shows them on each commit). Skip this if git config user.email already prints an address.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"Make the project folder and a Git repository whose first branch is called main (-b main; without it, many Git installs still start on master), then create package.json with a pinned copy of Prettier, the code formatter the pipeline's first job will run:
mkdir -p ~/gitlab-ci-demo/bill-split
cd ~/gitlab-ci-demo/bill-split
git init -b main
npm init -y
npm pkg set type=module
npm install --save-dev --save-exact prettier@3.10.1
mkdir src test scriptsnpm install writes package-lock.json. Commit it: the pipeline installs from it, and its contents decide when the cache is rebuilt.
Now add the code. splitBill takes a total in minor units (cents, kobo, pesewas) and a number of people, and shares out any remainder one unit at a time, so the shares always add up to the total. Working in whole minor units avoids the rounding errors you get from decimals such as 0.1 + 0.2.
cd ~/gitlab-ci-demo/bill-split
cat > src/split.js <<'JS'
export function splitBill(total, people) {
if (!Number.isInteger(total) || total < 0) {
throw new RangeError("total must be a whole number of minor units");
}
if (!Number.isInteger(people) || people < 1) {
throw new RangeError("people must be a whole number above zero");
}
const base = Math.floor(total / people);
const remainder = total % people;
return Array.from({ length: people }, (_, i) =>
i < remainder ? base + 1 : base,
);
}
JS
cat > test/split.test.js <<'JS'
import test from "node:test";
import assert from "node:assert/strict";
import { splitBill } from "../src/split.js";
test("splits evenly when it can", () => {
assert.deepEqual(splitBill(900, 3), [300, 300, 300]);
});
test("hands out the remainder one unit at a time", () => {
assert.deepEqual(splitBill(1000, 3), [334, 333, 333]);
});
test("rejects zero people", () => {
assert.throws(() => splitBill(500, 0), RangeError);
});
JS
cat > scripts/build.js <<'JS'
import { cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
rmSync("dist", { recursive: true, force: true });
mkdirSync("dist");
cpSync("src", "dist", { recursive: true });
const info = {
commit: process.env.CI_COMMIT_SHORT_SHA ?? "local",
builtAt: new Date().toISOString(),
};
writeFileSync("dist/build-info.json", JSON.stringify(info, null, 2) + "\n");
console.log(`Built dist/ for commit ${info.commit}`);
JS
printf 'node_modules/\n.npm/\ndist/\njunit.xml\n' > .gitignoreThe build script copies the source into dist/ and records which commit it came from. CI_COMMIT_SHORT_SHA is one of the variables GitLab sets in every job; on your machine it is unset, so the script writes local.
Add four scripts to package.json. test:ci runs the same tests with two reporters at once: the readable spec output to the terminal, and a JUnit XML file, junit.xml, which GitLab knows how to display.
cd ~/gitlab-ci-demo/bill-split
npm pkg set scripts.format="prettier --check src test scripts"
npm pkg set scripts.test="node --test"
npm pkg set scripts.test:ci="node --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=junit.xml"
npm pkg set scripts.build="node scripts/build.js"Check it worked
cd ~/gitlab-ci-demo/bill-split
npm run format
npm testPrettier ends with All matched files use Prettier code style!, and the test summary shows tests 3, pass 3 and fail 0. If Prettier lists a file instead, run npx prettier --write src test scripts and check again.
Step 2 · Install a validator for the pipeline file
GitLab only tells you a pipeline file is broken after you push it. check-jsonschema catches most mistakes first: it carries a copy of the published JSON schema for .gitlab-ci.yml and reports misspelt keywords, values in the wrong place and wrong types. Install version 0.39.0 into its own Python environment. On Ubuntu or Debian, install the venv module first; on macOS, skip the two apt lines.
sudo apt update
sudo apt install -y python3-venv
python3 -m venv ~/gitlab-ci-demo/tools
~/gitlab-ci-demo/tools/bin/pip install "check-jsonschema==0.39.0"
export PATH="$HOME/gitlab-ci-demo/tools/bin:$PATH"The export line lasts only for this terminal. Run it again if you open a new one.
Check it worked
check-jsonschema --versionIt prints check-jsonschema, version 0.39.0.
Step 3 · Write a pipeline with stages and jobs
Create .gitlab-ci.yml at the root of the project:
cd ~/gitlab-ci-demo/bill-split
cat > .gitlab-ci.yml <<'YAML'
stages:
- check
- test
- build
default:
image: node:26
before_script:
- npm ci
format:
stage: check
script:
- npm run format
test:
stage: test
script:
- npm test
build:
stage: build
script:
- npm run build
YAMLRead it from the top:
stageslists the stages in the order they run. Every job incheckmust pass before any job inteststarts, and so on. Jobs in the same stage run in parallel.defaultsets values every job inherits.image: node:26runs each job in the official Node.js 26 container, so the runner needs nothing installed beyond its container engine.before_scriptruns ahead of each job's ownscript; here it installs dependencies withnpm ci, which installs exactly whatpackage-lock.jsonlists and fails if it disagrees withpackage.json.- Any top-level key that is not a GitLab keyword, such as
format,testandbuild, is a job. A job's name is your choice;scriptis the list of shell commands it runs. If any command exits with a non-zero code, the job fails.
GitLab clones the repository into each job before before_script runs. You do not add a checkout step.
Check it worked
cd ~/gitlab-ci-demo/bill-split
check-jsonschema --builtin-schema vendor.gitlab-ci .gitlab-ci.ymlIt prints ok -- validation done. Now see a failure: the next command writes a copy with script misspelt and checks it.
cd ~/gitlab-ci-demo/bill-split
printf 'lint:\n image: node:26\n scirpt:\n - npm run format\n' > /tmp/broken-ci.yml
if check-jsonschema --builtin-schema vendor.gitlab-ci /tmp/broken-ci.yml; then
echo "unexpected: validation passed"; false
else
echo "validation failed, as expected"
fi
rm /tmp/broken-ci.ymlThe validator reports a schema error for $.lint and the script prints validation failed, as expected. The exact wording depends on how the schema matches the job; it may read like Additional properties are not allowed ('scirpt' was unexpected), or say that $.lint is not valid under any of the given schemas. The schema does not know every rule GitLab applies (for example, that a stage you name actually exists in stages), so the Pipeline editor in GitLab, under Build, still has the final say. The schema check catches the typing mistakes before you push.
If you know GitHub Actions
- A GitLab job is a GitHub job; the
scriptlist is a series ofrunsteps. stageshas no direct equivalent. GitHub jobs run in parallel unless you chain them withneeds; GitLab jobs run stage by stage unless you useneeds(step 5).image: node:26is closest tocontainer: node:26, or toruns-on: ubuntu-latestplusactions/setup-node.- There is no
actions/checkout: GitLab fetches the code for you.
Step 4 · Add a cache, artifacts and a test report
Every job runs in a new container, so without help each one downloads every npm package again. A cache keeps files between pipelines; artifacts pass files out of a job, to later jobs and to you. Replace the file with this version:
cd ~/gitlab-ci-demo/bill-split
cat > .gitlab-ci.yml <<'YAML'
stages:
- check
- test
- build
default:
image: node:26
cache:
key:
files:
- package-lock.json
paths:
- .npm/
before_script:
- npm ci --cache .npm --prefer-offline
format:
stage: check
script:
- npm run format
test:
stage: test
script:
- npm run test:ci
artifacts:
when: always
expire_in: 1 week
reports:
junit: junit.xml
build:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 30 days
YAMLWhat changed:
cache:key:filesbuilds the cache key frompackage-lock.json. While the lock file stays the same, every job reuses one cache; when a dependency changes, the key changes and a fresh cache is built. The cache holds npm's download folder,.npm/, inside the project (a runner only caches paths inside the project folder).npm ci --cache .npm --prefer-offlinetells npm to use that folder and to skip the network for packages it already has. You do not cachenode_modules, becausenpm cideletes it at the start of every install.artifacts:pathsonbuilduploadsdist/when the job finishes. You can download it from the job page, and jobs in later stages receive it automatically.expire_in: 30 daysdeletes it after that, so old builds do not fill your storage. GitLab keeps the artifacts of the most recent successful pipeline on a branch even after they expire, unless that setting is turned off in the project's CI/CD settings.artifacts:reports:junitontesthandsjunit.xmlto GitLab, which reads it and shows the results in the merge request and in the pipeline's Tests tab.when: alwaysuploads the report even when the tests fail, which is when you most want it.
A cache is a speed-up and may be missing on any run, for example on a new runner. Artifacts are what you rely on to pass results between jobs.
Check it worked
cd ~/gitlab-ci-demo/bill-split
check-jsonschema --builtin-schema vendor.gitlab-ci .gitlab-ci.ymlIt prints ok -- validation done. Now check that a wrongly typed value is caught: the next command writes a copy with expire_in: [1, week], a list instead of a string, and validates it.
cd ~/gitlab-ci-demo/bill-split
sed 's/expire_in: 1 week/expire_in: [1, week]/' .gitlab-ci.yml > /tmp/bad-expiry-ci.yml
grep -q 'expire_in: \[1, week\]' /tmp/bad-expiry-ci.yml
if check-jsonschema --builtin-schema vendor.gitlab-ci /tmp/bad-expiry-ci.yml; then
echo "unexpected: validation passed"; false
else
echo "validation failed, as expected"
fi
rm /tmp/bad-expiry-ci.ymlThe validator fails because expire_in must be a string such as 1 week or 30 days. Your own .gitlab-ci.yml is unchanged.
If you know GitHub Actions
cache:key:filesisactions/cachewith a key built fromhashFiles('package-lock.json'), orcache: npmonactions/setup-node.artifacts:pathswithexpire_inisactions/upload-artifactwithretention-days. In GitLab, later jobs get the artifacts without a download step.- A GitHub workflow has no
reports: junitkeyword; showing test results in a pull request needs an extra action or a job summary.
Step 5 · Choose when the pipeline runs, and skip the queue with needs
With no rules, GitLab runs a pipeline on every push to every branch. For most projects you want two kinds: one for each merge request, and one for the default branch after a merge. Replace the file once more:
cd ~/gitlab-ci-demo/bill-split
cat > .gitlab-ci.yml <<'YAML'
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
stages:
- check
- test
- build
default:
image: node:26
cache:
key:
files:
- package-lock.json
paths:
- .npm/
before_script:
- npm ci --cache .npm --prefer-offline
format:
stage: check
script:
- npm run format
test:
stage: test
needs: []
script:
- npm run test:ci
artifacts:
when: always
expire_in: 1 week
reports:
junit: junit.xml
build:
stage: build
needs: [test]
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 30 days
YAMLHow the new parts work:
workflow:rulesdecides whether a pipeline is created at all. GitLab checks the rules in order and uses the first match. The first rule matches pipelines for merge requests; the second matches pushes to the default branch (mainhere). A push to any other branch matches neither, so it creates no pipeline until you open a merge request for it. That also stops the same commit running twice, once as a branch pipeline and once as a merge request pipeline.ruleson a job decides whether that job is added.buildonly runs on the default branch, so merge requests get the quick feedback (format and tests) without spending time on a build nobody downloads.needs: []letsteststart as soon as the pipeline starts, alongsideformat, instead of waiting for the wholecheckstage.needs: [test]letsbuildstart the momenttestpasses, even ifformatis still running. A job withneedsonly downloads artifacts from the jobs it lists.
$CI_PIPELINE_SOURCE, $CI_COMMIT_BRANCH and $CI_DEFAULT_BRANCH are predefined variables. CI_COMMIT_BRANCH is not set in merge request pipelines, which is why the build rule never matches there.
Check it worked
cd ~/gitlab-ci-demo/bill-split
check-jsonschema --builtin-schema vendor.gitlab-ci .gitlab-ci.yml
grep -c 'needs:' .gitlab-ci.ymlThe validator prints ok -- validation done, and grep counts 2 lines with needs:.
If you know GitHub Actions
workflow:rulesdoes the job ofon: pull_requestpluson: push: branches: [main].ruleson a job isif:on a job, for exampleif: github.ref == 'refs/heads/main'.needsmeans the same in both. The difference is the default: GitHub jobs start together unless they haveneeds, while GitLab jobs wait for earlier stages unless they haveneeds.
Step 6 · Run each job's commands before you push
The schema check proves the file's shape, not that the jobs pass. Run each job's commands yourself, in the order the runner would, starting from a clean install as the runner does. Use Node.js 26 so you match image: node:26.
cd ~/gitlab-ci-demo/bill-split
node --version
rm -rf node_modules .npm dist junit.xml
# format job
npm ci --cache .npm --prefer-offline
npm run format
# test job
npm ci --cache .npm --prefer-offline
npm run test:ci
# build job
npm ci --cache .npm --prefer-offline
CI_COMMIT_SHORT_SHA=abc1234 npm run buildThe second and third npm ci runs are faster than the first because .npm/ is already filled: the same effect the cache has between jobs on GitLab. Setting CI_COMMIT_SHORT_SHA by hand stands in for the value GitLab sets.
If you have Docker, you can run the same commands inside the job's own image instead, which also catches anything that only works because of software on your machine: docker run --rm -v "$PWD":/app -w /app node:26 sh -c "npm ci && npm run test:ci".
Check it worked
cd ~/gitlab-ci-demo/bill-split
node --version | grep '^v26\.'
grep -o '<testsuites[^>]*>' junit.xml
grep -c '<testcase' junit.xml
cat dist/build-info.json
grep -q '"commit": "abc1234"' dist/build-info.json && echo "build info ok"node --version starts with v26, junit.xml opens with a <testsuites> element and holds 3 test cases, and dist/build-info.json names commit abc1234. These are the files GitLab will pick up as the test report and the build artifact.
Step 7 · Push, open a merge request and read the results
Commit everything on main. The .gitignore keeps node_modules, the npm cache, dist/ and junit.xml out of the repository.
cd ~/gitlab-ci-demo/bill-split
git add .
git commit -m "Add bill-split with a GitLab CI/CD pipeline"
git log --onelineCreate an empty project on GitLab called bill-split (no README, so the push is not rejected), then push. Replace YOUR-GROUP with your GitLab username or group.
git remote add origin git@gitlab.com:YOUR-GROUP/bill-split.git
git push -u origin mainOn GitLab.com, jobs on the shared instance runners use compute minutes from your namespace's monthly allowance, and new accounts may be asked to verify their identity before the first pipeline runs. A self-managed GitLab needs a runner registered by an administrator.
Open the project and go to Build, then Pipelines. The push to main created a pipeline with all three jobs. Open it and look at the order: format and test start together, and build starts as soon as test passes. Open the build job to see its log and, on the right, the artifact you can download or browse.
Now make a change on a branch to see a merge request pipeline. Add a test that fails:
git switch -c split-check
cat >> test/split.test.js <<'JS'
test("shares add up to the total", () => {
assert.equal(splitBill(1000, 3).length, 4);
});
JS
git commit -am "Add a test that fails"
git push -u origin split-checkThe push itself starts no pipeline, because of workflow:rules. Open a merge request from split-check into main, using the link Git prints or the Merge requests page. A merge request pipeline starts with format and test only, and test fails.
Check it worked
In the merge request, the pipeline widget shows the failed pipeline, and below it a test summary that reports one failed test out of four. Open the failed test to read the assertion message. The pipeline's Tests tab shows the same results, job by job.
Fix the test so it checks the sum, then push again:
cat > /tmp/fix.mjs <<'JS'
import { readFileSync, writeFileSync } from "node:fs";
const file = "test/split.test.js";
const text = readFileSync(file, "utf8").replace(
"assert.equal(splitBill(1000, 3).length, 4);",
"assert.equal(splitBill(1000, 3).reduce((a, b) => a + b, 0), 1000);",
);
writeFileSync(file, text);
JS
node /tmp/fix.mjs && rm /tmp/fix.mjs
npm run format
git commit -am "Check that the shares add up to the total"
git pushThe new merge request pipeline passes, and the test summary reports no failures. If you want to keep the history clean, close the merge request without merging and delete the split-check branch.
Next steps
- Compare the same ideas on GitHub:
/tutorials/github-actions-first-workflowand/tutorials/run-node-tests-in-github-actions. - Deploy from this pipeline to staging and production with protected variables and manual jobs:
/tutorials/deploy-from-gitlab-ci-with-environments-and-protected-variables. - See caching and passing build outputs between jobs in more depth, in the GitHub Actions version:
/tutorials/cache-dependencies-and-build-outputs-in-github-actions. - Reference: the full keyword list is at docs.gitlab.com/ci/yaml/.
Related tutorials
- How to Create Your First GitHub Actions WorkflowYou will write a workflow file that runs on every push and every pull request, check its syntax on your own computer with actionlint, push it, and read the run on GitHub.
- How to Run Node.js Tests Automatically with GitHub ActionsYou will write tests with Node.js's built-in test runner, run them on every push and pull request with a GitHub Actions workflow that caches npm downloads and tries two Node.js versions, and check the workflow file locally before you push it.
- Deploy from GitLab CI with environments, protected variables and manual jobsYou will have a GitLab pipeline that deploys a small site to review, staging and production environments over SSH, with a separate protected, masked file-type key for each environment, a manual production job that never overlaps another deploy, a stop job for review apps and an AWS upload that uses a short-lived ID token instead of a stored key.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials