Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit 09eb5c6 · 15 days ago

Git for the team, part 5: GitLab CI in practice — tests, building a Docker image, and deploying to the server

🌐 Machine-translated from Russian. Show original

In this part:

How GitLab CI works#

ConceptWhat is
.gitlab-ci.ymlfile in the root of the repository describing the pipeline
Pipelinerunning everything described on a specific commit
Stagestage: test → build → deploy; stages proceed sequentially
Joba task within a stage; tasks from one stage run parallel to
Runnera machine that performs tasks (installed in Git for the team, part 4: my GitLab CE on Ubuntu 24.04 — installation, HTTPS, email, backups, and runners
Artifactsfiles that the task passes on or uploads
Variablesvariables and secrets set in the project settings
Environmentenvironment (staging, production) with deployment history and a rollback button

The basics of Docker, Dockerfile, and rollback deployment are thoroughly covered in the series "Docker and CI/CD from Scratch." Here we assemble the full pipeline specifically for GitLab: with launch rules, cache, registry, and environments.

What we will get#

  1. For each MR — linter and tests. Red CI → cannot be merged (see Git for the team, part 3: code review and merge request — rules, templates, CODEOWNERS, and protected branches).
  2. When merging into main — build the Docker image and upload it to the built-in GitLab Container Registry .
  3. Automatic staging deployment.
  4. Upload to production — by button, with a record of who and when downloaded it.

Step 1. Variables and secrets#

Settings → CI/CD → Variables → Add variable:

VariableValueFlags
SSH_PRIVATE_KEYuser private key deploy (type File)Protected
STAGING_HOST10.0.10.21—
PROD_HOST10.0.10.31Protected
SSH_KNOWN_HOSTSoutput ssh-keyscan 10.0.10.21 10.0.10.31 (type File)—
  • Protected — the variable is available only to pipelines of protected branches (main, production). Code from someone else's feature branch will not see it.
  • Masked — the value is hidden in logs (suitable for single-line tokens).

Variables CI_REGISTRY, CI_REGISTRY_IMAGE, CI_REGISTRY_USER, CI_REGISTRY_PASSWORD, CI_COMMIT_SHA are set by GitLab itself — they do not need to be created.

🔐 No passwords in .gitlab-ci.yml — the file is visible to everyone who has access to the repository.

Step 2. The entire pipeline#

.gitlab-ci.yml for Node.js applications (for Python, Go, .NET, only the image and commands change):

stages: [test, build, deploy]

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG

default:
  tags: [docker]

variables:
  IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA

# ── Тесты: на каждый MR и на main ──────────────────
lint:
  stage: test
  image: node:24-alpine
  cache:
    key:
      files: [package-lock.json]
    paths: [.npm/]
  script:
    - npm ci --cache .npm --prefer-offline
    - npm run lint

test:
  stage: test
  image: node:24-alpine
  cache:
    key:
      files: [package-lock.json]
    paths: [.npm/]
    policy: pull
  script:
    - npm ci --cache .npm --prefer-offline
    - npm test -- --reporter=junit --outputFile=junit.xml
  artifacts:
    when: always
    reports:
      junit: junit.xml

# ── Сборка образа: только main ─────────────────────
build:
  stage: build
  image: docker:29
  services: [docker:29-dind]
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
    - docker build --pull -t "$IMAGE" -t "$CI_REGISTRY_IMAGE:latest" .
    - docker push "$IMAGE"
    - docker push "$CI_REGISTRY_IMAGE:latest"

# ── Деплой: шаблон ─────────────────────────────────
.deploy:
  stage: deploy
  image: alpine:3
  before_script:
    - apk add --no-cache openssh-client
    - mkdir -p ~/.ssh && chmod 700 ~/.ssh
    - cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
    - chmod 600 "$SSH_PRIVATE_KEY"
  script:
    - ssh -i "$SSH_PRIVATE_KEY" deploy@"$HOST" "/opt/app/deploy.sh $CI_COMMIT_SHORT_SHA"

deploy_staging:
  extends: .deploy
  variables:
    HOST: $STAGING_HOST
  environment:
    name: staging
    url: https://staging.company.kz
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy_production:
  extends: .deploy
  variables:
    HOST: $PROD_HOST
  environment:
    name: production
    url: https://app.company.kz
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual
  allow_failure: false

What is important here:

  • workflow: rules — the pipeline runs for MR, main , and tags, without duplicates of "push + MR" per branch.
  • cache over package-lock.json — dependencies are not downloaded again until the lock file changes.
  • artifacts: reports: junit — test results are visible directly on the MR page: which tests failed.
  • The image tag is a short SHA of the commit. It always makes it clear which code works, and it's easy to roll back.
  • docker:29-dind — Docker inside the task. For this, a runner with an executor docker must run in privileged = true mode (in /etc/gitlab-runner/config.toml, section [runners.docker]). This is a security compromise — keep such a runner on a separate VM and only for your projects. An alternative without privileged is building through Kaniko or Buildah.
  • when: manual — deploy to the product will appear in the pipeline with a ▶️ button. Who clicked — visible in the environment history.

Step 3. Application server#

On the staging and production server:

  1. The user deploy in the dockergroup, login only with the key, the public part of the key is in ~deploy/.ssh/authorized_keys.
  2. The server must be able to download images from the GitLab registry. Create a Deploy token (Settings → Repository → Deploy tokens) with read_registry rights and run on the server from deploy:
docker login registry.gitlab.company.kz -u gitlab+deploy-token-1
# пароль — значение deploy-токена
  1. The /opt/app contains compose.yaml, .env, and the deploy.shscript, which pulls up the image with the required tag, launches migrations, restarts the container, and checks healthcheck with rollback in case of error. The finished script and parsing are in the part "Docker from scratch, part 4: deploy to server and rollback in a minute."

To prevent the deploy key from running only the deployment script, limit it to authorized_keys:

command="/opt/app/deploy-wrapper.sh",no-port-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAAA... gitlab-ci

where deploy-wrapper.sh takes a tag from $SSH_ORIGINAL_COMMAND and checks that it's just letters and numbers.

Step 4. Production protection#

  • Settings → Repository → Protected branches — main protected (part 3).
  • Settings → CI/CD → Protected environments are available in Premium; in CE, protect the product through Protected variables: PROD_HOST and key are available only to pipelines of the protected branch, and only Maintainers can merge into it.
  • In Operate → Environments, you can see the history: which commit, when, and by whom it was downloaded. The Re-deploy button on the previous deployment is a quick rollback to the previous version.

Step 5. Cleaning the registry#

Each commit in main adds an image. Configure cleanup: Settings → Packages and registries → Container registry → Cleanup policies — for example, keep the last 10 tags and remove tags older than 30 days (except latest). Otherwise, the registry will eat up the GitLab server disk.

Useful techniques#

TaskHow
Do not run CI for README editsrules: - changes: [src/**/*, package*.json]
General templates for allinclude: - project: company/ci-templates file: node.yml
Scheduled launch (night tests, backup)Build → Pipeline schedules
Check the syntax before the commitBuild → Pipeline editor → Validate
Scanninginclude: - template: Jobs/Secret-Detection.gitlab-ci.yml
Skip CI for commitgit push -o ci.skip

If the pipeline does not start#

SymptomCause
The task hangs in pendingthere is no runner with the required tag (docker), the runner is disabled
Cannot connect to the Docker daemonrunner not in privileged mode or not services: docker:dind
Empty secrets in the taskthe Protected variable, and the branch is not protected
Host key verification failednot filled SSH_KNOWN_HOSTS
YAML errorPipeline editor will show the string

Part 5 checklist#

  • Tests and Linter for each MR, results in MR
  • Image with SHA tag in Container Registry
  • Secrets — only in CI/CD Variables, Protected for sale
  • Deploy on staging automatically, on the prod button
  • Rollback via Re-deploy has been verified at least once
  • Registry cleanup policy enabled

The last part is whether it's worth keeping your GitLab at all and what to replace it with: Git for the team, part 6: GitLab, Gitea, Forgejo, or GitHub — what to choose and when to pay.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.