DockerIntermediate

Docker Security Scanning: A Complete Guide to Container Security

DevHub Team
9 min read

TL;DR

Master Docker security scanning with this comprehensive guide covering vulnerability scanning, compliance checks, and best practices for securing containerized applications

Docker Security Scanning: A Complete Guide to Container Security

Executive Summary

Security scanning answers one question about a container image: what is inside it that is already known to be vulnerable, misconfigured, or secret? This guide covers the three kinds of scanning (vulnerability scanning of OS packages and application libraries, misconfiguration scanning of Dockerfiles and manifests, and secret scanning), the major tools and how they differ, and how to wire scanning into CI/CD so findings actually gate releases instead of generating unread reports. It also covers the operational half: severity policy, handling unfixed and disputed findings, rescanning images in the registry as new CVEs appear, and the runtime monitoring and compliance checks that pick up where static scanning stops.

Why This Matters

An image is a snapshot. The day it is built, a clean scan means its components have no known vulnerabilities; a month later, new CVEs have been published against those exact component versions, and the unchanged image has become vulnerable sitting still. Teams that scan only at build time, or not at all, routinely run production containers with remotely exploitable library flaws they could have found with a free tool in under a minute. Scanning is also the control auditors ask about first, because it is objective and evidence-producing. The cost of skipping it is measured in incident response, emergency rebuilds, and compliance findings.

Core Concepts

What a Scanner Actually Examines

A vulnerability scanner inventories the image: OS packages from the base image's package manager, and application libraries it can identify for languages such as Node.js, Python, Java, Go, and Ruby. It then matches versions against vulnerability databases built from CVE and vendor advisory feeds. Two consequences follow. Findings are only as good as the inventory, so stripped or unusual images can hide components. And a finding means "this version is listed as affected", not "your deployment is exploitable"; triage still matters.

Modern scanners widen the lens beyond CVEs. Trivy, used throughout this guide, also scans Dockerfiles and Kubernetes manifests for misconfigurations and searches files for leaked secrets:

# trivy.yaml
scan:
  # Vulnerability scanning
  vulnerability:
    type:
      - os
      - library
    ignore-unfixed: true
    severity:
      - CRITICAL
      - HIGH

  # Misconfiguration scanning
  config:
    include:
      - kubernetes
      - dockerfile
    severity:
      - CRITICAL
      - HIGH
      - MEDIUM

  # Secret scanning
  secret:
    enable: true

The ignore-unfixed setting deserves attention: it suppresses vulnerabilities with no available patch. That keeps gates actionable, but it should be a visible policy decision, because an unfixed critical in an exposed component is still a risk to record and revisit.

Choosing a Tool

The widely used options overlap heavily, and most teams should pick one primary scanner and run it well rather than run three badly. Trivy is open source, fast, covers OS packages, libraries, misconfigurations, and secrets, and is the common default for CI. Snyk emphasises developer workflow and dependency remediation advice, and fits teams already using it for application security. Clair is designed as a service for scanning registries at scale, suiting platform teams that want an API-driven, always-on inventory. Docker Scout integrates with Docker Hub and Docker Desktop and ties findings to image provenance. All of them consume the same public CVE ecosystem; differences are in coverage of specific ecosystems, reporting, policy features, and where scanning runs.

Scanning in CI: Make It a Gate

A scan that cannot fail a build is documentation. The working pattern is: build the image, scan it, publish results in a machine-readable format such as SARIF to the code-scanning dashboard, and exit non-zero on findings above your severity threshold.

# .github/workflows/security-scan.yml
name: Security Scan

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

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'docker.io/my-organization/my-app:${{ github.sha }}'
          format: 'table'
          exit-code: '1'
          ignore-unfixed: true
          vuln-type: 'os,library'
          severity: 'CRITICAL,HIGH'

      - name: Scan with Trivy
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: myapp:${{ github.sha }}
          format: 'sarif'
          output: 'trivy-results.sarif'

      - name: Upload scan results
        uses: github/codeql-action/upload-sarif@v1
        with:
          sarif_file: 'trivy-results.sarif'

The same gate translates directly to other CI systems; in Jenkins the scanner simply runs as a stage whose failure stops the pipeline:

stage('Trivy') {
    steps {
        sh '''
            trivy image \
                --exit-code 1 \
                --severity HIGH,CRITICAL \
                --no-progress \
                ${DOCKER_IMAGE}
        '''
    }
}

Scan the image you will actually deploy, identified by digest or commit tag, not a floating tag that may resolve to something else by deploy time.

Policy: Severity, Exceptions, and Base Images

Write the policy down before the first argument about a blocked release. A workable default: fail on critical and high findings that have fixes; warn on the rest; allow time-boxed exceptions recorded in a file in the repository (Trivy supports .trivyignore) with an owner and an expiry. Separately, maintain an approved list of base images. Most findings originate in the base, so rebuilding onto a patched or smaller base fixes more findings per hour than chasing application dependencies. Finally, schedule rebuilds: a weekly rebuild of unchanged services onto fresh base images is what keeps the registry from quietly accumulating known-vulnerable images.

Reduce Findings at the Source

Scanning is detection; image design is prevention. Pin exact dependency versions so builds are reproducible and findings are attributable, as in this manifest fragment:

{
  "name": "secure-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "4.18.2"
  },
  "scripts": {
    "security-audit": "npm audit",
    "update-deps": "npm update"
  }
}

Use minimal, specifically tagged bases and non-root users so that even unscanned misconfigurations are rarer:

# Use specific version tags
FROM alpine:3.17.0

# Add security packages
RUN apk add --no-cache \
    ca-certificates \
    tzdata \
    && update-ca-certificates

# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

Multi-stage builds amplify this by keeping build tools and their vulnerabilities out of the deployed image entirely.

Beyond the Image: Runtime and Compliance

Static scanning cannot see a container behaving badly. Runtime tools such as Falco watch syscalls and raise alerts on behaviour like a shell spawning inside a production container or a package manager executing at runtime:

# falco-rules.yaml
- rule: Detect Shell in Container
  desc: Alert on shell execution in container
  condition: >
    container.id != host and
    proc.name = bash
  output: Shell executed in container (user=%user.name container=%container.name)
  priority: WARNING

- rule: Package Management Execution
  desc: Package management execution in container
  condition: >
    container.id != host and
    (proc.name = apt or proc.name = apk or proc.name = yum)
  output: Package management command executed in container (user=%user.name command=%proc.cmdline)
  priority: WARNING

For the host and daemon configuration itself, the CIS Docker Benchmark is the standard checklist, and Docker Bench for Security automates much of it:

#!/bin/bash

# Run Docker Bench Security
docker run --rm -v /var:/var \
    -v /usr/bin/docker:/usr/bin/docker \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /etc:/etc --label docker_bench_security \
    docker/docker-bench-security

Treat benchmark output like scan output: fix what applies, record exceptions with reasons, and rerun after upgrades.

Decision Framework

SituationRecommendation
Starting from zeroTrivy in CI, gate on fixable critical and high findings
Findings overwhelming the teamGate on critical only for two weeks while bases are refreshed, then restore the high gate
Critical CVE with no fix availableRecord a time-boxed exception; check whether the component is reachable in your configuration
Images already in productionEnable registry rescanning and schedule base-image rebuilds
Regulated environmentAdd CIS benchmark checks, signed images, and retained scan reports as audit evidence
Scanner disagreementsTrust the inventory: check whether the component is actually in the image before disputing a finding

Implementation Checklist

  • [ ] Every image is scanned in CI before it can be pushed or deployed
  • [ ] The pipeline fails on fixable critical and high severity findings
  • [ ] Scan results are uploaded in SARIF or an equivalent format where reviewers can see them
  • [ ] Exceptions live in a versioned ignore file with owner and expiry date
  • [ ] Base images come from an approved list and are rebuilt on a schedule
  • [ ] Registry images are rescanned as new CVE data is published
  • [ ] Secret scanning is enabled so credentials cannot be committed into layers unnoticed
  • [ ] Runtime detection and a CIS benchmark review cover what static scanning cannot
  • Trade-offs

    Scanning adds minutes to pipelines and a triage burden to teams. Scanners disagree at the margins because they build inventories differently, and every scanner produces some findings that are not exploitable in context; treating every result as an emergency trains teams to ignore all of them. Gates can also pressure teams into rushed base-image upgrades. The alternative, however, is discovering your exposure from someone else's scan of your production system. A tuned gate with honest exceptions is the middle path that survives contact with a release schedule.

    When Not to Use

  • A scan gate as a substitute for fixing the base image habit: if every build lights up with findings, the problem is image selection and rebuild cadence, not the scanner.
  • Blocking on every severity: gating on low and informational findings makes the gate unusable and guarantees it will be bypassed; reserve hard failures for what you will actually fix immediately.
  • Scanning as your only container security control: it covers known vulnerabilities in known components. It does not cover application flaws, excessive privileges, exposed ports, or runtime behaviour, which need the controls described in the companion security guide.
  • Conclusion

    Scanning works when it is early, enforced, and maintained: scan every image in CI, fail on what you would genuinely fix, record exceptions with expiry dates, and keep rebuilding onto patched bases so yesterday's clean image does not become tomorrow's incident. The tools are mature and mostly free. The discipline is the product.

    References

  • Docker Security Documentation
  • Trivy Documentation
  • Snyk Container Security
  • CIS Docker Benchmark
  • Container Security Best Practices
  • NIST Container Security Guide
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.