Skip to main content

GitLab CI Pipeline - Docker Compose Deployment: Containerize and Deploy Static Website Project via Docker Compose; Image Build Naming Convention

1714 words·
GitLab GitLab CI CI Pipeline Docker-Compose Apache Unprivileged Container
Table of Contents
GitHub Repository Available



Overview
#

In this tutorial I’m using the following setup based on Ubuntu 22.04 servers, GitLab is dockerized:

192.168.70.4 # GitLab
192.168.70.5 # GitLab Runner
192.168.70.6 # Deployment Server with Docker installed



GitLab Repository
#

Overview & GitHub Repository
#

This GitLab CI Pipeline and Docker Compose manifest offer two versions for the naming convention of the build & deployed container image.

# Define the image name for Apache, tagging it with the GitLab CI registry and the current commit SHA
APACHE_IMAGE_SHA: $CI_REGISTRY_IMAGE/apache:$CI_COMMIT_SHA

# Define the image name for Apache, tagging it with the GitLab CI registry and just "latest"
APACHE_IMAGE_LATEST: $CI_REGISTRY_IMAGE/apache:latest

The final images names look like this:

# APACHE_IMAGE_SHA:
gitlab-registry.jklug.work/static-websites/simple-static-website-compose/apache:16c1e59bcb936927be3f65469ccf1953d2f3c094

# APACHE_IMAGE_LATEST:
gitlab-registry.jklug.work/static-websites/simple-static-website-compose/apache:latest

This repository is available on GitHub:
https://github.com/jueklu/simple-static-website-compose



File and Folder Structure
#

The file and folder structure of the GitLab project looks like this:

GitLab-Repository
├── Docker-Compose
│   └── docker-compose-apache.tmpl
├── Dockerfiles
│   └── Dockerfile-Apache
├── .gitlab-ci.yml
├── public
│   ├── css
│   │   └── styles.css
│   ├── index.html
│   └── js
│       └── scripts.js
└── README.md

CI Pipeline Manifest
#

Image:SHA Version
#

  • .gitlab-ci.yml
### Variables
variables:
  DEPLOY_IP: "192.168.70.6"  # Deployment server IP
  DEPLOY_USER: "gitlab-deployment"  # Deployment server SSH user

  # Define the image name for Apache, tagging it with the GitLab CI registry and the current commit SHA
  APACHE_IMAGE_SHA: $CI_REGISTRY_IMAGE/apache:$CI_COMMIT_SHA
  # Define the image name for Apache, tagging it with the GitLab CI registry and just "latest"
  APACHE_IMAGE_LATEST: $CI_REGISTRY_IMAGE/apache:latest


### Stages
stages:
  - build
  - deploy


### Build Container
build-apache:
  stage: build
  image: docker:20.10.16
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
  services:
    - docker:20.10.16-dind
  before_script:
    # Log in to the GitLab Container registry using CI credentials
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $CI_REGISTRY_IMAGE/apache:latest || true
    # Build the Apache Docker image / enable caching from the previously pulled image / tag the new image with the current commit SHA and as "latest"
    - docker build -f Dockerfiles/Dockerfile-Apache --cache-from $CI_REGISTRY_IMAGE/apache:latest --tag $APACHE_IMAGE_SHA --tag $CI_REGISTRY_IMAGE/apache:latest .
    # Push the newly built image to the GitLab Container registry
    - docker push $APACHE_IMAGE_SHA
    # Push the image tagged as "latest" to the GitLab Container registry
    - docker push $CI_REGISTRY_IMAGE/apache:latest


### Deploy Container to Virtual Machine
deploy_apache:
  stage: deploy
  image: alpine:latest
  before_script:
    # Update the package index, install OpenSSH client and gettext for envsubst
    - apk update && apk add openssh-client gettext
    # If the private SSH key file ($ID_RSA) exists, set secure permissions (read/write for the owner only)
    - if [ -f "$ID_RSA" ]; then chmod og= $ID_RSA; fi
  script:
    # SSH into the deployment server, log in to the GitLab Container registry
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY"
    # Substitute environment variables in the Docker Compose template to generate final Docker Compose file
    - envsubst < Docker-Compose/docker-compose-apache.tmpl > docker-compose-apache.yml
    # Copy generated Docker Compose file to the deployment server
    - scp -i $ID_RSA -o StrictHostKeyChecking=no docker-compose-apache.yml $DEPLOY_USER@$DEPLOY_IP:/tmp
    # SSH into the deployment server, stop any running containers defined in the Docker Compose file
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "cd /tmp; docker compose -f docker-compose-apache.yml down"
    # SSH into the deployment server, start the containers defined in the Docker Compose file
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "cd /tmp; docker compose -f docker-compose-apache.yml up -d"
  rules:
    # Rule: Run this job only for main branch
    - if: $CI_COMMIT_BRANCH == "main"

