Developer Tools & Environments ADVANCED Linux / macOS โฑ๏ธ 7 min read ๐Ÿ“… Updated: 15 Sep 2026

Implementing Container Image Vulnerability Scanning in Git Pre-Commit Hooks

This advanced guide details how to integrate automated container image vulnerability scanning (using tools like Trivy or Clair) directly into a Git pre-commit hook, ensuring that no vulnerable images are committed to the repository.

Gurveer Singh
Gurveer Singh โœ“ Verified Specialist
Founder & Chief Architect ยท hSECURITIES Labs
โšก FAST-TRACK PROTOCOL

Direct Diagnostic & Remediation Summary

  • Install Scanner: Ensure your chosen scanner (e.g., Trivy) is installed locally: docker pull trivy/trivy.
  • Create Hook Script: Develop a shell script that checks for Dockerfiles and runs the scan before allowing the commit: #!/bin/sh if docker build --tag vulnerable_image . && trivy image --exit-code 1 vulnerable_image; then echo "Scan Passed."; else echo "Vulnerability Detected!"; exit 1; fi.
  • Activate Hook: Place the script in the .git/hooks/pre-commit directory and make it executable: chmod +x .git/hooks/pre-commit.
๐Ÿ› ๏ธ Tools & Prerequisites: A Linux or macOS development environment, Docker Engine installed and running, Git version 2.20+, A container vulnerability scanner (e.g., Trivy, Clair) configured and accessible via CLI.
๐Ÿ” Root Cause & Diagnostic Overview: The primary risk is the accidental commitment of source code that defines or includes a vulnerable base image layer within a Dockerfile. Traditional CI/CD scanning only runs on push/merge, allowing bad artifacts to enter the repository history. By implementing a pre-commit hook, we intercept the commit process locally, forcing an immediate, lightweight scan against any container definition before it ever hits the remote server, thereby enforcing security policy at the developer's workstation level.
STEP 1

Prerequisite Setup: Scanner Installation & Testing

Before touching Git hooks, ensure your chosen vulnerability scanner works reliably on a test image. We recommend Trivy for its simplicity and effectiveness.

  • Install Docker Image: Ensure the base scan tool is available locally via Docker or direct binary installation.docker pull aquasec/trivy
  • Create Test Dockerfile: In a dedicated test directory, create a minimal Dockerfile that uses an intentionally vulnerable base image for testing purposes (e.g., one known to have old libraries).
  • Execute Baseline Scan: Build the image and run the scanner against it manually to confirm exit code handling.
    docker build -t test_vuln:latest .
    aquasec/trivy image --exit-code 1 test_vuln:latest

Note: The --exit-code 1 flag is critical; it forces the scanner to exit with a non-zero status if vulnerabilities are found, which we will leverage in the hook.

Pro Tip: Always test your scanning tool against both known clean and known vulnerable images before integrating hooks into team workflows.
STEP 2

Creating the Pre-Commit Hook Script

The hook must check for Dockerfiles, build an image contextually, and then execute the scan. This script needs to be robust enough to fail the commit if the exit code is non-zero.

  • Navigate to Hooks Directory: Change into your local repository's hooks directory: cd .git/hooks.
  • Create Script File: Create a new file named pre-commit (no extension): touch pre-commit
  • Populate Script Content: Open pre-commit in your preferred editor and paste the following logic. This example assumes you want to scan any image built from Dockerfiles found in staged changes.
    #!/bin/sh
    
    # Check if a Dockerfile exists among staged files (a simplification for demonstration)
    if ! git diff --cached --name-only | grep -q "Dockerfile"; then
        exit 0 # No Dockerfile staged, skip scanning.
    fi
    
    echo "[SECURITY SCAN] Initiating container vulnerability scan..."
    
    # In a real scenario, you would pass the specific image tag/context here.
    # For this example, we assume the build context is the root of the repo.
    IMAGE_TAG="temp_scan_image"
    
    # 1. Build the image (This step must succeed for scanning to occur)
    docker build -t ${IMAGE_TAG} . || { echo "Error: Docker build failed. Aborting commit."; exit 1; }
    
    # 2. Run the vulnerability scan, expecting an exit code of 0 on success
    if aquasec/trivy image --exit-code 1 ${IMAGE_TAG}; then
        echo "[SECURITY SCAN] Success: Image passed all configured security checks."
    else
        echo "[SECURITY SCAN] FAILURE: Vulnerabilities detected in the container image. Commit aborted for remediation."
        docker rmi ${IMAGE_TAG} # Clean up the temporary image
        exit 1 # Exit with non-zero code to fail the commit
    fi
    
    # Cleanup temp image regardless of success/failure if needed, though exit handles failure cleanup above
    docker rmi ${IMAGE_TAG}
    exit 0
  • Set Permissions: Make the script executable: chmod +x .git/hooks/pre-commit
STEP 3

Testing and Integration Workflow

Test the hook in isolation to ensure it correctly fails commits when vulnerabilities are present, and passes when clean.

  • Stage Files: Stage a Dockerfile and any related source code changes: git add Dockerfile .
  • Simulate Vulnerability (Failure Test): Modify the test image to include a known CVE, then attempt to commit:
    git commit -m "Testing vulnerability hook failure"
    Expected Result: The terminal must display the custom failure message and refuse the commit.
  • Simulate Clean State (Success Test): Revert changes, ensure all base images are clean, and attempt to commit again:
    git commit -m "Testing vulnerability hook success"
    Expected Result: The terminal must display the custom success message and allow the commit.
