Gitlab CI configuration using Docker socket binding

To avoid rebuild of images on each run there is a possibility to use Docker socket binding. It’s covered in the documentation, here is a more detailed example.

gitlab runner config.toml

[[runners]]
  url = "https://gitlab.com/"
  token = REGISTRATION_TOKEN
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "docker:stable"
    privileged = false
    disable_cache = false
    volumes = ["/var/run/docker.sock:/var/run/docker.sock", "/cache"]
    pull_policy = "if-not-present"
  [runners.cache]
    Insecure = false

Dockerfile with make, git and docker-compose commands to run build.

FROM docker:stable

RUN apk add --no-cache git make openssh-client py3-pip
RUN pip3 install docker-compose

docker-compose.ci.yml

version: '3.4'
services:
  my_app:
    image: repository/project/image_name:${VERSION}
    links:
      - mongo
  mongo:
    image: mongo:3.6.7

Makefile

VERSION = $(shell git rev-parse HEAD)  # use git commit as image version

build: ## build app image
	docker build -t repository/project/image_name:$(VERSION) .

test: ## run tests in container, separate runs by version with `--project-name` option
	VERSION=$(VERSION) docker-compose --project-name app_$(VERSION) -f docker-compose.ci.yml run --rm my_app pytest tests

push: ## push app image to docker repository
	docker push repositiory/project/image_name:$(APP_VERSION)

clean:  ## remove containers after tests
	VERSION=$(VERSION) docker-compose --project-name app_$(VERSION) -f docker-compose.ci.yml down

.gitlab-ci.yml

image: 'image built from the Dockerfile above'

stages:
  - test
  - push

test_app:
  stage: test
  script:
    - make build
    - make test
  after_script:
    - make clean

push_app:
  stage: push
  before_script:
    - docker login ...
  script:
    - make push
comments powered by Disqus