Image:latest Version
#

  • .gitlab-ci.yml
### Variables
variables:
  DEPLOY_IP: "192.168.70.6"  # Deployment server IP
  DEPLOY_USER: "gitlab-deployment"  # Deployment server SSH user

  # Define the image name for Apache, tagging it with the GitLab CI registry and the current commit SHA
  APACHE_IMAGE_SHA: $CI_REGISTRY_IMAGE/apache:$CI_COMMIT_SHA
  # Define the image name for Apache, tagging it with the GitLab CI registry and just "latest"
  APACHE_IMAGE_LATEST: $CI_REGISTRY_IMAGE/apache:latest


### Stages
stages:
  - build
  - deploy


### Build Container
build-apache:
  stage: build
  image: docker:20.10.16
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
  services:
    - docker:20.10.16-dind
  before_script:
    # Log in to the GitLab Container registry using CI credentials
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $CI_REGISTRY_IMAGE/apache:latest || true
    # Build the Apache Docker image / enable caching from the previously pulled image / tag the new image with the current commit SHA and as "latest"
    - docker build -f Dockerfiles/Dockerfile-Apache --cache-from $CI_REGISTRY_IMAGE/apache:latest --tag $APACHE_IMAGE_LATEST --tag $CI_REGISTRY_IMAGE/apache:latest .
    # Push the newly built image to the GitLab Container registry
    - docker push $APACHE_IMAGE_LATEST
    # Push the image tagged as "latest" to the GitLab Container registry
    - docker push $CI_REGISTRY_IMAGE/apache:latest


### Deploy Container to Virtual Machine
deploy_apache:
  stage: deploy
  image: alpine:latest
  before_script:
    # Update the package index, install OpenSSH client and gettext for envsubst
    - apk update && apk add openssh-client gettext
    # If the private SSH key file ($ID_RSA) exists, set secure permissions (read/write for the owner only)
    - if [ -f "$ID_RSA" ]; then chmod og= $ID_RSA; fi
  script:
    # SSH into the deployment server, log in to the GitLab Container registry
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY"
    # Substitute environment variables in the Docker Compose template to generate final Docker Compose file
    - envsubst < Docker-Compose/docker-compose-apache.tmpl > docker-compose-apache.yml
    # Copy generated Docker Compose file to the deployment server
    - scp -i $ID_RSA -o StrictHostKeyChecking=no docker-compose-apache.yml $DEPLOY_USER@$DEPLOY_IP:/tmp
    # SSH into the deployment server, stop any running containers defined in the Docker Compose file
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "cd /tmp; docker compose -f docker-compose-apache.yml down"
    # SSH into the deployment server, start the containers defined in the Docker Compose file
    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_IP "cd /tmp; docker compose -f docker-compose-apache.yml up -d"
  rules:
    # Rule: Run this job only for main branch
    - if: $CI_COMMIT_BRANCH == "main"



Dockerfile
#

  • Dockerfiles/Dockerfile-Apache
# Use the Alpine base image
FROM alpine:latest

# Install Apache2
RUN apk update && apk add apache2 && rm -rf /var/cache/apk/*

# Copy website files to the document root
COPY public/ /var/www/localhost/htdocs/

# Set ownership and permissions for Apache directories
RUN chown -R apache:apache /var/www && \
    chown -R apache:apache /run/apache2 && \
    chown -R apache:apache /var/log/apache2 && \
    chmod -R 770 /var/run/apache2 && \
    chmod -R 770 /var/log/apache2 && \
    chown -R apache:apache /etc/apache2

# Start Apache2 using non-root user
USER apache

# Expose the default Apache port
EXPOSE 80

# Start Apache
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]

Docker Compose Manifest
#

Image:SHA Version
#

  • Docker-Compose/docker-compose-apache.tmpl
services:
  apache:
    image: ${APACHE_IMAGE_SHA}
    container_name: apache-container # Define container name
    ports:
      - 8080:80
    restart: unless-stopped

Image:latest Version
#

  • Docker-Compose/docker-compose-apache.tmpl
services:
  apache:
    image: ${APACHE_IMAGE_LATEST}
    container_name: apache-container # Define container name
    ports:
      - 8080:80
    restart: unless-stopped



Static Website
#

HTML File
#

  • public/index.html
<!DOCTYPE html>
<html>

<head>
    <title>jklug.work</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>

<body>
    <h1>Some HTML</h1>
    <p>Hi there, click me.</p>
    <!-- Add a button -->
    <button id="myButton">Click Me</button>

    <!-- Link to the JavaScript file -->
    <script src="js/scripts.js"></script>
</body>

</html>

CSS File
#

  • public/css/styles.css
/* General styling for the body */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;

    /* Flexbox centering */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh; /* Full viewport height */
}

