Trivy Docker Vulnerability Scanning – Complete Guide

Introduction

In modern DevOps environments, Docker containers are widely used to package and deploy applications. Containers make application deployment faster and more consistent, but they can also contain security vulnerabilities in the operating system packages, application dependencies, libraries, and configuration.

A vulnerable Docker image can introduce security risks into development, testing, and production environments.

This is where Trivy becomes useful.

Trivy is an open-source security scanner that can detect vulnerabilities and other security issues in container images, filesystems, Git repositories, Kubernetes environments, and more.

In a DevSecOps pipeline, Trivy can be integrated into CI/CD so that Docker images are scanned before they are pushed to a container registry or deployed to Kubernetes.

What is Trivy?

Trivy is a comprehensive security scanner commonly used for detecting:

  • Container image vulnerabilities
  • Operating system package vulnerabilities
  • Application dependency vulnerabilities
  • Infrastructure-as-Code misconfigurations
  • Secrets
  • License-related issues
  • Kubernetes-related security issues

The basic workflow can be represented as:

Developer
|
v
Source Code
|
v
Build Application
|
v
Docker Image
|
v
+—————-+
| Trivy |
| Vulnerability |
| Scanner |
+—————-+
|
+——> Vulnerabilities Found
|
+——> No Critical Issues
|
v
Container Registry
|
v
Deployment

Why Do We Need Docker Vulnerability Scanning?

A Docker image is not necessarily secure simply because the application works correctly.

For example, a Docker image may contain:

Application
Java Runtime
Linux Packages
OpenSSL
curl
glibc
Python packages
Node.js packages
Other libraries

Any of these components may contain known security vulnerabilities.

For example:

Docker Image
|
+– OpenSSL
+– curl
+– glibc
+– Java
+– Application dependencies
+– Linux packages

If one of these packages contains a known vulnerability, attackers may potentially exploit it depending on the vulnerability and the application’s exposure.

Therefore:

Docker image scanning should be an important part of a DevSecOps pipeline.

What is a Docker Vulnerability?

A vulnerability is a security weakness that could potentially be exploited.

Docker images can contain vulnerabilities from several sources.

1. Operating System Packages

For example:

Ubuntu
Debian
Alpine
Red Hat
Amazon Linux

These distributions contain many system packages.

Example:

openssl
libssl
curl
bash
glibc

An outdated package may have a known CVE.

2. Application Dependencies

Your application may depend on external libraries.

For example, a Java application may have:

Spring Boot
Spring Security
Jackson
Logback
Hibernate
Maven dependencies

A Node.js application may have:

express
lodash
axios
npm packages

A Python application may have:

Django
Flask
requests
urllib3

If one of these dependencies contains a known vulnerability, the scanner can report it.

What is CVE?

CVE stands for:

Common Vulnerabilities and Exposures

A CVE provides a standardized identifier for a publicly known security vulnerability.

Example:

CVE-2024-XXXX

A vulnerability report may contain information such as:

Vulnerability: CVE-XXXX-XXXX
Package: openssl
Installed Version: X.X.X
Fixed Version: Y.Y.Y
Severity: HIGH

This helps developers and security teams understand what needs to be updated.

What is CVSS?

CVSS stands for:

Common Vulnerability Scoring System

It is used to represent the severity of a vulnerability.

A vulnerability can generally be categorized as:

SeverityMeaning
UNKNOWNSeverity information unavailable
LOWLower security impact
MEDIUMModerate security impact
HIGHSignificant security impact
CRITICALVery serious security impact

The exact risk for an organization depends on factors such as exposure, exploitability, affected component, and how the component is used.

How Does Trivy Work?

Trivy analyzes the target and compares detected components against vulnerability databases.

For a Docker image:

Docker Image
|
v
Trivy Scanner
|
+—- OS packages
|
+—- Application dependencies
|
+—- Vulnerability information
|
v
Scan Result

The output can identify:

Package
Installed Version
Vulnerability ID
Severity
Fixed Version

