Gitlab-runner to build docker images with shell executor code example

Example: Gitlab-runner to build docker images with shell executor

### Use Gitlab-runner to build docker images with shell executor ###

# ---------- Install GitLab Runner: using official GitLab repo ---------
# https://docs.gitlab.com/runner/install/linux-repository.html

# 1. Add the official GitLab repository:
# For Debian/Ubuntu/Mint
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | sudo bash

# For RHEL/CentOS/Fedora
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh" | sudo bash

# 2. Install the latest version of GitLab Runner:
# For Debian/Ubuntu/Mint
export GITLAB_RUNNER_DISABLE_SKEL=true; sudo -E apt-get install gitlab-runner

# For RHEL/CentOS/Fedora
export GITLAB_RUNNER_DISABLE_SKEL=true; sudo -E yum install gitlab-runner

# 3. Remove ".bash_logout" file in gitlab-runner user's home folder if any
# check the "/home/gitlab-runner" folder.
# https://docs.gitlab.com/runner/shells/index.html#shell-profile-loading

# ------- Registration --------------
# https://docs.gitlab.com/ee/ci/docker/using_docker_build.html

# 1. Go to the terminal where you have installed the gitlab-runner.

# 2. register the runner.Select the shell executor.
# Note: change the 'url' and 'registration-token' accordingly.
sudo gitlab-runner register -n \
  --url https://gitlab.com/ \
  --registration-token SWRMY9uYjgev-Go1e3F7 \
  --executor shell \
  --description "My New Shell Runner"
  
# 3. On the server where GitLab Runner is installed, install Docker Engine.   
  
# 4. Add the gitlab-runner user to the docker group:
sudo usermod -aG docker gitlab-runner
  
# 5. Verify that gitlab-runner has access to Docker:
sudo -u gitlab-runner -H docker info
 
# 6. In GitLab, to verify that everything works, add docker info to .gitlab-ci.yml:

# -------- .gitlab-ci.yml file ------------

stages:
  - build

docker-build:
  variables:
    TARGET_NAME: "mydockerHubID/myImageName"
    TAG_NAME: ":whatEverTag"
  stage: build
  # tags:
  #   - api
  before_script:
    - export DYNAMIC_ENV_VAR=BUILD
	- docker info
    - docker login -u "$DOCKER_USER" -p "$DOCKER_HUB_PWD"
  script:
    - docker build --pull -t "$TARGET_NAME${TAG_NAME}" .
    - docker push "$TARGET_NAME${TAG_NAME}"
	## to run any tests if you want to
	# - docker run "$TARGET_NAME${TAG_NAME}" /script/to/run/tests
    - echo "build success!!"
  # Run this job in a branch where a Dockerfile exists
  rules:
    - if: $CI_COMMIT_BRANCH
      exists:
        - Dockerfile