Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

Two-Tier Flask + MySQL App with Docker, Docker Compose & Jenkins CI/CD

Bucket: CI/CD (Continuous Integration / Continuous Delivery) Resume Claim: Built an automated pipeline that takes code from a git push to a running, publicly accessible deployment with zero manual steps.


1. Architecture Overview

Developer (local machine)
        │ git push
        ▼
GitHub Repository  ──webhook──▶  Jenkins (EC2, port 8080)
                                       │
                                       │ Jenkinsfile pipeline:
                                       │  1. Checkout
                                       │  2. docker compose build
                                       │  3. docker compose down / up -d
                                       ▼
                          ┌─────────────────────────────┐
                          │     Single EC2 Instance       │
                          │  (Ubuntu 24.04, t3.small)      │
                          │                                │
                          │  ┌──────────┐   ┌───────────┐ │
                          │  │ flask-app│──▶│  mysql-db  │ │
                          │  │ :5000    │   │  :3306     │ │
                          │  └──────────┘   └───────────┘ │
                          │   (Docker network +            │
                          │    named volume for MySQL)     │
                          └─────────────────────────────┘
                                       │
                                       ▼
                          http://<EC2-IP>:5000  (public)

One EC2 instance plays three roles at once: CI/CD server (Jenkins), container host (Docker), and the deployment target itself. This is intentional for a learning/portfolio project — and you should be able to explain why a real production setup might separate these (covered in the Scaling section).


2. The "Before You Touch Anything" Framework

Before any new install/config step, ask:

  1. What problem does this step solve? (the "why," not just the "what")
  2. What's the dependency order? — does this need something else first?
  3. What's the blast radius if this goes wrong? — reversible? security-impacting? just convenience?
  4. How will I verify it worked? — every step needs a "check" command

And for installing software specifically, the recurring 8-step shape:

  1. Update package lists (apt update)
  2. Install prerequisites (curl, gnupg, certificates)
  3. Add the vendor's signing key
  4. Add the vendor's repo
  5. Update again
  6. Install the software (apt install <package>)
  7. Verify (--version, systemctl status)
  8. Post-install config (group membership, etc.)

This shape applied to both Docker and Jenkins installs below.


3. Phase 1 — AWS Account Safety Net

3.1 Billing Alert

AWS Console → Billing and Cost Management → Budgets → Create budget → template "Zero spend budget" → enter email → Create.

Why: Free tier covers a lot, but it's easy to forget a running instance or attach something non-free. A budget alert emails you the moment any cost appears — a basic hygiene habit for any cloud account.


4. Phase 2 — EC2 Instance Launch

Concepts

  • AMI = OS template (we used Ubuntu 24.04 LTS)
  • Instance type = hardware size. Started on t3.micro (1 vCPU/1GB RAM, free-tier-ish), later vertically scaled to t3.small (2 vCPU/2GB RAM) due to resource exhaustion during Docker builds.
  • Key pair = asymmetric SSH auth. Private .pem stays on your laptop; AWS places the public half on the instance.
  • Security Group = stateful virtual firewall. Inbound rules only — outbound responses to allowed inbound traffic are automatically permitted (this statefulness is the key difference vs. Network ACLs, which are stateless).