Installing Trivy

The installation method depends on your operating system.

For Ubuntu/Linux environments, use the installation instructions provided by the official Trivy documentation rather than relying on an outdated third-party installation command.

After installation, verify:

trivy --version

Example:

Version: 0.x.x

The exact version will depend on the version currently installed.

Scan a Docker Image Using Trivy

Suppose you have an image:

docker images

Example:

REPOSITORY          TAG       IMAGE ID
farmer-product      latest    abc123

You can scan it using:

trivy image farmer-product:latest

Trivy will inspect the image and display detected vulnerabilities.

Example Trivy Output

A simplified example may look like:

farmer-product:latest

Library       Vulnerability     Severity    Installed Version    Fixed Version
openssl       CVE-XXXX-XXXX     HIGH        3.x.x                3.x.x
curl          CVE-XXXX-XXXX     MEDIUM      8.x.x                8.x.x
libssl        CVE-XXXX-XXXX     HIGH        3.x.x                3.x.x

The important columns are:

Library

The affected package.

Vulnerability

The vulnerability identifier, commonly a CVE.

Severity

The reported severity.

Installed Version

The version currently present in the image.

Fixed Version

The version that contains the relevant security fix, when one is available.

Scan Only HIGH and CRITICAL Vulnerabilities

In CI/CD pipelines, teams commonly focus on higher-severity findings.

Example:

trivy image --severity HIGH,CRITICAL farmer-product:latest

This helps reduce noise when the pipeline’s security gate is intended to focus on high-impact findings.

Fail the Pipeline When Vulnerabilities Are Found

One useful DevSecOps approach is to make the pipeline fail when vulnerabilities meeting your defined threshold are detected.

Example:

trivy image \
  --severity HIGH,CRITICAL \
  --exit-code 1 \
  farmer-product:latest

Here:

--severity HIGH,CRITICAL

means scan/report the selected severity levels.

And:

--exit-code 1

means Trivy returns a non-zero exit code when matching vulnerabilities are found, allowing CI/CD to stop.

Conceptually:

Build Docker Image
       |
       v
   Run Trivy
       |
       +---- No matching vulnerabilities
       |             |
       |             v
       |        Push Image
       |
       +---- Vulnerability found
                     |
                     v
                Stop Pipeline

Trivy Docker Image Scanning Example

Suppose you build an application:

docker build -t farmer-product:1.0 .

First check the image:

docker images

Then scan:

trivy image farmer-product:1.0

For CI/CD security gating:

trivy image \
  --severity HIGH,CRITICAL \
  --exit-code 1 \
  farmer-product:1.0

If the scan passes:

Trivy Scan
     |
     v
PASS
     |
     v
Push Docker Image

If the configured threshold is exceeded:

Trivy Scan
     |
     v
FAIL
     |
     v
Pipeline Stops

Trivy in a Docker-Based Workflow

A typical developer workflow can be:

git clone <repository>
cd project

Build the application:

mvn clean package

Build Docker image:

docker build -t farmer-product:latest .

Scan image:

trivy image farmer-product:latest

If the result satisfies your security policy:

docker push farmer-product:latest

Trivy in Jenkins CI/CD

Trivy becomes especially useful when integrated with Jenkins.

A typical pipeline is:

GitHub
   |
   v
Jenkins
   |
   v
Checkout
   |
   v
Maven Build
   |
   v
Docker Build
   |
   v
Trivy Scan
   |
   +---- FAIL
   |
   +---- PASS
          |
          v
      Docker Push
          |
          v
       Deploy

This is an example Jenkinsfile structure:

pipeline {

    agent any

    stages {

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

        stage('Maven Build') {
            steps {
                sh 'mvn clean package'
            }
        }

        stage('Docker Build') {
            steps {
                sh 'docker build -t farmer-product:${BUILD_NUMBER} .'
            }
        }

        stage('Trivy Scan') {
            steps {
                sh '''
                trivy image \
                --severity HIGH,CRITICAL \
                --exit-code 1 \
                farmer-product:${BUILD_NUMBER}
                '''
            }
        }

        stage('Docker Push') {
            steps {
                sh 'docker push farmer-product:${BUILD_NUMBER}'
            }
        }
    }
}

