GitLab CI from zero: stages, jobs, artifacts and caches
A first .gitlab-ci.yml for shorty, the Go URL shortener: stages, jobs, workflow rules, a Postgres service, test reports and the difference between artifacts and caches. Checked locally with gitlab-ci-local and the real job commands.
Most of my CI since the last few years has been GitHub Actions. But a lot of teams live on GitLab, and the first file you meet there is .gitlab-ci.yml. It looks a bit like a workflow file and then behaves quite differently in a few places, mostly around stages, caches and when a job runs at all.
In this blog we will write a .gitlab-ci.yml for shorty, the URL shortener in Go from the REST API post and the pgx and sqlc post. It will vet the code, run unit tests with the race detector, run the Postgres tests against a real database and build a binary. Level is beginner. You need a GitLab project with shorty pushed to it and a runner, and gitlab.com's hosted runners are fine for this one. If you have not read CI/CD explained yet, that post has the big picture.
I used Go 1.27.4 (the golang:1.27.4-alpine image), Postgres 18 (postgres:18-alpine) and GitLab Runner 19.5. There is no GitLab instance on my machine, so I checked the file with gitlab-ci-local 4.77.1 and ran every job's commands myself in the same images. More on that at the end.
How GitLab thinks about a pipeline
A push creates a pipeline. A pipeline has stages, and every stage holds jobs. All jobs in one stage run in parallel, and the next stage only starts when every job in the current one passed. Each job runs in a fresh container on a runner, so nothing on disk survives from one job to the next unless you ask for it.
That last part is where artifacts and caches come in. Keep it in mind, we come back to it.
If you know GitHub Actions from the GitHub Actions from zero post, a GitLab job is roughly a GitHub job, and script is a list of run steps glued together. There is no uses:. You get an image and a shell.
The whole file
Here it is first. Put it in the root of the repo, next to go.mod.
# .gitlab-ci.yml for shorty (put it in the repo root, next to go.mod)
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
- if: $CI_COMMIT_TAG
stages:
- lint
- test
- build
default:
image: golang:1.27.4-alpine
cache:
key:
files:
- go.sum
paths:
- .go/pkg/mod/
- .cache/go-build/
policy: pull
variables:
GOPATH: $CI_PROJECT_DIR/.go
GOCACHE: $CI_PROJECT_DIR/.cache/go-build
GOTOOLCHAIN: local
# Fills the module and build cache once per go.sum. Other jobs only pull it.
deps:
stage: .pre
script:
- go mod download
- go build ./...
cache:
key:
files:
- go.sum
paths:
- .go/pkg/mod/
- .cache/go-build/
policy: pull-push
vet:
stage: lint
script:
- test -z "$(gofmt -l cmd internal migrations)" || (gofmt -l cmd internal migrations; exit 1)
- go vet ./...
unit-test:
stage: test
variables:
CGO_ENABLED: "1"
before_script:
- apk add --no-cache gcc musl-dev
script:
- go run gotest.tools/gotestsum@v1.13.0 --junitfile report.xml -- -race -coverprofile=coverage.out ./...
- go tool cover -func=coverage.out | tail -n 1
coverage: '/total:\s+\(statements\)\s+\d+\.\d+%/'
artifacts:
when: always
paths:
- coverage.out
reports:
junit: report.xml
expire_in: 1 week
postgres-test:
stage: test
services:
- name: postgres:18-alpine
alias: postgres
variables:
POSTGRES_USER: shorty
POSTGRES_PASSWORD: shorty
POSTGRES_DB: shorty
SHORTY_TEST_DATABASE_URL: postgres://shorty:shorty@postgres:5432/shorty?sslmode=disable
script:
- go test -count=1 -run TestPostgres -v ./internal/links/
build:
stage: build
variables:
CGO_ENABLED: "0"
script:
- go build -trimpath -ldflags "-s -w" -o bin/shorty ./cmd/shorty
- ./bin/shorty version
artifacts:
paths:
- bin/shorty
expire_in: 1 week
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_TAG
Now let us go through it piece by piece.
Stages and jobs
stages lists the order. Every top level key that isn't a keyword (workflow, stages, default, variables) is a job. deps, vet, unit-test, postgres-test and build are the five jobs here.
.pre is a stage GitLab gives you for free. It always runs first, even though it is not in the list. I put cache warm-up job there.
default is for settings every job gets unless it overrides them. Here that is the image and the cache. One small gotcha: the variables at the top level are global too, but they are not under default. They just apply everywhere.
In the GitLab UI the pipeline graph shows one column per stage: .pre, lint, test, build. unit-test and postgres-test sit next to each other in the test column and run at the same time. If you later want build to start as soon as vet passes without waiting on the slow tests, that is what needs: is for. I'm keeping it simple here and letting stages do the ordering.
When does a pipeline run
Without workflow: rules, a push to a branch that has an open merge request gives you two pipelines: a branch pipeline and a merge request pipeline. Same commit, double the minutes. The four rules above say:
- Run for merge request events.
- Don't run a branch pipeline if that branch has an open MR (the MR pipeline covers it).
- Otherwise run for any branch push.
- And for tags.
The rules are checked top to bottom and the first match wins. That trips people up quite often. If you put if: $CI_COMMIT_BRANCH first, rule 2 never gets a chance.
The build job has its own rules. It only runs on the default branch and on tags. A feature branch gets lint and test only, nothing more. I checked this with gitlab-ci-local by switching branches: on feature/x it listed four jobs and on main it listed five, with build at the end.
Caches vs artifacts
Both save files out of a job. They are for different things, and mixing them up is the most common mistake I see in GitLab files.
A cache is a speed-up. It's fine if it's missing. Here it holds the Go module downloads and the build cache, keyed on go.sum, so a new dependency gives a new cache. GitLab can only cache paths inside the project directory, which is why GOPATH and GOCACHE point to $CI_PROJECT_DIR/.go and $CI_PROJECT_DIR/.cache/go-build. With the defaults (/go and ~/.cache) nothing gets saved. The job doesn't fail, there is only a warning in the log, so the cache is just quietly empty every time.
The deps job has policy: pull-push, it downloads the cache and uploads it again. Every other job inherits policy: pull from default. They read it and never write. Without this, four jobs in parallel all try to upload the same cache at the end, which is slow and pointless.
One more thing about caches. On gitlab.com hosted runners the cache is shared. On your own runners it's stored on that runner's machine unless you set up a distributed cache in S3, so two runners do not see each other's cache. The runner posts later in this series deal with that.
An artifact is a result. Other jobs and people need it. bin/shorty from build is an artifact, you can download it from the job page and jobs in later stages get it automatically. expire_in: 1 week stops them piling up in storage.
unit-test has two kinds. coverage.out is a normal artifact. report.xml goes under reports: junit, and GitLab reads it and shows test results in the merge request, failed test names included. when: always uploads them even when the tests fail, which is exactly when you want to read them.
The coverage keyword is a regex that GitLab runs on the job log. go tool cover -func prints a last line like total: (statements) 48.0%, the regex picks the number and the MR shows it.
The race detector needs gcc on Alpine
This one I hit while checking the file itself. My first unit-test job didn't have CGO_ENABLED or apk add, and it failed straight away:
go: -race requires cgo; enable cgo by setting CGO_ENABLED=1
So I set CGO_ENABLED=1. Next error:
# runtime/cgo
cgo: C compiler "gcc" not found: exec: "gcc": executable file not found in $PATH
FAIL github.com/fenixara/shorty/internal/shortcode [build failed]
The Alpine Go image has no C compiler. apk add --no-cache gcc musl-dev in before_script fixed it and the run went green, 23 tests and 1 skipped. The skip is the Postgres test, which has its own job. If the few seconds of apk add bother you, use the Debian based golang:1.27.4 image for that job instead, it has gcc already.
A real Postgres as a service
services starts another container next to the job, on the same network. With alias: postgres the job reaches it at postgres:5432. The POSTGRES_* variables are job variables, and GitLab passes job variables to the service containers too, so the official image creates the shorty user and database on start.
shorty's TestPostgres skips itself unless SHORTY_TEST_DATABASE_URL is set, and it runs the goose migrations on its own. So the job is one line. When I ran it against postgres:18-alpine on a private Docker network with the same alias it took just 0.08s, that was faster than I expected.
=== RUN TestPostgres
--- PASS: TestPostgres (0.08s)
PASS
ok github.com/fenixara/shorty/internal/links 0.087s
How I checked all this without GitLab
gitlab-ci-local ships as a single binary on its GitHub releases page, so no npm needed. From the repo root:
gitlab-ci-local --list
json schema validated in 76 ms
name description stage when allow_failure environment needs
deps .pre on_success false
vet lint on_success false
unit-test test on_success false
postgres-test test on_success false
build build on_success false
It validates the file against GitLab's JSON schema and works out which jobs the rules keep. It can run jobs in Docker too, but I ran them by hand instead: the vet, test and build commands on my Mac, then unit-test and postgres-test again inside golang:1.27.4-alpine with a Postgres container next to them. That is where the gcc error came from. What I could not test is GitLab itself: the MR widget, the test report tab and the shared cache. On gitlab.com you can also paste the file into the pipeline editor, which runs the official lint.
There we have it. Push the file, open a merge request and look at the pipeline graph. Next up is running these jobs on your own runner on EC2.