Launch steps

  1. EC2 Console → Launch Instance
  2. Name: flask-mysql-cicd
  3. AMI: Ubuntu Server 24.04 LTS
  4. Instance type: t3.small (in hindsight — see Pitfall #9)
  5. Key pair: create new, RSA, .pem format — download and keep safe, AWS won't re-issue it
  6. Security Group inbound rules:
    Type Port Source Purpose
    SSH 22 My IP Remote terminal access
    Custom TCP 5000 0.0.0.0/0 Flask app (public demo)
    Custom TCP 8080 0.0.0.0/0 (or My IP) Jenkins web UI
  7. Storage: default 8GB
  8. Launch

5. Phase 3 — Connecting via SSH (Windows)

Find the .pem file

Get-ChildItem -Path "D:\Downloads" -Filter "*.pem"

Fix permissions (SSH refuses "too open" key files)

icacls "D:\Downloads\flask-cicd-key.pem" /inheritance:r
icacls "D:\Downloads\flask-cicd-key.pem" /grant:r "$($env:USERNAME):(R)"

Connect

ssh -i "D:\Downloads\flask-cicd-key.pem" ubuntu@<public-ip>
  • Default username for Ubuntu AMIs on AWS is ubuntu (Amazon Linux AMIs use ec2-user).
  • First connection: accept the host fingerprint prompt (yes).

6. Phase 4 — Install Docker (the "vendor repo" pattern)

sudo apt update && sudo apt upgrade -y

# Prerequisites
sudo apt install ca-certificates curl gnupg -y

# Add Docker's signing key
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

# Add Docker's repo
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Update + install
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y

# Verify
docker --version
docker compose version

Add user to docker group

sudo usermod -aG docker $USER
newgrp docker
docker ps    # should run with no permission error

Why the docker group matters: the Docker daemon socket (/var/run/docker.sock) is owned by root:docker. Membership in the docker group = ability to run containers without sudo. This same step is needed again later for the jenkins user — that's the classic "Jenkins permission denied on docker socket" issue.

Concept — group changes need a new session: usermod -aG doesn't retroactively apply to an already-open shell. newgrp docker (or logging out/in, or restarting a service) is required.


7. Phase 5 — Install Java + Jenkins (same pattern, two real gotchas)

Java

sudo apt update
sudo apt install fontconfig openjdk-17-jre -y   # NOTE: see Pitfall below — ended up needing Java 21
java -version

Jenkins repo + install

sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \
  https://pkg.jenkins.io/debian-stable/jenkins.io-2026.key     # see Pitfall — key URL had rotated

echo "deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc]" \
  https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
  /etc/apt/sources.list.d/jenkins.list > /dev/null

sudo apt update
sudo apt install jenkins -y
sudo systemctl status jenkins

Add jenkins user to docker group (do this proactively!)

sudo usermod -aG docker jenkins
sudo systemctl restart jenkins

Unlock Jenkins

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Browse to http://<EC2-IP>:8080, paste password, choose "Install suggested plugins", create admin user, accept default Jenkins URL.


8. Phase 6 — Application Code

Project structure (all lowercase — see Pitfall about case-sensitivity):

flask-mysql-cicd/
├── app/
│   ├── app.py
│   ├── requirements.txt
│   └── templates/
│       └── index.html
├── Dockerfile
├── docker-compose.yml
└── Jenkinsfile

8.1 app/requirements.txt

Flask==3.0.3
mysql-connector-python==8.4.0

Why pin versions? Reproducible builds — pip install flask without a version grabs "whatever's latest right now," which can silently change behavior between builds. Pinning means a build today and a build in 6 months behave the same.

8.2 app/app.py

from flask import Flask, render_template, request, redirect
import mysql.connector
import os

app = Flask(__name__)

db_config = {
    'host': os.environ.get('MYSQL_HOST', 'mysql'),
    'user': os.environ.get('MYSQL_USER', 'root'),
    'password': os.environ.get('MYSQL_PASSWORD', 'password'),
    'database': os.environ.get('MYSQL_DATABASE', 'messagedb')
}


def get_db_connection():
    conn = mysql.connector.connect(**db_config)
    return conn


def init_db():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS messages (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            message TEXT NOT NULL
        )
    ''')
    conn.commit()
    cursor.close()
    conn.close()


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        message = request.form['message']

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            'INSERT INTO messages (name, message) VALUES (%s, %s)',
            (name, message)
        )
        conn.commit()
        cursor.close()
        conn.close()

        return redirect('/')

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT name, message FROM messages ORDER BY id DESC')
    messages = cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template('index.html', messages=messages)


if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000)

Key points:

  • Config read from environment variables (os.environ.get) — never hardcode credentials. docker-compose.yml injects these.
  • Default host is 'mysql', not 'localhost' — this is the Docker Compose service-name DNS trick (explained below).
  • SQL uses parameterized queries (%s placeholders + tuple) — prevents SQL injection. Never use f-strings/concatenation for SQL with user input.
  • host='0.0.0.0' — binding to 127.0.0.1 inside a container makes the app unreachable from outside the container. Always 0.0.0.0 in containers.
  • CREATE TABLE IF NOT EXISTS — idempotent; safe to run on every app restart.

8.3 app/templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Two-Tier Flask App</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 0 20px; }
        h1 { color: #333; }
        form { margin-bottom: 30px; }
        input, textarea { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
        button { padding: 10px 20px; background: #4CAF50; color: white; border: none; cursor: pointer; }
        .message { background: #f4f4f4; padding: 10px; margin: 8px 0; border-radius: 4px; }
        .message strong { color: #2c5f2d; }
    </style>
</head>
<body>
    <h1>Flask + MySQL Message Board</h1>

    <form method="POST">
        <label>Name:</label>
        <input type="text" name="name" required>
        <label>Message:</label>
        <textarea name="message" required></textarea>
        <button type="submit">Submit</button>
    </form>

    <h2>Messages</h2>
    {% for msg in messages %}
        <div class="message">
            <strong>{{ msg[0] }}</strong>: {{ msg[1] }}
        </div>
    {% else %}
        <p>No messages yet.</p>
    {% endfor %}
</body>
</html>

Key points:

  • method="POST" matches methods=['GET','POST'] in app.py.
  • name="name" / name="message" inputs map to request.form['name'] / request.form['message'].
  • {% for %}...{% else %}...{% endfor %} — Jinja2 loop with an else for the empty case.
  • msg[0], msg[1] — tuple ordering matches the SELECT name, message column order.

8.4 Dockerfile (project root)

FROM python:3.12-slim

WORKDIR /app

COPY app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app/ .

EXPOSE 5000

CMD ["python", "app.py"]

Key points:

  • python:3.12-slim — pinned, minimal base image.
  • Layer caching order matters: requirements.txt is copied and installed before the rest of the code. If only app.py changes, Docker reuses the cached pip install layer — much faster rebuilds. (Copying everything first would invalidate the cache on every code change.)
  • EXPOSE 5000 is documentation only — doesn't open the port by itself; docker-compose.yml's ports: does that.
  • CMD ["python", "app.py"] — exec form (JSON array), runs as PID 1, handles signals (docker stop) correctly.

8.5 docker-compose.yml (project root)

services:
  mysql:
    image: mysql:8.0
    container_name: mysql-db
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: messagedb
    ports:
      - "3306:3306"
    volumes:
      - mysql-data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-ppassword"]
      interval: 10s
      timeout: 5s
      retries: 5

  flask-app:
    build: .
    container_name: flask-app
    restart: always
    ports:
      - "5000:5000"
    environment:
      MYSQL_HOST: mysql
      MYSQL_USER: root
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: messagedb
    depends_on:
      mysql:
        condition: service_healthy

volumes:
  mysql-data:

Key points:

  • image: vs build: — MySQL uses the official pre-built image; Flask is built from our local Dockerfile (build: .).
  • Service-name DNS: Compose creates a private network where each service is reachable by its service name. MYSQL_HOST: mysql works because mysql resolves to the mysql-db container's internal IP — no manual IP management.
  • Named volume (mysql-data): containers are ephemeral; /var/lib/mysql inside the container would be wiped on recreation without this. The volume persists independently of the container lifecycle.
  • healthcheck + depends_on: condition: service_healthy: MySQL takes time to actually become ready after "starting." Without this, Flask could try to connect during MySQL's init window and crash. Compose waits for the healthcheck to pass before starting flask-app.

8.6 Jenkinsfile (project root)

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build') {
            steps {
                sh 'docker compose build'
            }
        }

        stage('Deploy') {
            steps {
                sh 'docker compose down'
                sh 'docker compose up -d'
            }
        }
    }

    post {
        always {
            sh 'docker ps'
        }
    }
}

Key points:

  • Declarative Pipeline syntax (modern, structured — vs. older "Scripted Pipeline").
  • agent any — runs on the Jenkins server itself (no separate build agents configured).
  • Stage View in Jenkins UI visualizes Checkout → Build → Deploy as boxes with pass/fail status — your portfolio screenshot.
  • docker compose build rebuilds only what changed (uses Dockerfile layer caching).
  • docker compose down then up -d — clean teardown/recreate, avoids port conflicts; -d = detached (non-blocking).
  • post { always { docker ps } } — always prints running containers for quick confirmation in Console Output.
  • Pipeline-as-code: the pipeline definition lives in the repo (version-controlled, reviewable) rather than being clicked together in Jenkins' UI.

9. Phase 7 — Push to GitHub

cd flask-mysql-cicd
git init
git add .
git status

Case-sensitivity fix (Windows → Linux)

Windows is case-insensitive; Linux/Docker is not. If folders end up as App/Templates instead of app/templates, Docker COPY app/... and Flask's render_template() will fail on Linux even though everything "looks fine" locally.

git mv App App_tmp
git mv App_tmp app
git mv app/Templates app/Templates_tmp
git mv app/Templates_tmp app/templates

Commit & push

git commit -m "Initial commit: Flask app, Dockerfile, docker-compose, Jenkinsfile"
git remote add origin https://github.com/<username>/flask-mysql-cicd.git
git branch -M main
git push -u origin main

Note: GitHub requires a Personal Access Token (not password) for HTTPS git operations if not already cached.


10. Phase 8 — Jenkins Pipeline Job

  1. Jenkins Dashboard → New Item → name flask-mysql-pipeline → type Pipeline → OK
  2. Pipeline section:
    • Definition: Pipeline script from SCM
    • SCM: Git
    • Repository URL: https://github.com/<username>/flask-mysql-cicd.git
    • Branch Specifier: */main
    • Script Path: Jenkinsfile
  3. Save → Build Now

11. Phase 9 — GitHub Webhook (true push-to-deploy)

  1. Jenkins job → Configure → Build Triggers → check "GitHub hook trigger for GITScm polling" → Save
  2. GitHub repo → Settings → Webhooks → Add webhook
    • Payload URL: http://<EC2-IP>:8080/github-webhook/ (trailing slash required)
    • Content type: application/json
    • Event: Just the push event
  3. Verify green ✅ in Recent Deliveries

Concept: Webhook = event-driven (GitHub notifies Jenkins instantly on push) vs. polling (Jenkins repeatedly asks "anything new?"). Event-driven is faster and less wasteful.

Caveat: webhook URL is tied to the EC2 instance's current public IP. Stop/start changes the IP → webhook breaks until updated (or use an Elastic IP in a real setup).


12. Pitfalls Encountered — Full List

# Pitfall Root Cause Fix Lesson
1 t2.micro unavailable / wrong AMI shown AWS console quick-start defaults changed Picked Ubuntu 24.04 + t3.micro (later t3.small) explicitly, checked Summary panel Always verify AMI + instance type in the summary before launching
2 .pem file "not found" File was on D:\Downloads, not C:\Users\...\Downloads Get-ChildItem -Recurse to locate it Don't assume default paths
3 docker ps permission denied (avoided proactively) ubuntu user not in docker group usermod -aG docker $USER + newgrp docker Group membership needs new session
4 Jenkins apt update → NO_PUBKEY 7198F4B714ABFC68 Jenkins rotated its GPG signing key (Dec 2025); old key URLs (jenkins.io-2023.key, jenkins.io.key) were expired Found current key: jenkins.io-2026.key Vendor signing keys expire/rotate (~3yr cycle); find current key in vendor's own announcement, not old tutorials
5 Jenkins service failed (Result: exit-code) Jenkins 2.541+ requires Java 21; we had Java 17 apt install openjdk-21-jre + update-alternatives --config java journalctl -u <service> shows the real error in plain English
6 "Start request repeated too quickly" systemd crash-loop protection from repeated Java-version failures sudo systemctl reset-failed jenkins then start Fixing root cause isn't always enough — also clear the rate-limit state
7 git status showed App/Templates/... Folder created with capital letters; Windows is case-insensitive Two-step git mv via temp names to force lowercase rename Linux/Docker paths are case-sensitive — always lowercase for code-referenced paths
8 Browser + SSH froze during first Jenkins build t3.micro (1GB RAM) overwhelmed by Jenkins + Docker image pulls/build simultaneously Stop instance → change instance type to t3.small (2GB) → also added 1GB swap Right-size compute for CI/CD workloads; swap is cheap insurance, not a substitute for adequate RAM
9 SSH "Connection timed out" after instance restart Stop/Start reassigned a new public IP Used new IP from EC2 console Stop/Start ≠ Reboot — IP changes unless using an Elastic IP
10 SSH still timed out after fixing IP Security Group SSH rule was locked to a stale "My IP" snapshot from earlier; home IP had changed Edited inbound rule → re-selected "My IP" to refresh "My IP" is a one-time snapshot, not dynamic
11 docker compose up -d → dependency failed to start: mysql-db is unhealthy MySQL log: --initialize specified but the data directory has files in it — earlier freeze interrupted MySQL's first-time init, leaving a half-initialized volume docker rm -f mysql-db then docker volume rm flask-mysql-pipeline_mysql-data, rebuild Named volumes persist across container recreation — sometimes you need to deliberately reset them; healthcheck/depends_on correctly prevented Flask from starting against broken MySQL

13. Scaling & Production Considerations (talking points)

These weren't all implemented, but you should be able to discuss them:

  • Vertical scaling (done): t3.micro → t3.small when RAM became the bottleneck for concurrent Jenkins + Docker build workloads. Quick fix, but has a ceiling and causes downtime + IP changes during stop/start.
  • Separate CI/CD server from deployment target: in this project, Jenkins and the running app share one box. In production, you'd typically have Jenkins on its own server (or use ephemeral build agents/containers) and deploy to separate app servers — so a heavy build doesn't compete with the live app for resources.
  • Elastic IP: a static public IP that survives stop/start — needed so the GitHub webhook URL and any DNS records don't break.
  • Managed database (e.g., AWS RDS for MySQL): instead of running MySQL in a container on the same host, use a managed DB service — handles backups, patching, failover, and removes the "noisy neighbor" problem of DB + app competing for the same CPU/RAM.
  • Horizontal scaling: running multiple flask-app replicas behind a load balancer (e.g., an Nginx reverse proxy or AWS ALB) for redundancy and to handle more traffic — would require the app to be stateless (it already is, since state lives in MySQL) and the DB to be reachable from multiple hosts (favors a managed DB).
  • HTTPS: currently everything is plain HTTP. A real deployment would put Nginx + Let's Encrypt in front of both Jenkins (8080) and the app (5000), and the webhook would use https://.
  • Secrets management: MYSQL_ROOT_PASSWORD: password is hardcoded in docker-compose.yml for simplicity. Production would use Jenkins Credentials, Docker secrets, or AWS Secrets Manager/Parameter Store instead.
  • Monitoring: nothing here reports health/metrics externally. A natural next step (and the subject of your earlier VPS project) — Prometheus + Grafana, or even just docker stats / CloudWatch agent for basic visibility.
  • Backups: the MySQL named volume has no backup strategy — docker volume rm permanently destroys data, as we experienced firsthand.

14. Interview Summary (one paragraph, memorize the shape of this)

"I built a two-tier Flask + MySQL app, containerized with Docker and Docker Compose, deployed via a Jenkins CI/CD pipeline on an AWS EC2 instance. The Jenkinsfile defines Checkout → Build → Deploy stages as pipeline-as-code, triggered automatically by a GitHub webhook on every push. Along the way I debugged real infrastructure issues: an expired vendor GPG signing key, a Java version mismatch causing a Jenkins systemd crash loop, RAM exhaustion during Docker builds that required vertically scaling the instance, a stale Security Group rule that locked me out over SSH, and a corrupted MySQL data volume from an interrupted container startup — diagnosed via container logs and resolved by understanding Docker volume lifecycle and the healthcheck/depends_on mechanism."


15. REBUILD GUIDE — From Zero, Fast

Use this section to rebuild the entire project quickly (e.g., before an interview demo).

A. AWS Setup (~10 min)

  1. Set a Zero Spend budget alert (Billing → Budgets).
  2. Launch EC2: Ubuntu 24.04, t3.small (skip t3.micro this time — avoids Pitfall #8), create/download a key pair.
  3. Security Group inbound rules: SSH (22, My IP), 5000 (0.0.0.0/0), 8080 (0.0.0.0/0 or My IP).
  4. (Optional, recommended) Allocate and associate an Elastic IP to avoid IP-change issues on stop/start.

B. Connect & Prep Server (~5 min)

ssh -i "<path-to-pem>" ubuntu@<EC2-IP>
sudo apt update && sudo apt upgrade -y

C. Install Docker (~5 min)

sudo apt install ca-certificates curl gnupg -y
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
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y
sudo usermod -aG docker $USER
newgrp docker
docker ps

D. Install Java 21 + Jenkins (~5 min)

sudo apt install fontconfig openjdk-21-jre -y

# Check Jenkins' current signing key URL at https://pkg.jenkins.io/debian-stable/
# (rotates periodically — verify the key year is current!)
sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \
  https://pkg.jenkins.io/debian-stable/jenkins.io-2026.key

echo "deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc]" \
  https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
  /etc/apt/sources.list.d/jenkins.list > /dev/null

sudo apt update
sudo apt install jenkins -y

sudo usermod -aG docker jenkins
sudo systemctl restart jenkins
sudo systemctl status jenkins

E. Jenkins Setup Wizard (~5 min)

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Visit http://<EC2-IP>:8080 → paste password → Install suggested plugins → create admin user → finish.

F. Clone Your Existing Project Code

Since the project code already exists on GitHub from last time, just clone it locally if needed:

git clone https://github.com/<username>/flask-mysql-cicd.git

(All 6 files — app/app.py, app/requirements.txt, app/templates/index.html, Dockerfile, docker-compose.yml, Jenkinsfile — are already correct and committed. No changes needed unless you want to demo a live code change.)

G. Create Jenkins Pipeline Job (~3 min)

New Item → flask-mysql-pipeline → Pipeline → Pipeline script from SCM → Git → your repo URL → branch */main → script path Jenkinsfile → Save.

H. (Optional) Re-add Webhook

GitHub repo → Settings → Webhooks → Add webhook → http://<EC2-IP>:8080/github-webhook/ → application/json → push event. Remember: new IP = update this URL (unless Elastic IP used).

I. Build & Verify

Click Build Now. Watch Stage View go green. Then:

docker ps

Visit http://<EC2-IP>:5000 — submit a test message.

J. After the Demo

Stop or terminate the instance again. If an Elastic IP was allocated, release it when terminating (Elastic IPs incur charges when not attached to a running instance).


16. Quick Command Reference (cheat sheet)

# systemd debugging
sudo systemctl status <service>
sudo systemctl restart <service>
sudo systemctl reset-failed <service>
sudo journalctl -u <service> -n 50 --no-pager

# Docker
docker ps -a
docker images
docker logs <container>
docker compose build
docker compose up -d
docker compose down
docker volume ls
docker rm -f <container>
docker volume rm <volume>

# Groups
sudo usermod -aG <group> <user>
newgrp <group>

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages