Create Docker images in Gitlab CI


I want to create an docker image from an Java Maven project.
We use Gitlab CI Docker Runner for CI Builds and in my opinion there are 2 methods to do this:

  • create docker image directly with maven (this requires an DOCKER_HOST)
  • create docker image in CI Process with an own stage and Dockerfile

I tried this 2 options, but now i describe the second option.

So I added an stage for docker image creation.
Here is my gitlab-ci.yml:

image: maven:3.3.9-jdk-8

#    - chmod +x mvn

  # This will supress any download for dependencies and plugins or upload messages which would clutter the console log.
  # `showDateTime` will show the passed time in milliseconds. You need to specify `--batch-mode` to make this work.
  MAVEN_OPTS: " -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  # As of Maven 3.3.0 instead of this you may define these options in `.mvn/maven.config` so the same config is used
  # when running from the command line.
  # `installAtEnd` and `deployAtEnd`are only effective with recent version of the corresponding plugins.
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"
  MAVEN_VERSION: "3.3.9"
  USER_HOME_DIR: "/root"
  MAVEN_HOME: "/usr/share/maven"

# Cache downloaded dependencies and plugins between builds.
   - /root/.m2/repository/

  - build
  - test
  - analyze
  - docker
  - deploy

  stage: build
    - "mvn clean package -B -Dmaven.test.skip=true
  allow_failure: false

  stage: test
    - "mvn org.jacoco:jacoco-maven-plugin:prepare-agent install -Pcoverage-per-test -B
  allow_failure: false

  stage: analyze
    - "mvn org.jacoco:jacoco-maven-plugin:prepare-agent verify sonar:sonar -Pcoverage-per-test

#Build docker image
  stage: docker
#   - "mvn docker:build"

    # create 2 image tags
    - " docker build -t groupID/artifactID:1.0.4 -t shykes/myapp:latest ."

  stage: deploy
    - "mvn org.jacoco:jacoco-maven-plugin:prepare-agent deploy -Pcoverage-per-test

But it doesnt works, because to create an docker image you have to install an docker host.
How can i install Docker Host and set ENV Variables?

Here is the error:

$ docker build .
/bin/bash: line 50: docker: command not found
ERROR: Build failed: exit code 1

Can anyone help?

You are using image: maven:3.3.9-jdk-8. This image us linux with maven and does not include docker command. Either install docker form apt-get or use gitlab docker image and keep maven in source code folder to avoid maven installation (you can also install maven later). Or install docker in maven image, this is not tried. First method works well and am using in my personal project.