🪔 Happy Diwali Website: OCI + GitLab CI ...

🪔 Happy Diwali Website: OCI + GitLab CI/CD Deployment Notebook

Nov 07, 2026
67

image

End-to-end implementation guide | macOS (Apple Silicon) → GitLab → OCI Ubuntu → Docker/Nginx → Cloudflare Tunnel

Project objective: Build a static website on a MacBook, push it to GitLab, and deploy it automatically to an Oracle Cloud Infrastructure (OCI) Always Free Ubuntu VM whenever code is pushed to main. Nginx serves the site inside Docker. Cloudflare Tunnel publishes it without opening inbound HTTP/HTTPS ports on OCI.

[!NOTE] How to use this notebook

  • Click any ▶ heading to expand or collapse a section (works on GitLab, GitHub and most Markdown viewers).

  • Tick the - [ ] checkboxes as you finish steps (in GitLab/GitHub you can tick them directly in the rendered view).

  • Anything in is a placeholder. Replace it with your own value. Never commit real values to a public repo.


🧭 Quick navigation

# Section Where you work 0 Project overview Read 1 Architecture Read 2 Create the website 💻 MacBook 3 GitLab project 🌐 GitLab 4 OCI account ☁️ OCI Console 5 OCI network ☁️ OCI Console 6 Compute instance ☁️ OCI + 💻 Mac 7 GitLab Runner 🖥️ OCI VM + 🌐 GitLab 8 Sudo access 🖥️ OCI VM 9 Docker via CI/CD Read 10 Compose file 💻 MacBook 11 Pipeline 💻 MacBook 12 Commit & push 💻 MacBook 13 Verify 🌐 GitLab 14 Operational commands 🖥️ OCI VM 15 Troubleshooting Reference 16 Security checklist ✅ Audit 17 Updating the site Daily use 18 Interview explanation Reference 19 Final checklist ✅ Audit

🔤 Placeholders used in this guide

Placeholder Replace with Your GitLab username or group Output of curl -4 https://ifconfig.me on your Mac Public IPv4 shown on the OCI instance page Your chosen OCI region identifier Your SSH private key filename The random subdomain Cloudflare gives your tunnel


📊 Progress tracker (tick as you go)

  • [ ] Website created and tested (§2)

  • [ ] GitLab project ready (§3)

  • [ ] OCI account + network ready (§4–5)

  • [ ] VM running and reachable by SSH (§6)

  • [ ] Runner installed, registered, sudo configured (§7–8)

  • [ ] compose.yaml and .gitlab-ci.yml pushed (§10–12)

  • [ ] Pipeline green, public URL opens (§13)


0. Project overview

▶ What this project demonstrates

  • Static website creation and Git version control.

  • OCI account, networking, compute instance and SSH hardening.

  • GitLab Shell Runner registration and CI/CD.

  • Controlled privileged operations for Docker installation and deployment.

  • Docker Engine, Docker Compose, Nginx and container networking.

  • Cloudflare Quick Tunnel for public access.

  • Deployment verification and GitLab job artifacts.

▶ Important design and cost notes (read before starting)

[!WARNING] 1. OCI Always Free eligibility is subject to Oracle's current terms, capacity and account eligibility. Select a shape explicitly marked Always Free in your tenancy. The example used in this project is VM.Standard.E2.1.Micro with Ubuntu 24.04. Do not assume every region has capacity.

[!NOTE] 2. Cloudflare Quick Tunnel gives a random *.trycloudflare.com URL. It is free and useful for demos, but it is temporary and has no uptime guarantee. A restart/recreation can produce a different URL. It is not a permanent custom domain.

[!TIP] 3. No inbound ports 80 or 443 are required. cloudflared initiates an outbound connection to Cloudflare. The Nginx host port is bound only to 127.0.0.1:8080.

[!CAUTION] 4. The GitLab Shell Runner is powerful. A Shell executor runs jobs directly on the VM. Passwordless sudo makes the job effectively root-capable. Use a dedicated VM, protect main, restrict the runner to the intended project/protected branches, and do not run untrusted merge-request code on it.

[!WARNING] 5. A free VM is resource-constrained. The example E2.1.Micro has limited memory. Avoid running build-heavy workloads, Jenkins, Kubernetes clusters, SonarQube or other large services on the same VM. This project pulls prebuilt Nginx and cloudflared images and does not build application images.


1. End-to-end architecture

▶ 1.1 Logical architecture diagram

