Gitlab CI - example build Docker image

Moki Lv6

Variables assigned to project/group:

  • DEPLOY_SSH_PRIVATE_KEY - example result of ssh-keygen -t ed25519
  • DEPLOY_SSH_USER - example: root
  • TARGET_DIR - example: /var/www/my-project/

.env

1
VERSION=

docker-compose.yml

1
2
3
4
5
version: '3.8'

services:
project_name:
image: example.com/path/to/project:$VERSION

.gitlab-ci.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
image: docker

stages:
- build
- deploy

build:
stage: build
services:
- docker:dind
script:
- docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
- docker pull "${CI_REGISTRY_IMAGE}:latest" || true ; docker image ls
- docker build -t "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}" -t "${CI_REGISTRY_IMAGE}:latest" .
- docker push "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}"
- docker push "${CI_REGISTRY_IMAGE}:latest"

.deploy:
stage: deploy
needs:
- build
before_script:
- apk add openssh-client rsync
- eval $(ssh-agent -s)
- ssh-add <(echo "$DEPLOY_SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
script:
- export SSH_PART="ssh -p 22"
- alias SSH="$SSH_PART $DEPLOY_SSH_USER@$SRV"
- alias RSYNC="rsync -e '$SSH_PART'"

- docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
- docker pull "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}"
- docker save "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}" | SSH "docker load"

- RSYNC --include .env --include docker-compose.yml --exclude="*" -Cavr ./ $DEPLOY_SSH_USER@$SRV:$TARGET_DIR
- SSH "mkdir -p $TARGET_DIR ; cd $TARGET_DIR && sed -i 's/VERSION=.*/VERSION=${CI_COMMIT_SHORT_SHA}/g' .env && docker compose up -d"

only:
- master

deploy_srv1:
extends: .deploy
variables:
SRV: 1.1.1.1

deploy_srv2:
extends: .deploy
variables:
SRV: 2.2.2.2
On this page
Gitlab CI - example build Docker image