DevOps & Deployment

GitLab CI/CD Setup & Deployment Guide

Pipelines defined in .gitlab-ci.yml – stages, runners, variables, Docker builds to the GitLab registry and SSH deployments with environments.

Updated Official documentation ↗

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 needVersion / notes
GitLab projectOn gitlab.com or a self-managed GitLab
RunnerShared runners (gitlab.com) or your own gitlab-runner
YAML basicsIndentation with spaces

3. Local setup

  1. 1Check runners are available

    In Settings → CI/CD → Runners make sure instance (shared) runners are enabled, or register your own (next step).

  2. 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

  1. 1Write the pipeline

    Three stages; npm cache keyed on the lockfile; test results and build output kept as artifacts.

    .gitlab-ci.yml
    stages: [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 week
  2. 2Commit and watch the pipeline

    Open Build → Pipelines in the project.

    BASH
    git add .gitlab-ci.yml
    git commit -m "Add CI pipeline"
    git push
  3. 3Validate 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.

CI/CD variables
# 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_BRANCH

Key dependencies

Package / toolUsed for
.gitlab-ci.ymlPipeline definition
gitlab-runnerExecutes jobs (Docker, shell, Kubernetes executors)
GitLab Container Registry$CI_REGISTRY_IMAGE for your images
EnvironmentsTrack deployments, manual approvals, rollbacks
include: / templatesReuse pipeline snippets

Folder structure

project structure
project/
├── .gitlab-ci.yml
├── ci/
│   └── deploy.sh       # scripts called by jobs
├── Dockerfile
└── src/

Essential commands

CommandWhat it does
gitlab-runner registerConnect a runner
gitlab-runner verifyCheck registered runners
Build → Pipeline editorValidate/visualise the YAML
Retry / Run pipeline buttonsRe-run jobs or start manually

6. Production deployment

Server & hosting requirements

RequirementRecommendation
RunnerShared or self-hosted with Docker
TargetServer via SSH, Kubernetes agent, or cloud
VariablesProtected + masked secrets
Protected branchesmain/tags allowed to deploy

Deployment steps

  1. 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.

    YAML
    build_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_BRANCH
  2. 2Prepare 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.

    BASH
    ssh 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_IP
  3. 3Add 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 variable SSH_PRIVATE_KEY (protected).

    BASH
    ssh-keygen -t ed25519 -f gitlab_deploy -N ""
    ssh-copy-id -i gitlab_deploy.pub deploy@203.0.113.10
  4. 4Deploy job with an environment and manual approval

    Runs only on the default branch; when: manual adds a “Deploy” button; the environment records each deployment.

    YAML
    deploy_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: manual
  5. 5Serve the build with Nginx

    Copy the build output to the server and let Nginx serve it. The try_files … /index.html line sends every unknown path to index.html, so client-side routes (React Router, Vue Router) work after a page refresh.

    /etc/nginx/sites-available/example.com
    server {
        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";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or 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.com
  8. 8Add 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.

    BASH
    sudo 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.

terminalPipeline #1123 passed for mainStage: test ✔ test 1m 02sStage: build ✔ build 0m 41sStage: deploy ⏵ deploy_production (manual)Job log (test):$ npm ci --cache .npm --prefer-offlineadded 312 packages in 9s$ npm testTests: 24 passed, 24 totalJob succeeded
Figure 1: terminal output of the sample GitLab CI/CD project (section 4).
1Push / mergerequest2test stage3build stage +registry4Manual deploybutton5Server via SSH +HTTPS
Figure 2: production deployment flow (section 6).
project/├── .gitlab-ci.yml├── ci/│ └── deploy.sh # scripts called by jobs├── Dockerfile└── src/
Figure 3: project folder structure (section 5).

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.