flowchart LR
    DEV["Developer MacBook<br/>index.html + Git"] -->|"git push main"| GL["GitLab repository"]
    GL -->|"pipeline trigger"| RUN["GitLab Runner<br/>OCI VM / Shell executor"]
    subgraph OCI["Oracle Cloud Infrastructure"]
      RUN -->|"sudo-controlled deployment"| DOCKER["Docker Engine + Compose"]
      DOCKER --> WEB["Nginx container<br/>diwali-website"]
      DOCKER --> CF["cloudflared container<br/>diwali-tunnel"]
      WEB -->|"Docker bridge network<br/>website:80"| CF
      WEB -->|"127.0.0.1:8080"| LOCAL["VM loopback only"]
    end
    CF -->|"Outbound encrypted tunnel"| EDGE["Cloudflare edge"]
    BROWSER["Visitor browser"] -->|"HTTPS to trycloudflare URL"| EDGE
    EDGE -->|"Tunnel routes to website:80"| CF

▶ 1.2 Deployment sequence

sequenceDiagram
    participant Dev as MacBook
    participant Git as GitLab
    participant Runner as OCI GitLab Runner
    participant Docker as Docker/Compose
    participant Nginx as Nginx container
    participant CF as cloudflared
    participant User as Public browser

    Dev->>Git: Push commit to main
    Git->>Runner: Start tagged pipeline job
    Runner->>Runner: Check sudo and Docker
    Runner->>Docker: Install Docker if missing
    Runner->>Runner: Sync website files to /opt/happy-diwali/public
    Runner->>Docker: docker compose up -d
    Docker->>Nginx: Start/update website
    Docker->>CF: Start tunnel sidecar
    Runner->>Nginx: curl 127.0.0.1:8080
    CF-->>Runner: Quick Tunnel URL in container logs
    User->>CF: HTTPS request
    CF->>Nginx: Forward through tunnel and Docker network
    Nginx-->>User: HTML response
    Runner->>Git: Upload deployment-info.txt artifact

▶ 1.3 Network and security model

Component Address / port Exposure SSH TCP 22 Inbound only from your current MacBook public IPv4 /32 Nginx on OCI host 127.0.0.1:8080 Loopback only; not publicly exposed Nginx in container TCP 80 Docker bridge network cloudflared Outbound HTTPS/QUIC to Cloudflare Outbound only OCI inbound TCP 80 Not opened Not needed OCI inbound TCP 443 Not opened Not needed

Security-list rule: use your actual current public IPv4 address as /32. If your ISP changes your IP, update the SSH ingress rule before the next SSH session.


2. Create the website on your MacBook

▶ 2.1 Prerequisites 💻

Open Terminal on macOS. Install Git if it is not already available:

git --version

If macOS asks to install Command Line Tools, accept the prompt. Create the project:

mkdir -p ~/Happy_Diwali/happy_diwali
cd ~/Happy_Diwali/happy_diwali
  • [ ] Git installed

  • [ ] Project folder created

▶ 2.2 Create index.html 💻

Create the file:

nano index.html