Important

In a real production pipeline, Docker registry authentication, credential management, image tagging, and Trivy installation should be configured securely rather than hard-coded.


Why Scan Before Docker Push?

Consider this workflow:

Developer
   |
   v
Build Image
   |
   v
Push Vulnerable Image
   |
   v
Production Registry
   |
   v
Kubernetes

The vulnerable image has already entered the organization’s registry.

A better approach is:

Developer
   |
   v
Build Image
   |
   v
Trivy Scan
   |
   +---- FAIL ---> Fix Vulnerability
   |
   +---- PASS
          |
          v
       Push Image
          |
          v
       Deploy

This is called shift-left security.


What is Shift-Left Security?

Traditionally, security testing might happen near the end of the software delivery process.

Modern DevSecOps moves security checks earlier.

Traditional:

Code → Build → Test → Deploy → Security


DevSecOps:

Code → Security → Build → Scan → Deploy

The goal is to identify security issues as early as practical.

Benefits include:

  • Earlier detection
  • Faster remediation
  • Reduced deployment risk
  • Better developer awareness
  • Automated security checks

Scan a Docker Image from Docker Hub

You can also scan publicly available images.

For example:

trivy image nginx:latest

or:

trivy image ubuntu:latest

This can help developers understand the security posture of base images before using them.


Scan a Specific Image Version

Instead of:

docker build -t myapp:latest .

you can use versioned tags:

docker build -t myapp:1.0.0 .

Then:

trivy image myapp:1.0.0

Versioned images make it easier to identify exactly which image was scanned and deployed.


Scan Image Before and After Updating Packages

Suppose your image contains an outdated package.

First:

trivy image myapp:1.0

You identify a vulnerable package.

Then update the base image or package versions.

Rebuild:

docker build -t myapp:1.1 .

Scan again:

trivy image myapp:1.1

Then compare the results.

This creates a simple remediation cycle:

Scan
  |
  v
Find Vulnerability
  |
  v
Update Package
  |
  v
Rebuild Image
  |
  v
Scan Again
  |
  v
Pass

How to Reduce Docker Vulnerabilities

1. Use Updated Base Images

Instead of using an outdated base image:

FROM ubuntu:old-version

use a currently supported base image appropriate for your application.


2. Use Minimal Base Images

Smaller images generally contain fewer packages.

Examples include:

Alpine
Debian slim
Distroless

However, “smaller” does not automatically mean “secure.” The image still needs to be maintained and scanned.


3. Keep Dependencies Updated

For Maven:

mvn dependency:tree

Review and update vulnerable dependencies.

For Node.js:

npm audit

For Python:

pip-audit

Trivy can complement these application-specific checks.


4. Remove Unnecessary Packages

Avoid installing packages that the application does not require.

For example:

RUN apt-get update && \
    apt-get install -y curl vim wget

If these tools are not required at runtime, consider leaving them out of the production image.


Multi-Stage Docker Builds

Multi-stage builds can help produce smaller runtime images.

Example:

FROM maven:3.9-eclipse-temurin-17 AS build

WORKDIR /app

COPY pom.xml .
COPY src ./src

RUN mvn clean package -DskipTests

FROM eclipse-temurin:17-jre

WORKDIR /app