/* Header styling */
h1 {
    color: #333;
    margin: 0 0 10px 0; /* Remove default margin and add spacing */
}

/* Paragraph styling */
p {
    color: #666;
    font-size: 18px;
    margin: 10px 0; /* Add some spacing */
}

/* Button styling */
button {
    background-color: #d2691e;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 20px; /* Add space above the button */
}

/* Button hover effect */
button:hover {
    background-color: #8b4513;
}

JavaScript File
#

  • public/js/scripts.js
// Function to handle button clicks
function handleButtonClick() {
    const paragraph = document.querySelector("p");
    // Toggle text between text
    if (paragraph.textContent === "Hi there, click me.") {
        paragraph.textContent = "Button was clicked.";
    } else {
        paragraph.textContent = "Hi there, click me.";
    }
}

// Attach event listener when the DOM is ready
document.addEventListener("DOMContentLoaded", () => {
    const button = document.querySelector("#myButton");
    button.addEventListener("click", handleButtonClick);
});



Deployment Server Prerequisites
#

Create SSH Key Pair
#

Create a SSH key pair on the server where GitLab is deployed:

# Create SSH key pair
ssh-keygen -t rsa -b 2048

Create a User for the Container Deployment
#

On the deployment server, create a new user “gitlab-deployment” that is used by the deploy_container job of the GitLab CI pipeline:

# Create user for the GitLab deployment
sudo adduser gitlab-deployment

# Add the user to the Docker group
sudo usermod -aG docker gitlab-deployment

Add Public Key & Fingerprint
#

Copy the public SSH key to the authorized keys file of the Deployment servers:

# Copy the public SSH key: Default "id_rsa.pub" key
ssh-copy-id gitlab-deployment@192.168.70.6

# Copy the public SSH key: Define specific key
ssh-copy-id -i ~/.ssh/filename.pub gitlab-deployment@192.168.70.6

SSH into the deployment server to add the fingerprint:

# SSH into deployment server
ssh gitlab-deployment@192.168.70.6

DNS Entry
#

Make sure the deployment server can resolve the DNS names of GitLab and the GitLab Registry:

# Add the following DNS entry
192.168.70.4 gitlab.jklug.work gitlab-registry.jklug.work

Add SSH Key as CI/CD Variable
#

Add the previously created private SSH key as variable to the simple-static-website-pipeline project:

  • Go to: (Project) “Settings” > “CI/CD”

  • Expand the “Variables” section

  • Select “Type”: “File”

  • Define “Key”: ID_RSA

  • Paste the private SSH key as “Value”

  • Click “Add variable” to add a variable for your private SSH Key.

Note: Remove the “Protect variable” option so that it can be used in different branches.



Verify the Deployment
#

Image:SHA Version
#

SSH into the deployment server:

# List containers
docker ps

# Shell output:
CONTAINER ID   IMAGE                                                                                                                      COMMAND                  CREATED              STATUS              PORTS                                     NAMES
350ecc2eee93   gitlab-registry.jklug.work/static-websites/simple-static-website-compose/apache:f598a38f3b474625dcb05c2941cf1cebe645e479   "/usr/sbin/httpd -D …"   About a minute ago   Up About a minute   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp   apache-container

Verify the Apache server:

# Curl the container
curl localhost:8080

# Shell output:
<!DOCTYPE html>
<html>

<head>
    <title>jklug.work</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>

Image:latest Version
#

SSH into the deployment server:

# List containers
docker ps

# Shell output:
CONTAINER ID   IMAGE                                                                                    COMMAND                  CREATED              STATUS              PORTS                                     NAMES
b2a76bf584af   gitlab-registry.jklug.work/static-websites/simple-static-website-compose/apache:latest   "/usr/sbin/httpd -D …"   About a minute ago   Up About a minute   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp   apache-container

Verify the Apache server:

# Curl the container
curl localhost:8080

# Shell output:
<!DOCTYPE html>
<html>

<head>
    <title>jklug.work</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>



Links #

jueklu/simple-static-website-compose

GitLab CI Pipeline - Containerize and Deploy Static Website Project with Docker Compose

CSS
0
0