1. Introduction & use cases
GitLab CI/CD is built into GitLab. A file named .gitlab-ci.yml at the root of the repository defines a pipeline of stages (e.g. test → build → deploy); each stage contains jobs that run on runners – machines that execute the job, usually inside a Docker image.
GitLab.com provides shared runners; you can also register your own. Variables (masked/protected), artifacts, caches, environments, review apps and a built-in container registry are all part of the platform.
Where it is used
- Testing every merge request
- Building Docker images into the GitLab Container Registry
- Deploying to servers, Kubernetes or cloud
- Self-hosted CI for companies running GitLab on their own servers
2. Prerequisites
| You need | Version / notes |
|---|---|
| GitLab project | On gitlab.com or a self-managed GitLab |
| Runner | Shared runners (gitlab.com) or your own gitlab-runner |
| YAML basics | Indentation with spaces |
3. Local setup
1Check runners are available
In Settings → CI/CD → Runners make sure instance (shared) runners are enabled, or register your own (next step).
2Optional: register your own runner
Create a runner in Settings → CI/CD → Runners → New project runner to get a token (
glrt-…), then on your machine/server:BASH# install: see docs.gitlab.com/runner/install sudo gitlab-runner register \ --url https://gitlab.com \ --token glrt-XXXXXXXXXXXX \ --executor docker \ --docker-image alpine:latest sudo gitlab-runner status
4. Create & run a project
1Write the pipeline
Three stages; npm cache keyed on the lockfile; test results and build output kept as artifacts.
.gitlab-ci.ymlstages: [test, build, deploy] default: image: node:lts cache: key: files: [package-lock.json] paths: [.npm/] before_script: - npm ci --cache .npm --prefer-offline test: stage: test script: - npm run lint --if-present - npm test build: stage: build script: - npm run build artifacts: paths: [dist/] expire_in: 1 week2Commit and watch the pipeline
Open Build → Pipelines in the project.
BASHgit add .gitlab-ci.yml git commit -m "Add CI pipeline" git push3Validate the file
Use Build → Pipeline editor (it validates and visualises the pipeline) before pushing big changes.
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Define variables in Settings → CI/CD → Variables. Mark secrets Masked (hidden in logs) and Protected (only on protected branches/tags). A File-type variable is written to a temp file – ideal for SSH keys.
# Settings → CI/CD → Variables
SSH_PRIVATE_KEY (type: File, protected)
PROD_HOST 203.0.113.10 (protected)
DATABASE_URL postgres://... (masked, protected)
# predefined, available in every job
$CI_COMMIT_SHA $CI_COMMIT_BRANCH $CI_REGISTRY_IMAGE $CI_DEFAULT_BRANCHKey dependencies
| Package / tool | Used for |
|---|---|
.gitlab-ci.yml | Pipeline definition |
gitlab-runner | Executes jobs (Docker, shell, Kubernetes executors) |
GitLab Container Registry | $CI_REGISTRY_IMAGE for your images |
Environments | Track deployments, manual approvals, rollbacks |
include: / templates | Reuse pipeline snippets |
Folder structure
project/
├── .gitlab-ci.yml
├── ci/
│ └── deploy.sh # scripts called by jobs
├── Dockerfile
└── src/Essential commands
| Command | What it does |
|---|---|
gitlab-runner register | Connect a runner |
gitlab-runner verify | Check registered runners |
Build → Pipeline editor | Validate/visualise the YAML |
Retry / Run pipeline buttons | Re-run jobs or start manually |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Runner | Shared or self-hosted with Docker |
| Target | Server via SSH, Kubernetes agent, or cloud |
| Variables | Protected + masked secrets |
| Protected branches | main/tags allowed to deploy |
Deployment steps
1Build and push a Docker image
Docker-in-Docker builds an image and pushes it to the project registry with the commit SHA as tag.
YAMLbuild_image: stage: build image: docker:27 services: [docker:27-dind] variables: DOCKER_TLS_CERTDIR: "/certs" before_script: [] script: - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY" - docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" . - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH2Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP3Add the deploy key and host as variables
Create a key pair, add the public key to the server user’s
authorized_keys, and store the private key as a File variableSSH_PRIVATE_KEY(protected).BASHssh-keygen -t ed25519 -f gitlab_deploy -N "" ssh-copy-id -i gitlab_deploy.pub deploy@203.0.113.104Deploy job with an environment and manual approval
Runs only on the default branch;
when: manualadds a “Deploy” button; the environment records each deployment.YAMLdeploy_production: stage: deploy image: alpine:latest before_script: - apk add --no-cache openssh-client rsync - chmod 600 "$SSH_PRIVATE_KEY" - mkdir -p ~/.ssh && ssh-keyscan -H "$PROD_HOST" >> ~/.ssh/known_hosts script: - rsync -az --delete -e "ssh -i $SSH_PRIVATE_KEY" dist/ deploy@$PROD_HOST:/var/www/example.com/ environment: name: production url: https://example.com rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH when: manual5Serve the build with Nginx
Copy the build output to the server and let Nginx serve it. The
try_files … /index.htmlline sends every unknown path toindex.html, so client-side routes (React Router, Vue Router) work after a page refresh./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; root /var/www/example.com; index index.html; location / { try_files $uri $uri/ /index.html; } location ~* \.(js|css|png|jpg|jpeg|gif|svg|webp|woff2?)$ { expires 30d; add_header Cache-Control "public, immutable"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com8Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
Jobs stuck: This job is stuck because you don’t have any active runners
Enable shared runners or register a runner whose tags match the job (or remove tags: from the job).
yaml invalid / pipeline not created
Check indentation and keys in the Pipeline editor; one wrong space breaks the file.
Variables are empty in a job
Protected variables are only exposed to protected branches/tags. Protect the branch or unprotect the variable.
Docker-in-Docker: Cannot connect to the Docker daemon
The runner needs privileged = true for dind, and the job must use the docker:dind service with matching TLS settings.
Host key verification failed
Add the server with ssh-keyscan before connecting (as in the deploy job).
Best practices
- Keep secrets as masked + protected variables; use File variables for keys.
- Use
rules:so deploy jobs only run on protected branches/tags. - Cache dependencies and keep artifacts small with
expire_in. - Tag images with the commit SHA and deploy that exact tag.
- Use environments for visibility and one-click rollback.