惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
MyScale Blog
MyScale Blog
Microsoft Security Blog
Microsoft Security Blog
量子位
B
Blog
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
T
The Exploit Database - CXSecurity.com
N
News | PayPal Newsroom
Cloudbric
Cloudbric
A
About on SuperTechFans
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
S
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 最新话题
T
The Blog of Author Tim Ferriss
Simon Willison's Weblog
Simon Willison's Weblog
有赞技术团队
有赞技术团队
H
Heimdal Security Blog
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
N
News and Events Feed by Topic
IT之家
IT之家
Know Your Adversary
Know Your Adversary
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
B
Blog RSS Feed
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
博客园 - 叶小钗
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
The Hacker News
The Hacker News
Y
Y Combinator Blog
I
Intezer
The Register - Security
The Register - Security
F
Full Disclosure
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I Built, Scanned, and Automated a Docker Pipeline
Yaa Kesewaa · 2026-05-09 · via DEV Community

I recently completed a hands-on Docker and DevSecOps lab as part of my learning track, and I wanted to write up the full walkthrough — including the parts where things broke, because that's honestly where the real learning happened.

By the end of this lab, I had:

  • Pulled and inspected a public container image from Docker Hub
  • Built a Python Flask web app and packaged it into a secure Docker image
  • Pushed it to Docker Hub and shared it
  • Automated the entire workflow with a GitHub Actions pipeline that includes Trivy vulnerability scanning as a hard security gate

This article walks you through each phase exactly as I did it, including the three issues I ran into and how I resolved them. If you're replicating this yourself, this should save you some time.


What You'll Need

Before you start, make sure you have:

  • Docker Desktop installed and running
  • A GitHub account
  • A Docker Hub account
  • A code editor (VS Code recommended)

You'll also need a Docker Hub Personal Access Token — not your password. Generate one at:
hub.docker.com → Avatar → Account Settings → Security → New Access Token

Give it Read & Write permissions and copy it straight away. You only see it once.


Phase 0 — Pull and Inspect a Public Container

The first phase is simple but important. Before building anything yourself, you act as a consumer — you pull a public image, run it, and observe what happens.

# Pull the lightweight Nginx image
docker pull nginx:alpine

# Run it in detached mode, mapping host port 8080 to container port 80
docker run -d -p 8080:80 --name my-nginx nginx:alpine

# Check it's running
docker ps

# View the logs
docker logs my-nginx

# Clean up
docker rm -f my-nginx

Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8080 in your browser and you'll see the Nginx welcome page.

What just happened? You downloaded a pre-built filesystem (the image) from Docker Hub, and Docker spun up an isolated process (the container) from it. The -p 8080:80 flag mapped port 80 inside the container to port 8080 on your machine, making it reachable from your browser.

This pull-and-run flow is the foundation of everything else in the lab.

Phase 0 — Pulling the nginx:alpine image,Running the container and confirming with docker ps, Pulling the nginx:alpine image from Docker Hub in the terminal


Phase 1 — Build, Push, Pull & Share Your Own Image

Now you become the image creator. This phase has you build a Python Flask web application, write a Dockerfile, push the image to Docker Hub, and share it.

The Project Structure

your-project/
├── app.py
├── templates/
│   └── index.html
├── requirements.txt
├── Dockerfile
└── .dockerignore

Enter fullscreen mode Exit fullscreen mode

Project structure Project folder structure in VS Code showing all the required files

The Application

app.py — A minimal Flask app with a home page and a /health endpoint.

from flask import Flask, render_template, jsonify
import os, datetime

app = Flask(__name__)
APP_NODE = os.environ.get("APP_NODE", "developer")

@app.route("/")
def home():
    return render_template("index.html", node=APP_NODE)

@app.route("/health")
def health():
    return jsonify({
        "status": "healthy",
        "node": APP_NODE,
        "time": datetime.datetime.utcnow().isoformat() + "Z"
    })

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

Enter fullscreen mode Exit fullscreen mode

The APP_NODE variable is read from the environment. This externalises configuration from code — you can inject any identifier at runtime without rebuilding the image.

templates/index.html

<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body style="font-family: sans-serif; text-align: center; padding-top: 5rem;">
    <h1>Hello from <span style="color: #2b6cb0;">{{ node }}</span></h1>
    <p>This container is alive and running!</p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

requirements.txt

flask==3.0.0

Enter fullscreen mode Exit fullscreen mode

Pinning the version ensures reproducible builds.

The Dockerfile

FROM python:3.11-slim

LABEL maintainer="your-name@example.com"
LABEL version="1.0.0"
LABEL description="Simple Flask web app for Docker/GitHub Actions lab"