Paste this starter page. Customize the message, colors, images and content as desired.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="A warm Diwali greeting from our family.">
  <title>Happy Diwali 2026</title>
  <style>
    :root {
      color-scheme: dark;
      --gold: #ffd166;
      --orange: #ff8c42;
      --night: #160d2b;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      display: grid;
      place-items: center;
      padding: 24px;
      color: #fff8e8;
      text-align: center;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      background:
        radial-gradient(circle at 50% 20%, #62306e 0, transparent 35%),
        linear-gradient(145deg, var(--night), #35133d 55%, #6c2b26);
    }
    main {
      width: min(720px, 100%);
      padding: clamp(28px, 7vw, 64px);
      border: 1px solid rgba(255, 209, 102, .45);
      border-radius: 28px;
      background: rgba(20, 10, 35, .58);
      box-shadow: 0 24px 80px rgba(0, 0, 0, .35);
    }
    .diya { font-size: clamp(3rem, 10vw, 6rem); }
    h1 {
      margin: 12px 0;
      color: var(--gold);
      font-size: clamp(2.3rem, 8vw, 4.8rem);
      line-height: 1.05;
    }
    p { font-size: clamp(1rem, 2.5vw, 1.25rem); line-height: 1.7; }
    .highlight { color: #ffdca0; font-weight: 700; }
    footer { margin-top: 28px; color: #e8cce8; font-size: .9rem; }
  </style>
</head>
<body>
  <main>
    <div class="diya" aria-hidden="true">🪔✨🪔</div>
    <h1>Happy Diwali 2026!</h1>
    <p>May the festival of lights bring happiness, peace, good health and success.</p>
    <p class="highlight">Wishing you and your family a bright and beautiful Diwali.</p>
    <footer>Made with care • Deployed using GitLab CI/CD on OCI</footer>
  </main>
</body>
</html>

Save in nano: Ctrl+O, Enter, then Ctrl+X.

  • [ ] index.html saved

▶ 2.3 Test locally 💻

python3 -m http.server 8000

Open http://localhost:8000 in your browser. Stop the server with Ctrl+C.

  • [ ] Page renders correctly locally

▶ 2.4 Initialize Git 💻

git init
git branch -M main
git add index.html
git commit -m "Create Diwali greeting website"
  • [ ] First commit created on main


3. Create the GitLab project

▶ Steps 🌐

  1. Sign in to GitLab.

  2. Select New project → Create blank project.

  3. Project name: happy_diwali.

  4. Namespace: your GitLab namespace (shown below as ).

  5. Choose Private or Public according to your preference. A private repository is suitable for this deployment.

  6. Create the project. If GitLab created a README automatically, pull/reconcile it before pushing your local commit.

Add the remote and push:

git remote add origin https://gitlab.com/<YOUR_GITLAB_NAMESPACE>/happy_diwali.git
git push -u origin main

If origin already exists, inspect it first:

git remote -v

Then correct it if required:

git remote set-url origin https://gitlab.com/<YOUR_GITLAB_NAMESPACE>/happy_diwali.git

Repository layout at this stage:

happy_diwali/
├── index.html
└── .git/

The compose.yaml and .gitlab-ci.yml files will be added later.

  • [ ] Project created

  • [ ] main pushed


4. Create an Oracle Cloud Infrastructure account

▶ 4.1 Account registration ☁️

  1. Open the official Oracle Cloud website and choose Start for free.

  2. Enter your real name, email and country/region.

  3. Complete email verification.

  4. Provide the requested address and payment-card verification details.

  5. Select a home region carefully (shown as ). Choose a region suitable for your location and where Always Free capacity is available.

  6. Complete account verification and sign in to the OCI Console.

[!CAUTION] Billing caution: Always Free eligibility does not mean every OCI resource is free. Review the estimated cost and the Always Free eligibility label before creating resources. Do not upgrade to paid resources just to obtain capacity without reviewing the cost.

▶ 4.2 Select the region ☁️

In the OCI Console, verify the selected region in the top navigation. The region where the VM is created determines where its VCN and subnet are created.


5. Create the OCI network

The VM needs a public IP for SSH administration and outbound access. The website itself will not accept inbound public HTTP/HTTPS traffic.

▶ 5.1 Create a VCN ☁️

  1. Open Networking → Virtual Cloud Networks.

  2. Select Create VCN.

  3. Name: vcn-happy-diwali.

  4. IPv4 CIDR block: 10.0.0.0/16.

  5. Create the VCN.

  • [ ] VCN created

▶ 5.2 Create an Internet Gateway ☁️

  1. Open the VCN.

  2. Select Internet Gateways → Create Internet Gateway.

  3. Name: igw-happy-diwali.

  4. Enable it and create.

  • [ ] Internet Gateway created

▶ 5.3 Configure the route table ☁️

Open the VCN's route table and add:

Destination CIDR Target type Target 0.0.0.0/0 Internet Gateway igw-happy-diwali

This permits outbound internet access and return traffic for connections initiated by the VM.

  • [ ] Default route added

▶ 5.4 Create a public subnet ☁️

  1. Select Subnets → Create Subnet.

  2. Name: subnet-happy-diwali-public.

  3. IPv4 CIDR: 10.0.0.0/24.

  4. Subnet type: Regional public subnet (or the equivalent public subnet option in the Console).

  5. Enable public IPv4 address assignment.

  6. Associate the route table that contains the Internet Gateway route.

  7. Associate the security list configured in the next section.

  • [ ] Public subnet created

▶ 5.5 Restrict SSH to your MacBook public IP ☁️ 🔒

Find your current public IPv4 address from your MacBook:

curl -4 https://ifconfig.me

Take the result and append /32. For example, if the command prints A.B.C.D, your SSH CIDR is A.B.C.D/32 (shown in this guide as /32).

In the VCN Security List (or a Network Security Group attached to the VM), add this ingress rule:

Source CIDR IP protocol Destination port Purpose /32 TCP 22 SSH administration

Remove any broad SSH rule such as 0.0.0.0/0 → TCP 22.

Do not add ingress rules for TCP 80 or TCP 443. The Cloudflare Tunnel is outbound.

[!NOTE] If your public IP changes, SSH will stop working until you update the rule. A VPN, office network or mobile hotspot may present a different public IP. A /32 rule allows exactly one IPv4 address.

  • [ ] SSH ingress limited to /32

  • [ ] No 0.0.0.0/0 SSH rule

  • [ ] No inbound 80/443 rules


6. Create the OCI compute instance

▶ Steps ☁️

  1. Open Compute → Instances → Create instance.

  2. Name: instance-happy-diwali.

  3. Image: Ubuntu 24.04 LTS (the project was tested on Ubuntu 24.04).

  4. Shape: choose an explicitly Always Free eligible shape available in your region. The example deployment used VM.Standard.E2.1.Micro.

  5. Networking:

    • Select the VCN created above.

    • Select subnet-happy-diwali-public.

    • Assign a public IPv4 address.

  6. SSH keys:

    • Choose Generate a key pair and download the private key, or upload your own public key.

    • Store the private key securely on your MacBook.

  7. Review and create the instance.

  • [ ] Instance running

▶ 6.1 Protect the SSH private key on macOS 💻 🔒

If the downloaded key is in ~/Downloads, move it to ~/.ssh:

mkdir -p ~/.ssh
mv ~/Downloads/<YOUR_KEY_FILE> ~/.ssh/<YOUR_KEY_FILE>
chmod 600 ~/.ssh/<YOUR_KEY_FILE>

Use the actual downloaded filename. Do not upload the private key to GitLab, commit it to the repository, or paste it into chat.

  • [ ] Key moved to ~/.ssh

  • [ ] Permissions set to 600

▶ 6.2 Connect to Ubuntu 💻

Copy the VM's public IPv4 address from the OCI instance details:

ssh -i ~/.ssh/<YOUR_KEY_FILE> ubuntu@<YOUR_OCI_PUBLIC_IP>

On first connection, verify the host fingerprint through a trusted channel before accepting it.

  • [ ] SSH login works

▶ 6.3 Initial OS checks 🖥️

whoami
lsb_release -a
uname -m
free -h
df -h /

Expected user: ubuntu; OS: Ubuntu 24.04. The VM's architecture depends on the selected shape.

▶ 6.4 Optional swap for a small-memory VM 🖥️

Swap can reduce the chance of immediate out-of-memory termination, but it is slower than RAM and does not turn a small VM into a large one. Check available disk space first.

sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
swapon --show
free -h

Do not create swap if the VM's storage is insufficient. Monitor disk usage after enabling it.


7. Install and register GitLab Runner on OCI

▶ 7.1 Install GitLab Runner 🖥️

Run these commands on the OCI Ubuntu VM during the initial setup:

sudo apt-get update
sudo apt-get install -y curl ca-certificates
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
sudo apt-get install -y gitlab-runner
sudo systemctl enable --now gitlab-runner
sudo systemctl status gitlab-runner --no-pager
gitlab-runner --version

The runner service should be active.

  • [ ] Runner installed and service active

▶ 7.2 Create a project runner in GitLab 🌐

  1. Open the happy_diwali project in GitLab.

  2. Navigate to Settings → CI/CD → Runners.

  3. Create a new project runner.

  4. Set the tag to oci-shell.

  5. Enable the option that makes the runner run jobs only when its tags match.

  6. Prefer restricting the runner to protected branches.

  7. Copy the runner authentication token. Treat it as a secret.

  • [ ] Project runner created with tag oci-shell

  • [ ] Token copied (never commit or share it)

▶ 7.3 Register the runner on OCI 🖥️

Run:

sudo gitlab-runner register

Enter the values requested by the registration wizard:

Prompt Value GitLab instance URL https://gitlab.com Token Project runner authentication token from GitLab Description oci-happy-diwali-runner Tags oci-shell Executor shell

If prompted for an optional maintenance note, enter a short description or leave it blank.

Check:

sudo gitlab-runner list
sudo gitlab-runner verify
sudo systemctl status gitlab-runner --no-pager

The runner should appear online in the project's Runners page.

  • [ ] Runner shows online in GitLab

▶ 7.4 Understand the Shell executor ⚠️

A Shell executor runs CI scripts directly on the OCI VM as the gitlab-runner operating-system user. It does not isolate jobs in a container. Therefore:

  • Use a dedicated VM for this runner.

  • Keep the runner assigned only to this trusted project.

  • Protect the main branch and runner.

  • Do not allow untrusted fork or merge-request jobs to run on this runner.

  • Do not store cloud credentials or private SSH keys in the repository.

  • Keep the runner concurrency at 1 on a small VM.


8. Give the runner controlled Docker administration access

There are two common patterns:

  • Docker group membership: convenient, but membership in the Docker group is effectively root-equivalent on a conventional Linux host.

  • Narrow sudo policy: can limit which Docker commands the runner may execute, but maintaining an exact command allowlist is difficult because Docker Compose invokes Docker in several ways.

For this small, dedicated, protected-branch deployment runner, the example uses a dedicated sudoers rule. This is still highly privileged. It is not a strong security boundary against malicious CI code.

▶ 8.1 Recommended project-specific sudo policy 🖥️ 🔒

On OCI, create the policy:

sudo visudo -f /etc/sudoers.d/gitlab-runner-happy-diwali

For the simplest reliable deployment policy, add:

gitlab-runner ALL=(root) NOPASSWD: /usr/bin/apt-get, /usr/bin/curl, /usr/bin/install, /usr/bin/tee, /usr/bin/rsync, /usr/bin/cp, /usr/bin/systemctl, /usr/bin/docker

[!CAUTION] Important security limitation: Allowing apt-get, curl, tee, systemctl and Docker permits powerful system changes. The rule is narrower than unrestricted NOPASSWD: ALL, but it is not a sandbox. For a stronger design, use a root-owned deployment script with fixed arguments and grant sudo access only to that script. The script itself must be root-owned and not writable by gitlab-runner.

Validate syntax:

sudo visudo -cf /etc/sudoers.d/gitlab-runner-happy-diwali

Check the runner can execute the required commands without a password:

sudo -u gitlab-runner sudo -n /usr/bin/docker --version
sudo -u gitlab-runner sudo -n /usr/bin/systemctl is-active gitlab-runner

If your system's executable paths differ, check them with command -v docker, command -v apt-get, etc. and adjust the policy. Do not add the runner to the Docker group as well unless you deliberately choose that alternative.

  • [ ] Sudoers file created

  • [ ] visudo -cf passes

  • [ ] Passwordless test commands succeed

▶ 8.2 Runner concurrency 🖥️

Edit /etc/gitlab-runner/config.toml as an administrator:

sudo nano /etc/gitlab-runner/config.toml

Keep global concurrency at 1:

concurrent = 1
check_interval = 0
shutdown_timeout = 0

[session_server]
  session_timeout = 1800

Do not delete the [[runners]] registration block created by gitlab-runner register. Restart and verify:

sudo systemctl restart gitlab-runner
sudo systemctl status gitlab-runner --no-pager
  • [ ] concurrent = 1

  • [ ] Runner restarted and active


9. Install Docker Engine and Docker Compose through CI/CD

The pipeline below installs Docker automatically if it is missing. This keeps repeatable installation in source-controlled automation rather than relying on manual SSH for routine deployment.

The official Docker APT repository is used. The pipeline installs:

  • Docker Engine (docker-ce)

  • Docker CLI (docker-ce-cli)

  • containerd (containerd.io)

  • Docker Buildx plugin

  • Docker Compose plugin

The installation is idempotent: if Docker and Compose are already installed, it skips the package installation.


10. Create the Nginx website container and Cloudflare Tunnel

▶ compose.yaml 💻

Create compose.yaml in the root of the GitLab repository:

services:
  website:
    image: nginx:alpine
    container_name: diwali-website
    restart: unless-stopped
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - /opt/happy-diwali/public:/usr/share/nginx/html:ro
    networks:
      - diwali-network

  cloudflared:
    image: cloudflare/cloudflared:latest
    container_name: diwali-tunnel
    restart: unless-stopped
    command:
      - tunnel
      - --no-autoupdate
      - --url
      - http://website:80
    depends_on:
      - website
    networks:
      - diwali-network

networks:
  diwali-network:
    driver: bridge
  • [ ] compose.yaml created in repo root

▶ 10.1 Understand the Compose file

Setting Explanation nginx:alpine Small prebuilt Nginx image container_name Stable container name used by operational commands restart: unless-stopped Restart container after daemon/VM restart unless explicitly stopped 127.0.0.1:8080:80 Bind host port 8080 only to loopback and forward to container port 80 :ro Mount website files read-only inside Nginx diwali-network Private Docker bridge shared by the two containers http://website:80 cloudflared reaches Nginx by Compose service DNS name --url Runs a Cloudflare Quick Tunnel to the local origin

▶ 10.2 Request flow

flowchart TB
    VIS["Visitor browser"] -->|"HTTPS: random-name.trycloudflare.com"| EDGE["Cloudflare edge"]
    EDGE <-->|"Outbound tunnel connection"| CF["cloudflared container"]
    CF -->|"http://website:80 over Docker bridge"| NG["Nginx container"]
    NG -->|"Read-only bind mount"| FILES["/opt/happy-diwali/public/index.html"]
    LOCAL["OCI localhost:8080"] -->|"127.0.0.1 only"| NG

Nginx is not directly exposed on the VM's public IP. The visitor reaches Cloudflare, and Cloudflare forwards the request through the outbound tunnel.


11. Add the complete GitLab CI/CD pipeline

Create .gitlab-ci.yml in the repository root. This pipeline:

  1. Runs only for the main branch.

  2. Checks the runner identity and sudo.

  3. Installs Docker Engine and Compose if needed.

  4. Enables Docker.

  5. Detects whether the site is in the repository root or in public/.

  6. Synchronizes the site to /opt/happy-diwali/public.

  7. Copies and validates compose.yaml.

  8. Starts/updates Nginx and cloudflared.

  9. Checks local Nginx health.

  10. Extracts the Quick Tunnel URL from cloudflared logs.

  11. Checks public reachability.

  12. Saves deployment metadata as a 30-day artifact.

▶ .gitlab-ci.yml (full pipeline) 💻

stages:
  - check
  - deploy

workflow:
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
    - when: never

check_oci_permissions:
  stage: check
  tags:
    - oci-shell
  script:
    - echo "Checking runner identity"
    - whoami
    - id
    - |
      sudo -n true
      echo "Passwordless sudo is available"
    - |
      if command -v docker >/dev/null 2>&1; then
        sudo docker --version
      else
        echo "Docker will be installed in deployment stage"
      fi

deploy_happy_diwali:
  stage: deploy
  tags:
    - oci-shell
  script:
    - |
      set -eu

      if ! command -v docker >/dev/null 2>&1 || ! sudo docker compose version >/dev/null 2>&1; then
        echo "Installing Docker Engine and Compose plugin..."

        sudo apt-get update
        sudo apt-get install -y ca-certificates curl rsync

        sudo install -m 0755 -d /etc/apt/keyrings
        sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
          -o /etc/apt/keyrings/docker.asc
        sudo chmod a+r /etc/apt/keyrings/docker.asc

        CODENAME=$(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
        ARCH=$(dpkg --print-architecture)

        printf 'Types: deb\nURIs: https://download.docker.com/linux/ubuntu\nSuites: %s\nComponents: stable\nArchitectures: %s\nSigned-By: /etc/apt/keyrings/docker.asc\n' \
          "$CODENAME" "$ARCH" |
          sudo tee /etc/apt/sources.list.d/docker.sources >/dev/null

        sudo apt-get update
        sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
      fi

      sudo systemctl enable --now docker
      sudo docker --version
      sudo docker compose version

    - sudo install -d -m 0755 /opt/happy-diwali/public
    - sudo apt-get install -y rsync

    - |
      if [ -f public/index.html ]; then
        SOURCE_DIR="public/"
      elif [ -f index.html ]; then
        SOURCE_DIR="./"
      else
        echo "ERROR: index.html not found in repository root or public/"
        exit 1
      fi

      echo "Website source directory: $SOURCE_DIR"

    - |
      sudo rsync -a --delete \
        --exclude='.git/' \
        --exclude='.gitlab-ci.yml' \
        --exclude='.gitignore' \
        --exclude='README*' \
        --exclude='.DS_Store' \
        --exclude='compose.yaml' \
        --exclude='docker-compose.yml' \
        "$SOURCE_DIR" /opt/happy-diwali/public/

    - sudo cp compose.yaml /opt/happy-diwali/compose.yaml
    - sudo docker compose -p happy-diwali -f /opt/happy-diwali/compose.yaml config -q
    - sudo docker compose -p happy-diwali -f /opt/happy-diwali/compose.yaml up -d

    - |
      curl --fail --silent --show-error \
        --retry 10 --retry-connrefused --retry-delay 2 \
        http://127.0.0.1:8080/ -o /dev/null
      echo "Nginx website is responding successfully"

    - |
      echo "Waiting for Cloudflare Quick Tunnel URL..."
      URL=""

      for i in $(seq 1 30); do
        URL=$(sudo docker logs diwali-tunnel 2>&1 |
          grep -Eo 'https://[-a-zA-Z0-9.]+\.trycloudflare\.com' |
          tail -n 1 || true)

        if [ -n "$URL" ]; then
          break
        fi

        echo "Waiting for tunnel URL... $i/30"
        sleep 2
      done

      if [ -z "$URL" ]; then
        echo "ERROR: Cloudflare URL was not found in tunnel logs"
        sudo docker logs --tail 100 diwali-tunnel
        exit 1
      fi

      {
        echo "Website URL: $URL"
        echo "Commit: $CI_COMMIT_SHORT_SHA"
        echo "Branch: $CI_COMMIT_REF_NAME"
        echo "Pipeline ID: $CI_PIPELINE_ID"
        echo "Deployment time UTC: $(date -u)"
      } > deployment-info.txt

      echo "PUBLIC WEBSITE: $URL"

    - |
      curl --fail --silent --show-error \
        --retry 10 --retry-connrefused --retry-delay 3 \
        "$URL" -o /dev/null
      echo "Public website is accessible"

    - sudo docker ps
    - echo "Happy Diwali deployment completed"

  artifacts:
    name: "happy-diwali-$CI_COMMIT_SHORT_SHA"
    when: always
    expire_in: 30 days
    paths:
      - deployment-info.txt

  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
  • [ ] .gitlab-ci.yml created in repo root

  • [ ] Validated with GitLab CI Lint

▶ 11.1 YAML and pipeline safety checks

  • Keep .gitlab-ci.yml indentation exactly as shown. YAML uses spaces, not tabs.

  • The multi-line shell commands are under - |, so shell syntax such as if, printf and pipes remain inside the script block.

  • workflow prevents this deployment pipeline from running on non-main branches. If you later want validation pipelines on feature branches, change the workflow and keep privileged deployment restricted to protected main.

  • The check_oci_permissions job assumes the runner has the required sudo policy.

  • The deployment job assumes the compose.yaml file exists in the repository root.

  • The runner should be configured for protected branches and the main branch should be protected.


12. Commit and push the deployment files

Your repository should now look like:

happy_diwali/
├── index.html
├── compose.yaml
├── .gitlab-ci.yml
└── .git/

Commit and push:

git add index.html compose.yaml .gitlab-ci.yml
git commit -m "Add OCI Docker and Cloudflare automated deployment"
git push origin main

Every subsequent push to main will trigger the deployment pipeline.

  • [ ] Files committed

  • [ ] Push to main done


13. Verify the pipeline

▶ Verification steps 🌐

In GitLab:

  1. Open the happy_diwali project.

  2. Select Build → Pipelines.

  3. Open the latest pipeline.

  4. Confirm both jobs succeed:

    • check_oci_permissions

    • deploy_happy_diwali

  5. Open the deployment job log and find PUBLIC WEBSITE.

The URL should look like:

https://<RANDOM_NAME>.trycloudflare.com

Open it in a browser. It should display the Diwali website.

  • [ ] Both jobs green

  • [ ] Public URL opens the site

▶ 13.1 Download deployment metadata

The deployment job publishes deployment-info.txt as an artifact for 30 days.

Expected example:

Website URL: https://<RANDOM_NAME>.trycloudflare.com
Commit: <SHORT_SHA>
Branch: main
Pipeline ID: <PIPELINE_ID>
Deployment time UTC: <DATE_TIME>

The values above are placeholders. Use the actual values from your pipeline.

To download it: Build → Pipelines → latest pipeline → deploy_happy_diwali job → Job artifacts.


14. Operational commands (only for troubleshooting)

Routine deployment should happen through GitLab CI/CD. These commands are for diagnosis if the pipeline or service fails.

▶ 14.1 Check containers 🖥️

sudo docker ps
sudo docker compose -p happy-diwali -f /opt/happy-diwali/compose.yaml ps

▶ 14.2 Inspect Nginx logs 🖥️

sudo docker logs --tail 100 diwali-website

▶ 14.3 Inspect Cloudflare Tunnel logs 🖥️

sudo docker logs --tail 150 diwali-tunnel

▶ 14.4 Test the local Nginx origin 🖥️

curl -I http://127.0.0.1:8080/

▶ 14.5 Check Docker daemon 🖥️

sudo systemctl status docker --no-pager
sudo docker info

▶ 14.6 Check runner 🖥️

sudo systemctl status gitlab-runner --no-pager
sudo gitlab-runner verify

▶ 14.7 Check disk and memory 🖥️

free -h
df -h
sudo docker stats --no-stream

15. Troubleshooting guide

💡 Find your symptom in the table, then expand the matching log commands below.

Symptom Likely cause Resolution Runner is offline Service stopped, token/registration issue, network problem Check systemctl status gitlab-runner, verify runner in GitLab, inspect service logs Job stuck waiting for runner Tag mismatch or runner not assigned to project Confirm job tag oci-shell and runner tag oci-shell sudo: a password is required Sudoers policy missing or invalid Validate with visudo -cf; test sudo -u gitlab-runner sudo -n ... docker: command not found Docker package installation failed Inspect apt output and Docker repository architecture/codename Docker permission denied Job is not using sudo or policy does not permit Docker Use sudo docker ...; validate sudoers docker compose not found Compose plugin missing Install docker-compose-plugin from Docker's repository Nginx returns default page Website files not copied to the mounted directory Check repository source path and /opt/happy-diwali/public/index.html Nginx health check fails Container not ready, invalid mount or port conflict Inspect docker ps, Nginx logs and port 8080 Tunnel URL not found cloudflared has not connected, container exited, or logs differ Inspect docker logs diwali-tunnel; check outbound DNS/network Public URL fails but localhost works Tunnel not connected or Quick Tunnel has changed Inspect cloudflared logs and retrieve the latest URL SSH timeout Public IP changed or ingress CIDR is wrong Recheck Mac public IPv4 and update TCP 22 /32 rule Pipeline YAML invalid Indentation, tabs or malformed block scalar Use GitLab CI Lint before committing VM runs out of memory Too many services or insufficient memory Keep only Runner, Docker, Nginx and cloudflared; inspect memory and swap

▶ 15.1 Useful service logs 🖥️

sudo journalctl -u gitlab-runner -n 100 --no-pager
sudo journalctl -u docker -n 100 --no-pager

16. Security checklist

  • [ ] OCI SSH ingress allows only your current Mac public IPv4 /32.

  • [ ] No 0.0.0.0/0 SSH ingress rule remains.

  • [ ] No inbound TCP 80 or 443 rule exists.

  • [ ] Nginx binds to 127.0.0.1:8080, not 0.0.0.0:8080.

  • [ ] SSH private key is stored only on your Mac and has restrictive file permissions.

  • [ ] GitLab runner is dedicated to this trusted project.

  • [ ] main is protected.

  • [ ] Runner is restricted to protected branches and matching tags.

  • [ ] No untrusted merge-request pipeline can execute on the privileged Shell runner.

  • [ ] Sudoers file is validated with visudo.

  • [ ] Repository contains no private keys, passwords or cloud secrets.

  • [ ] Docker images are reviewed and updated deliberately.

  • [ ] OCI Always Free usage and billing are monitored.


17. What happens when you update the website?

For a normal content update, the workflow is:

flowchart TD
    A["Edit index.html on MacBook"] --> B["git add / git commit"]
    B --> C["git push origin main"]
    C --> D["GitLab starts pipeline"]
    D --> E["OCI runner syncs new website files"]
    E --> F["Compose ensures Nginx and cloudflared are running"]
    F --> G["Local and public health checks"]
    G --> H["deployment-info.txt artifact uploaded"]
    H --> I["Updated website visible through public URL"]

Example:

# Edit index.html, then:
git add index.html
git commit -m "Update Diwali greeting"
git push origin main

You do not need to SSH into OCI for normal content updates.

Tunnel URL lifecycle: As long as the existing cloudflared Quick Tunnel process remains alive, its URL generally remains the same. If the container/process is recreated, Cloudflare may issue a new random URL. The next successful pipeline should capture the URL from the tunnel logs and publish it in the artifact.


18. Interview-ready project explanation

▶ Expand the full explanation

Project title: Automated Static Website Deployment on OCI using GitLab CI/CD, Docker, Nginx and Cloudflare Tunnel.

Problem statement: Deploy a static website to a cloud VM with repeatable CI/CD while minimizing public attack surface and avoiding inbound web ports.

Solution: A GitLab Shell Runner on an OCI Ubuntu VM executes a protected main-branch pipeline. The pipeline installs Docker Engine and Compose when needed, synchronizes website files to a host directory, validates the Compose configuration and starts Nginx and cloudflared containers. Nginx serves the static site on a loopback-only host binding. cloudflared creates an outbound Quick Tunnel to the Nginx service over a private Docker bridge network. The pipeline verifies the local origin and public URL, then publishes deployment metadata as an artifact.

Key engineering decisions:

  • Shell executor: simple and low overhead for a small dedicated VM, but requires strict trust and privilege controls.

  • Docker Compose: manages the two related containers and their private network as one application.

  • Read-only bind mount: Nginx can serve website content but cannot modify the host-mounted files.

  • Loopback port binding: prevents direct public access to the Nginx host port.

  • Cloudflare Tunnel: avoids opening inbound web ports or exposing the origin IP as a web endpoint.

  • GitLab artifacts: retain the deployed URL and commit metadata for traceability.

Limitations and production improvements:

  • Quick Tunnel is temporary and intended for testing/demo use, not production uptime.

  • For a production domain, use a named Cloudflare Tunnel with a domain managed in Cloudflare and store its tunnel credentials as protected GitLab CI/CD variables or another secret manager.

  • For stronger runner isolation, use a dedicated deployment service or a locked-down root-owned deployment script instead of broad sudo permissions.

  • Pin container images to tested versions or digests rather than relying indefinitely on latest.

  • Add monitoring, alerting, backups and a rollback strategy before treating the site as production infrastructure.


19. Final project checklist

  • [ ] index.html created and tested locally.

  • [ ] GitLab project created and main branch pushed.

  • [ ] OCI account and region selected.

  • [ ] VCN, Internet Gateway, route table and public subnet created.

  • [ ] SSH restricted to MacBook public IP /32.

  • [ ] Ubuntu 24.04 Always Free eligible instance running.

  • [ ] SSH key secured on MacBook.

  • [ ] GitLab Runner installed and registered with oci-shell.

  • [ ] Protected main branch and runner restrictions configured.

  • [ ] Controlled sudo access configured and validated.

  • [ ] compose.yaml committed.

  • [ ] .gitlab-ci.yml committed.

  • [ ] Docker Engine and Compose installed by pipeline.

  • [ ] Nginx and cloudflared containers running.

  • [ ] Local Nginx health check passes.

  • [ ] Cloudflare Quick Tunnel URL extracted.

  • [ ] Public URL opens the website.

  • [ ] deployment-info.txt artifact uploaded.

Final outcome: a push to GitLab main triggers an automated deployment to OCI, and the website is made publicly accessible through Cloudflare Tunnel without opening inbound ports 80 or 443 on the VM.


▶ 🔍 Appendix: Sanitization log (what was changed for privacy)

Original Replaced with Reason https://gitlab.com/123456789/happy_diwali.git (and namespace text) https://gitlab.com//happy_diwali.git Account/namespace identifier 203.0.113.10/32, 198.51.100.25 (example IPs) /32, A.B.C.D Remove IP literals, even documentation-range ones ap-hyderabad-1 Reveals approximate location oci-happy-diwali.key Key filename tied to the project Sample tunnel URL, commit hash, pipeline ID, timestamp , , , Avoid publishing real deployment identifiers

No passwords, tokens, private keys or real public IPs were found in the original. Technical content was otherwise left unchanged.

Ti piace questo post?

Offri un caffè a DigeratiDaily

Altro da DigeratiDaily

PrivacyTermini