Custom Docker images are very useful in a CI pipeline to test your application. With a custom image you can skip installation skips on every run because they are already done in the image. This saves time and result in faster feedback. The beauty is that the building of the docker images can also be done with GitLab CI. In this post I will explain how I do this.
First you need a Dockerfile like building a docker image on your local machine. In example from: https://gitlab.com/tjvb/phpimages/-/blob/php80/Dockerfile
FROM php:8.0 RUN rm /etc/apt/preferences.d/no-debian-php && \ apt-get update -yqq && \ apt-get install locales openssh-client git zip libzip-dev zlib1g-dev sqlite3 \ libjpeg-dev libjpeg62-turbo libjpeg62-turbo-dev libpng-dev wget libxml2-dev \ php-soap rsync libmagickwand-dev imagemagick -yq --no-install-recommends && \ echo "nl_NL UTF-8" > /etc/locale.gen && \ locale-gen nl_NL.UTF-8 && \ # install imagick # pecl install imagick && \ # docker-php-ext-enable imagick && \ docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg && \ docker-php-ext-install zip bcmath gd exif soap intl pdo_mysql && \ pecl install pcov && \ docker-php-ext-enable pcov && \ # cleanup docker-php-source delete && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # Install composer COPY --from=composer /usr/bin/composer /usr/bin/composer
To use the GitLab CI we need a .gitlab-ci.yml file that tells the CI what it need to do. This is my example from: https://gitlab.com/tjvb/phpimages/-/blob/php80/.gitlab-ci.yml
image: docker:stable services: - docker:dind before_script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY build: stage: build script: - docker build --no-cache --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME . - docker push $CI_REGISTRY_IMAGE
This configuration file tells the runner to use the docker dind services. This is possible with the shared runners for GitLab.com. If you have your own runners you need to be sure to have it enabled. See the GitLab Docs for more information how to enable it and the risk that are involved with it.
The docker login is needed to be able to push the image to the GitLab docker registry. This is done with credentials that GitLab by default provide to the CI jobs. See the Predefined variables list in the GitLab Docs.
The build command use the
$CI_COMMIT_REF_NAME GitLab CI variables. With that variables we tell that the tag is the repository path with the branch name. As example, my
php80 branch on
tjvb/phpimages result in the image tag
tjvb/phpimages:php80. And because I use gitlab.com to host the images I can pull the image from
After building and storing the docker image it is time to use it. I use my PHP80 image in Laravel Mail Catchall and it is possible by using the full path for the image in your GitLab CI.
Start creating and using your own docker images with the GitLab CI and speed up your CI jobs.