# Create a non-root user — running as root in a container is a security risk
RUN groupadd -r appuser && useradd -r -g appuser appuser

WORKDIR /app

# Copy requirements first to leverage Docker layer caching
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN chown -R appuser:appuser /app
USER appuser

EXPOSE 5000

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:5000/health || exit 1

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

Enter fullscreen mode Exit fullscreen mode

Two things worth calling out here:

Non-root user: If the application is ever compromised, an attacker running as a non-root user has far less access than one running as root. It's a foundational security hardening step.

Layer caching order: Copying requirements.txt before the rest of the application code means Docker's build cache is preserved for the pip install layer as long as dependencies haven't changed. If you only modified app.py, Docker doesn't reinstall packages — it reuses the cached layer. This significantly speeds up builds, especially in CI pipelines.

.dockerignore

__pycache__
*.pyc
*.pyo
.git
.env
*.md
Dockerfile
.dockerignore

Enter fullscreen mode Exit fullscreen mode

Without .dockerignore, your entire .git directory and any local .env files would be copied into the image — inflating its size and potentially exposing secrets.

Build and Test

docker build -t my-web-app .
docker run -d -p 5000:5000 --name webapp-test my-web-app

Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:5000 for the home page and http://localhost:5000/health for the health check.

Building the image docker build output showing all layers building successfully

Testing the app at localhost:5000 Flask app home page loading at localhost:5000

Health check returning JSON The /health endpoint returning a JSON response in the browser

Push to Docker Hub

docker login -u your-dockerhub-username
docker tag my-web-app your-dockerhub-username/my-web-app:v1.0.0-yourname
docker push your-dockerhub-username/my-web-app:v1.0.0-yourname

Enter fullscreen mode Exit fullscreen mode

The tag format <version>-<yourname> makes your image personally traceable — useful when you're sharing a registry with other learners.

Pushing to Docker Hub Pushing the tagged image to Docker Hub in the terminal

Docker Hub repository set to public Docker Hub showing the repository set to public

Pull Your Own Image

To simulate being a new user, delete your local copy and pull it from Docker Hub:

docker rmi your-dockerhub-username/my-web-app:v1.0.0-yourname
docker pull your-dockerhub-username/my-web-app:v1.0.0-yourname
docker run -d -p 5000:5000 --name pulled-app your-dockerhub-username/my-web-app:v1.0.0-yourname

Enter fullscreen mode Exit fullscreen mode

Pulling the image from Docker Hub* Pulling the image back from Docker Hub after deleting the local copy*

Running the container from the pulled image Running a container from the freshly pulled image

![Testing the pulled image]](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wwzlfwsj8ejpvb3i632.png) Home page working correctly from the pulled image

Health check on the pulled image Health endpoint responding correctly from the pulled image

The image should behave identically to your local build — which is the point. Portability is a core Docker guarantee.


Phase 2 — Automate with a GitHub Actions DevSecOps Pipeline

This is where it gets interesting. Phase 2 takes everything manual from Phase 1 and automates it in a CI/CD pipeline that runs on every push to main.

The pipeline:

  1. Builds the Docker image
  2. Scans it for vulnerabilities with Trivy
  3. Only pushes to Docker Hub if the scan passes
  4. Runs a smoke test to verify the pushed image works

Set Up GitHub Secrets

Go to your repo → Settings → Secrets and variables → Actions → New repository secret

Add two secrets:

  • DOCKERHUB_USERNAME — your Docker Hub username
  • DOCKERHUB_TOKEN — your access token

These must be two separate secrets. More on why this matters in the issues section below.

The Workflow File

Create .github/workflows/docker-build-push.yml:

name: Build, Scan, Push and Verify Docker Image

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  DOCKER_HUB_USER: ${{ secrets.DOCKERHUB_USERNAME }}
  IMAGE_NAME: my-web-app
  TAG_SUFFIX: yourname

jobs:
  build-scan-push-verify:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Build Docker image (load locally, do not push yet)
        uses: docker/build-push-action@v5
        with:
          context: .
          load: true
          push: false
          tags: |
            ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:v1.0.0-${{ env.TAG_SUFFIX }}
            ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:latest

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@v0.20.0
        with:
          image-ref: "${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:v1.0.0-${{ env.TAG_SUFFIX }}"
          format: 'table'
          exit-code: '1'
          ignore-unfixed: true
          severity: 'HIGH,CRITICAL'

      - name: Push Docker image to Hub
        if: success()
        run: |
          docker push ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:v1.0.0-${{ env.TAG_SUFFIX }}
          docker push ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:latest

      - name: Pull image and run smoke tests
        if: success()
        run: |
          docker pull ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:v1.0.0-${{ env.TAG_SUFFIX }}
          docker run -d -p 5000:5000 --name verify-container \
            ${{ env.DOCKER_HUB_USER }}/${{ env.IMAGE_NAME }}:v1.0.0-${{ env.TAG_SUFFIX }}
          sleep 5
          curl -f http://localhost:5000/health || (echo "Health check failed!" && exit 1)
          curl -s http://localhost:5000/ | grep -i "hello" || (echo "Home page missing greeting!" && exit 1)
          echo "All smoke tests passed."

      - name: Remove test container
        if: always()
        run: docker rm -f verify-container || true

