tim@kolberger.eu
Photo by kinsey on Unsplash

Tutorial: Road to production - Build docker images with GitLab CI

Build Image

We build our frontend application and copy the build artifacts in an nginx image.

FROM node:10-alpine as builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

RUN npm run build

FROM nginx:mainline-alpine
COPY --from=builder /app/dist/ /usr/share/nginx/html

Create a script to simplify the build process.

# .gitlab-ci/build-frontend.sh
#!/usr/bin/env sh

# stop script on error and log every executed command
set -ex

FRONTEND_IMAGE_TAG=${FRONTEND_IMAGE_TAG:-latest}
FRONTEND_IMAGE="${FRONTEND_IMAGE_NAME}:${FRONTEND_IMAGE_TAG}"

echo $CI_REGISTRY_PASSWORD | \
    docker login \
        -u $CI_REGISTRY_USER \
        --password-stdin $CI_REGISTRY

# Pull image from docker registry and ignore if they do not exist yet
docker pull "${FRONTEND_IMAGE}" || true

# build the web server image
docker build \
    --cache-from  /
    -t ${FRONTEND_IMAGE} /
    -f .docker/frontend/Dockerfile \
    .

# push image to our docker registry
docker push ${FRONTEND_IMAGE}

And execute the build script.

# make script executable
chmod +x .gitlab-ci/build-frontend.sh
# .gitlab-ci.yml
variables:
  FRONTEND_IMAGE_NAME: $CI_REGISTRY_IMAGE/frontend
  FRONTEND_IMAGE_TAG: $CI_COMMIT_REF_SLUG
  CI_REGISTRY_PASSWORD: $CI_JOB_TOKEN
  CI_REGISTRY_USER: gitlab-ci-token

stages:
  - build
  - deploy

build:frontend:
  stage: build
  image: docker:git
  services:
    - docker:dind
  script:
    - .gitlab-ci/build-frontend.sh

deploy:production:
  stage: deploy
  when: manual
  variables:
    BASE_PATH: /var/www/$CI_PROJECT_PATH_SLUG
    DOCKER_COMPOSE_FILE: docker-compose.production.yml
  script:
    - .gitlab-ci/deploy.sh
  environment:
    name: <your-environment-name>
    url: <your-environment-url>
  tags:
    - production # your shell runner
© 2021 Tim KolbergerDatenschutzerklärung