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.
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).
Before any new install/config step, ask:
- What problem does this step solve? (the "why," not just the "what")
- What's the dependency order? — does this need something else first?
- What's the blast radius if this goes wrong? — reversible? security-impacting? just convenience?
- How will I verify it worked? — every step needs a "check" command
And for installing software specifically, the recurring 8-step shape:
- Update package lists (
apt update) - Install prerequisites (curl, gnupg, certificates)
- Add the vendor's signing key
- Add the vendor's repo
- Update again
- Install the software (
apt install <package>) - Verify (
--version,systemctl status) - Post-install config (group membership, etc.)
This shape applied to both Docker and Jenkins installs below.
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.
- 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
.pemstays 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).
- EC2 Console → Launch Instance
- Name:
flask-mysql-cicd - AMI: Ubuntu Server 24.04 LTS
- Instance type: t3.small (in hindsight — see Pitfall #9)
- Key pair: create new, RSA,
.pemformat — download and keep safe, AWS won't re-issue it - 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 - Storage: default 8GB
- Launch
Get-ChildItem -Path "D:\Downloads" -Filter "*.pem"icacls "D:\Downloads\flask-cicd-key.pem" /inheritance:r
icacls "D:\Downloads\flask-cicd-key.pem" /grant:r "$($env:USERNAME):(R)"ssh -i "D:\Downloads\flask-cicd-key.pem" ubuntu@<public-ip>- Default username for Ubuntu AMIs on AWS is
ubuntu(Amazon Linux AMIs useec2-user). - First connection: accept the host fingerprint prompt (
yes).
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 versionsudo usermod -aG docker $USER
newgrp docker
docker ps # should run with no permission errorWhy 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.
sudo apt update
sudo apt install fontconfig openjdk-17-jre -y # NOTE: see Pitfall below — ended up needing Java 21
java -versionsudo 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 jenkinssudo usermod -aG docker jenkins
sudo systemctl restart jenkinssudo cat /var/lib/jenkins/secrets/initialAdminPasswordBrowse to http://<EC2-IP>:8080, paste password, choose "Install suggested plugins", create admin user, accept default Jenkins URL.
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
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.
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.ymlinjects these. - Default host is
'mysql', not'localhost'— this is the Docker Compose service-name DNS trick (explained below). - SQL uses parameterized queries (
%splaceholders + tuple) — prevents SQL injection. Never use f-strings/concatenation for SQL with user input. host='0.0.0.0'— binding to127.0.0.1inside a container makes the app unreachable from outside the container. Always0.0.0.0in containers.CREATE TABLE IF NOT EXISTS— idempotent; safe to run on every app restart.
<!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"matchesmethods=['GET','POST']inapp.py.name="name"/name="message"inputs map torequest.form['name']/request.form['message'].{% for %}...{% else %}...{% endfor %}— Jinja2 loop with anelsefor the empty case.msg[0],msg[1]— tuple ordering matches theSELECT name, messagecolumn order.
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.txtis copied and installed before the rest of the code. If onlyapp.pychanges, Docker reuses the cachedpip installlayer — much faster rebuilds. (Copying everything first would invalidate the cache on every code change.) EXPOSE 5000is documentation only — doesn't open the port by itself;docker-compose.yml'sports:does that.CMD ["python", "app.py"]— exec form (JSON array), runs as PID 1, handles signals (docker stop) correctly.
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:vsbuild:— MySQL uses the official pre-built image; Flask is built from our localDockerfile(build: .).- Service-name DNS: Compose creates a private network where each service is reachable by its service name.
MYSQL_HOST: mysqlworks becausemysqlresolves to themysql-dbcontainer's internal IP — no manual IP management. - Named volume (
mysql-data): containers are ephemeral;/var/lib/mysqlinside 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 startingflask-app.
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 buildrebuilds only what changed (uses Dockerfile layer caching).docker compose downthenup -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.
cd flask-mysql-cicd
git init
git add .
git statusWindows 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/templatesgit 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 mainNote: GitHub requires a Personal Access Token (not password) for HTTPS git operations if not already cached.
- Jenkins Dashboard → New Item → name
flask-mysql-pipeline→ type Pipeline → OK - 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
- Save → Build Now
- Jenkins job → Configure → Build Triggers → check "GitHub hook trigger for GITScm polling" → Save
- 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
- Payload URL:
- 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).
| # | 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 |
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-appreplicas 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: passwordis hardcoded indocker-compose.ymlfor 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 rmpermanently destroys data, as we experienced firsthand.
"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."
Use this section to rebuild the entire project quickly (e.g., before an interview demo).
- Set a Zero Spend budget alert (Billing → Budgets).
- Launch EC2: Ubuntu 24.04, t3.small (skip t3.micro this time — avoids Pitfall #8), create/download a key pair.
- Security Group inbound rules: SSH (22, My IP), 5000 (0.0.0.0/0), 8080 (0.0.0.0/0 or My IP).
- (Optional, recommended) Allocate and associate an Elastic IP to avoid IP-change issues on stop/start.
ssh -i "<path-to-pem>" ubuntu@<EC2-IP>
sudo apt update && sudo apt upgrade -ysudo 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 pssudo 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 jenkinssudo cat /var/lib/jenkins/secrets/initialAdminPasswordVisit http://<EC2-IP>:8080 → paste password → Install suggested plugins → create admin user → finish.
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.)
New Item → flask-mysql-pipeline → Pipeline → Pipeline script from SCM → Git → your repo URL → branch */main → script path Jenkinsfile → Save.
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).
Click Build Now. Watch Stage View go green. Then:
docker psVisit http://<EC2-IP>:5000 — submit a test message.
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).
# 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>