Enter fullscreen mode Exit fullscreen mode

Two conditional flags worth understanding:

  • if: success() on the push step — this ensures we never push an image that hasn't passed all previous steps, especially the vulnerability scan.
  • if: always() on the cleanup step — this guarantees the test container is removed even if earlier steps failed, preventing orphaned processes on the runner.

Push and Trigger

git add .github/workflows/docker-build-push.yml
git commit -m "Add DevSecOps CI pipeline"
git push

Enter fullscreen mode Exit fullscreen mode

Then go to the Actions tab in your repo and watch it run.


The Issues I Ran Into

This is the section I actually want people to read. The happy path above is clean, but this is what happened in practice.


Issue 1 — Docker Hub Credentials Not Set Up as Separate Secrets

The first pipeline run failed at login. The runner couldn't authenticate with Docker Hub.

The problem was that I hadn't properly separated the credentials into two distinct GitHub secrets. The docker/login-action needs username and password as completely separate values:

username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}

Enter fullscreen mode Exit fullscreen mode

Once I added them as two separate secrets — DOCKERHUB_USERNAME and DOCKERHUB_TOKEN — the login step worked.

Key takeaway: Never combine credentials into a single secret, and never use your Docker Hub password here — use the Personal Access Token.


Issue 2 — Trivy Action Version Tag Missing the v Prefix

The pipeline got past login and build, then failed at the Trivy step with an "Unable to resolve action" error.

The cause was a missing v in the action version tag:

# Broken
uses: aquasecurity/trivy-action@0.20.0

# Correct
uses: aquasecurity/trivy-action@v0.20.0

Enter fullscreen mode Exit fullscreen mode

GitHub Actions resolves action versions against the actual Git tags in the action's repository. The official release tag is v0.20.0 — without the v, it can't find it.

Key takeaway: Always check the official action repository for the exact tag format. Most actions use v prefixes — a missing v is an easy mistake and produces an unhelpful error message.


Issue 3 — Trivy Flagging HIGH and CRITICAL Vulnerabilities, Blocking the Push

With the version tag corrected, Trivy finally ran — and immediately failed the pipeline. It found HIGH and CRITICAL severity vulnerabilities in transitive dependencies (wheel and jaraco.context) coming from the python:3.11-slim base image.

Trivy vulnerability scan output Trivy scan output listing HIGH and CRITICAL vulnerabilities that blocked the push

This was the pipeline working exactly as intended. The exit-code: '1' setting means any HIGH or CRITICAL finding blocks the push — that's the security gate in action.

The question was how to fix it. The wrong approach would have been to add patching packages directly to requirements.txt — those are transitive dependencies that the application itself doesn't actually use, and bloating the requirements file with them is bad practice.

The correct approach was a base image upgrade. By moving to a more recent patch version of python:3.11-slim, the image inherits upstream security fixes that the Python Docker team had already applied. The vulnerabilities were resolved without touching the application's dependencies at all.

Successful pipeline run Final successful end-to-end pipeline run with all steps passing

Key takeaway: When Trivy flags base image vulnerabilities, upgrade the base image — don't suppress the finding or patch transitive dependencies directly. Keeping base images current is a core DevSecOps practice, and this is exactly the kind of thing an automated pipeline should surface and enforce.


What This Lab Actually Teaches

Looking back, the manual steps in Phase 1 exist to give you a clear mental model before Phase 2 automates all of it. By the time you write the workflow file, you understand exactly what each step is doing because you've done it yourself.

The pipeline is also a good introduction to what a real supply chain security gate looks like:

  • The image is built but not pushed
  • It's scanned before any push happens
  • A vulnerable image is blocked, not just warned about
  • The push only happens if everything passes

That ordering matters. It's the difference between security as an afterthought and security baked into the delivery process.


Clean Up

docker rm -f $(docker ps -aq) 2>/dev/null
docker rmi my-web-app your-dockerhub-username/my-web-app:v1.0.0-yourname nginx:alpine 2>/dev/null

Enter fullscreen mode Exit fullscreen mode


Resources


If you're working through a similar lab and hit any of the same issues, I hope this saved you some debugging time. Feel free to drop a comment if anything needs more explanation.