George Fedoseev
George Fedoseev

Reputation: 102

How to rebuild docker image on push before CI script jobs

I want to generate Dockerfile in GitLab CI script and build it. Then use this newly generated image in build jobs. How can I do this? Tried to use global before_script, but it already starts in default container. I need to do this out of any containers.

Upvotes: 1

Views: 1595

Answers (1)

tmt
tmt

Reputation: 8634

before_script is run before every job so it's not something you want. But you can have a first job to do the image build and take advantage of the fact that each job can use a different Docker image. The build of the image is covered in the manual.

Option A (uhm... sort of OK)

Have 2 runners, one with a shell executor (tagged shell) and one with a Docker executor (tagged docker). You would then have a first stage with a job dedicated to building the docker image. It would use the shell runner.

image_build:
  stage: image_build
  script:
    - # create dockerfile
    - # run docker build
    - # push image to a registry
  tags:
    - shell

The second job would then run using the runner with docker executor and use this created image:

job_1:
  stage: test
  image: [image you created]
  script:
    - # your tasks
  tags:
    - docker

The problem with this is that the runner would need to be part of the docker group which has security implications.

Option B (better)

The second option would do the same but would have only one runner using Docker executor. The Docker image would be built within a running container (gitlab/dind:latest image) = "docker in docker" solution.

stages:
  - image_build
  - test

image_build:
  stage: image_build
  image: gitlab/dind:latest
  script:
    - # create dockerfile
    - # run docker build
    - # push image to a registry

job_1:
  stage: test
  image: [image you created]
  script:
    - # your tasks

Upvotes: 2

Related Questions