COPY --from=build /app/target/*.jar app.jar

CMD ["java", "-jar", "app.jar"]

The first stage contains build tools.

The final stage contains only what is needed to run the application.

After building:

docker build -t farmer-product:latest .

Scan the final image:

trivy image farmer-product:latest

Trivy Configuration Scanning

Trivy is not limited to Docker image vulnerabilities.

It can also scan Infrastructure as Code.

For example:

trivy config .

This can help identify configuration issues in files such as:

Dockerfile
Terraform
Kubernetes YAML
Helm
CloudFormation

Scan a Filesystem

Trivy can also scan a local filesystem:

trivy fs .

This can help identify vulnerabilities in application dependencies and other supported artifacts.


Scan a Git Repository

Trivy can also be used against source repositories:

trivy repo https://github.com/example/project

This can help identify supported vulnerabilities and secrets depending on the scan configuration and target.


Trivy and Kubernetes

Trivy can also be used in Kubernetes security workflows.

A simplified DevSecOps architecture is:

Developer
    |
    v
GitHub
    |
    v
Jenkins
    |
    +--> SAST
    |
    +--> Trivy
    |
    +--> Docker Build
    |
    v
Container Registry
    |
    v
Kubernetes

For Kubernetes workloads, image scanning can happen before deployment, while Kubernetes configuration and cluster security can be checked separately.


Trivy vs SonarQube

Trivy and SonarQube are both useful DevSecOps tools, but they solve different problems.

FeatureTrivySonarQube
Container image scanning✅Not its primary purpose
OS package vulnerabilities✅❌
Dependency vulnerabilities✅Some related analysis, depending on setup
Docker security✅Limited/not primary
SASTNot its primary purpose✅
Code qualityNot its primary purpose✅
IaC scanning✅Available through supported analysis/configuration
Secret detection✅Available depending on analyzer/setup
CI/CD integration✅✅

Therefore, organizations may use both.

Example:

                    DevSecOps Pipeline
                           |
             +-------------+-------------+
             |                           |
         SonarQube                     Trivy
             |                           |
        Source Code                Container Image
             |                           |
       Code Quality               Vulnerabilities
             |                           |
             +-------------+-------------+
                           |
                           v
                       Deployment

Trivy vs Docker Scout

Another commonly encountered tool is Docker Scout.

Both can help with container security analysis, but they are different products with different workflows and integrations.

A team should evaluate:

  • Existing CI/CD platform
  • Container registry
  • Security policies
  • Reporting requirements
  • Licensing
  • Developer workflow
  • Kubernetes environment

rather than assuming one tool covers every security requirement.


Best Practices for Trivy

1. Scan Every Production Image

Make image scanning part of the CI/CD process.

2. Use Severity Thresholds

For example:

--severity HIGH,CRITICAL

Define the policy based on organizational risk requirements.

3. Fail CI/CD When Appropriate

Example:

--exit-code 1

But make sure the team has an agreed remediation policy so that scanning does not become an ignored source of noise.

4. Keep Base Images Updated

Regularly update:

Ubuntu
Debian
Alpine
Java
Node
Python
Nginx

and other base images.

5. Rescan Regularly

A previously clean image can become affected by newly disclosed vulnerabilities.

Therefore:

Build
 ↓
Scan
 ↓
Deploy
 ↓
New CVE discovered
 ↓
Rescan
 ↓
Remediate

Recommended DevSecOps Pipeline

A complete pipeline can look like this:

                  Developer
                      |
                      v
                   GitHub
                      |
                      v
                   Jenkins
                      |
              +-------+-------+
              |               |
              v               v
          SonarQube        Maven Test
              |               |
              +-------+-------+
                      |
                      v
                Docker Build
                      |
                      v
                 Trivy Scan
                      |
              +-------+-------+
              |               |
             FAIL            PASS
              |               |
              v               v
          Fix Issues      Docker Push
                              |
                              v
                         Container Registry
                              |
                              v
                           Helm
                              |
                              v
                         Kubernetes

This demonstrates the idea of integrating security into the software delivery lifecycle rather than treating security as a separate activity at the end.


Example Real-World DevOps Project

Suppose you have a Spring Boot application:

Farmer Product Application

The development flow could be:

Step 1 – Build Java Application

mvn clean package

Step 2 – Build Docker Image

docker build -t farmer-product:1.0 .

Step 3 – Scan Image

trivy image farmer-product:1.0

Step 4 – Scan High/Critical Vulnerabilities

trivy image \
  --severity HIGH,CRITICAL \
  farmer-product:1.0

Step 5 – Apply Security Gate

trivy image \
  --severity HIGH,CRITICAL \
  --exit-code 1 \
  farmer-product:1.0

Step 6 – Push Only After the Gate

docker push <registry>/farmer-product:1.0

Step 7 – Deploy

helm upgrade --install farmer-product ./helm-chart

This creates a practical DevSecOps workflow:

Code
 ↓
Build
 ↓
Docker Image
 ↓
Trivy
 ↓
Security Gate
 ↓
Registry
 ↓
Helm
 ↓
Kubernetes

Common Trivy Commands

PurposeCommand
Check versiontrivy --version
Scan Docker imagetrivy image IMAGE
Scan HIGH/CRITICALtrivy image --severity HIGH,CRITICAL IMAGE
Fail on findingstrivy image --exit-code 1 IMAGE
Scan filesystemtrivy fs .
Scan configurationtrivy config .
Scan repositorytrivy repo REPOSITORY

Always check the current Trivy documentation for command syntax because features and flags can change between releases.


Advantages of Trivy

Open Source

Trivy is widely used as an open-source security scanner.

Easy to Use

A basic image scan can be performed with:

trivy image myimage:latest

CI/CD Friendly

It can be integrated with:

Jenkins
GitHub Actions
GitLab CI/CD
Azure DevOps
Other CI systems

Multiple Scan Targets

Trivy can work with:

Container Images
Filesystems
Git Repositories
IaC
Kubernetes

Developer Friendly

The command-line workflow makes it practical for developers and DevOps engineers to run security checks during development.


Limitations and Important Considerations

Trivy is a security scanning tool, but a scanner cannot guarantee that an application is completely secure.

A vulnerability report also does not automatically mean that the application is exploitable in your particular environment.

Security teams should consider:

  • Whether the vulnerable component is actually used
  • Network exposure
  • Application configuration
  • Authentication and authorization
  • Runtime environment
  • Available exploit
  • Vendor fix
  • Compensating controls
  • Business impact

Therefore, vulnerability scanning should be combined with other security practices.


Trivy in DevSecOps

Trivy fits into the broader DevSecOps lifecycle:

PLAN
  ↓
CODE
  ↓
BUILD
  ↓
TEST
  ↓
SECURITY SCAN
  ↓
PACKAGE
  ↓
RELEASE
  ↓
DEPLOY
  ↓
MONITOR

Security should be continuously considered throughout the lifecycle.


Conclusion

Trivy is an important security scanning tool for modern containerized DevOps environments.

It can help teams identify vulnerabilities in Docker images, dependencies, filesystems, Infrastructure as Code, and other supported targets.

A practical workflow is:

Build Docker Image
       ↓
Run Trivy
       ↓
Identify Vulnerabilities
       ↓
Update Packages/Base Image
       ↓
Rebuild Image
       ↓
Scan Again
       ↓
Security Gate
       ↓
Push Image
       ↓
Deploy

By integrating Trivy into Jenkins or another CI/CD platform, organizations can introduce automated security checks into their delivery pipeline and detect many known vulnerabilities before an image reaches production.

Key Takeaways

  1. Trivy is a security scanner used in DevSecOps.
  2. It can scan Docker/container images for known vulnerabilities.
  3. It can identify vulnerabilities in OS packages and application dependencies.
  4. CVE identifies publicly known vulnerabilities.
  5. CVSS provides a standardized severity scoring framework.
  6. Trivy can be integrated with Jenkins and CI/CD pipelines.
  7. --exit-code 1 can be used as part of a CI/CD security gate.
  8. Updating base images and dependencies helps remediate vulnerabilities.
  9. Trivy can also scan filesystems, repositories, IaC, and Kubernetes-related targets.
  10. Trivy should be used as one component of a broader security strategy, not as a guarantee that an application is completely secure.
Mahesh Wabale

Leave a Comment