Warning: If you are working in a team, remember that Git hooks are local. Team members must manually install this hook or use pre-commit framework tools (like pre-commit Python library) for enforcement across the board.
TROUBLESHOOTING

Common Pitfalls & Advanced Diagnostics

If the hook fails unexpectedly, check these common pitfalls:

  • Hook Overwrite: If you run rm pre-commit and then re-add it later, ensure you are still running chmod +x .git/hooks/pre-commit.
  • Docker Context Issues: The hook assumes the build context is the repository root (.). If your Dockerfile requires a specific subdirectory context (e.g., ./backend), you must change both the build -t ... . and potentially adjust file path checks in the script.
  • Permission Inheritance: Sometimes, running Git hooks within IDEs or CI runners can strip execution permissions. Always verify ownership and permissions using ls -l .git/hooks/pre-commit.
  • Resource Exhaustion: Scanning large images can be CPU/Memory intensive. If the hook times out, consider adding a timeout mechanism (e.g., using timeout 60s ...) to prevent indefinite hanging.
FINAL STEP

Verification, Results & Long-Term Stability Validation

To validate long-term stability, do not rely solely on the local hook. The ultimate source of truth must remain in CI/CD.

  • CI Integration: Implement an identical scan step (using the same scanner and exit code logic) in your primary Continuous Integration pipeline (e.g., GitHub Actions, GitLab CI). This prevents developers from bypassing local hooks by committing directly to a runner environment that doesn't respect local setups.
  • Dependency Management: If using Python/Pip environments for scanning tools, manage dependencies via requirements.txt and use the official pre-commit framework wrapper instead of raw shell scripts. This centralizes hook management.
    pip install pre-commit
    pre-commit install
  • Monitoring: Monitor commit failure rates initially. A sudden spike in failures indicates a change in the base image or dependency that requires updating the allowed vulnerability threshold.

The goal is for the local hook to act as an immediate guardrail, while the CI/CD pipeline acts as the non-negotiable gatekeeper.

Resolution Complete: You have successfully implemented a layered security mechanism. The local Git pre-commit hook now provides instant feedback to developers, blocking commits containing vulnerable container definitions. Remember that for enterprise stability, this process MUST be mirrored and enforced by the central CI/CD platform.

Frequently Asked Questions

Q: Does this hook run if I use a different local machine? A: No. Git hooks are local to the repository clone. You must instruct all team members to install the hook or, preferably, adopt the pre-commit framework for centralized enforcement.

Q: How do I scan multiple Dockerfiles in one repo? A: The pre-commit script needs logic (using find . -name "Dockerfile"*) to identify all relevant build contexts and iterate through them, running the build/scan cycle for each context found.

Q: What if the vulnerability scanner itself is unavailable? A: The hook must be wrapped in a try/catch or shell conditional block that handles non-zero exit codes from the scanner tool gracefully, but it should fail the commit if the tool execution fails (e.g., Docker daemon down).

COMMAND LINE / TERMINAL
docker pull aquasec/trivy
chmod +x .git/hooks/pre-commit
git add Dockerfile .
docker build -t temp_scan_image .
git commit -m "Test"
pip install pre-commit

Frequently Asked Questions

Does this hook run if I use a different local machine?A: No. Git hooks are local to the repository clone. You must instruct all team members to install the hook or, preferably, adopt the <code>pre-commit</code> framework for centralized enforcement.

Refer to the verified triage steps detailed above.

How do I scan multiple Dockerfiles in one repo?A: The pre-commit script needs logic (using <code>find . -name "Dockerfile"</code>) to identify all relevant build contexts and iterate through them, running the build/scan cycle for each context found.

Refer to the verified triage steps detailed above.

What if the vulnerability scanner itself is unavailable?A: The hook must be wrapped in a try/catch or shell conditional block that handles non-zero exit codes from the scanner tool gracefully, but it should fail the commit if the tool execution fails (e.g., Docker daemon down).

Refer to the verified triage steps detailed above.

Engineering Assistance

Need help implementing this solution?

Our cybersecurity and infrastructure engineers can audit, harden, or configure your systems directly.

Request Technical Assistance โ†’
Gurveer Singh
Gurveer Singh โœ“ Verified Author
Founder & CEO at hSECURITIES | Cybersecurity Educator | Security Researcher | Ethical Hacking Enthusiast | Technology Mentor
Meet the Founder โ†’

Gurveer Singh Saggu is the Founder and CEO of hSECURITIES, a cybersecurity and technology education platform focused on practical learning, digital security awareness, hardware diagnostics, Linux administration, and real-world cybersecurity training.

With a strong passion for technology, ethical hacking, and security education, he has spent years helping students, professionals, and organizations understand modern cyber threats and develop practical technical skills. Through hSECURITIES, he creates hands-on learning resources, technical guides, security awareness content, and community-driven initiatives that make cybersecurity more accessible.

His mission is to bridge the gap between theoretical knowledge and practical implementation by providing step-by-step learning experiences, technical troubleshooting resources, and security-focused educational platforms.

Community Discussion & Confirmations (0)

Technical questions, hardware findings, and verified fix reports.

No reader questions posted yet. Have you tried this solution or experienced an edge case? Post below.

Ask a Question or Share Solution