
Docker from scratch, part 3: CI — build, tests, and image per commit
🌐 Machine-translated from Russian. Show original
In this part:
What is CI and why is it needed#
Continuous Integration — for each push server automatically assembles the project, runs tests and linters. The error is visible minutes after the commit, not on the prod. At the same time, CI collects the Docker image and places it in the registry — then the same image goes to the server.
GitHub Actions Pipeline#
File .github/workflows/ci.yml:
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
image:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
testis triggered on every push and pull request;image— only for main and only if the tests passed;- the image receives the commit SHA tag — it always shows which code is inside.
The same on GitLab CI#
File .gitlab-ci.yml:
stages: [test, build]
test:
stage: test
image: node:22-alpine
script:
- npm ci
- npm run lint
- npm test
build:
stage: build
image: docker:27
services: [docker:27-dind]
only: [main]
script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
- docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" .
- docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA"
Secrets in CI#
- Passwords and keys — only in Secrets (GitHub) or CI/CD Variables with the Masked/Protected flag (GitLab).
- Never print secrets in the log (
echo $TOKEN). - For pull requests from forks, secrets are unavailable — and that's correct.
Speeding up the pipeline#
- The dependency cache (
cache: npmin setup-node) saves minutes on each run. - Parallel jobs: linter, unit tests, and e2e can be run simultaneously.
- Path filters: do not rush backend builds if only the documentation has changed (
paths/rules: changes).
Protection of the main branch#
Enable in the repository settings: merge to main only via pull request and only with green CI. This is the main thing CI gives the command: broken code does not physically enter main.
What's next#
The image with the verified code lies in the registry. In part 4 , we will deliver it to the server automatically and learn to roll back in a minute.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.