Feedback

Chat Icon

DevSecOps in Practice

A Hands-On Guide to Operationalizing DevSecOps at Scale

Dockerfile: Security Linting
62%

Common Security Pitfalls in Dockerfiles

There are tools to help you secure your Dockerfiles, but before diving into them, it is important to understand some common security pitfalls that you should avoid. Below are some examples, along with best practices to mitigate them. These are just illustrative simplified examples, neither designed to be exhaustive nor to replace a comprehensive security strategy.

Using an Insecure Base Image

Using outdated or unverified base images can introduce vulnerabilities to your container. Many developers use latest tags or unofficial images without checking their security status.

Example of an insecure Dockerfile

# No version pinning, could introduce breaking changes or vulnerabilities
FROM ubuntu:latest  

Secure alternative

# Use a specific, trusted version to ensure stability and security
FROM ubuntu:22.04  
  • Prefer minimal and distroless images (e.g., gcr.io/distroless/base or alpine:3.17).
  • Regularly scan base images for vulnerabilities using tools like Trivy or Docker Scout.

Running as Root

By default, Docker containers run as the root user, which increases the attack surface if a container is compromised.

Example of an insecure Dockerfile

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "app.js"]  # Runs as root by default

Secure alternative

FROM node:18
WORKDIR /app
RUN useradd -m nonrootuser
USER nonrootuser
COPY . .
RUN npm install
CMD ["node", "app.js"]
  • Always create and switch to a non-root user.
  • Limit privileges using USER directives.

Hardcoding Secrets in the Dockerfile

Hardcoding sensitive information in a Dockerfile exposes secrets to anyone with access to the image.

Example of an insecure Dockerfile

# Hardcoded sensitive data
ENV DB_PASSWORD="SuperSecret123"  

Secure alternative

ARG DB_PASSWORD
ENV DB_PASSWORD=${DB_PASSWORD}
  • Use Docker secrets, environment variables, or vaults instead.
  • Avoid storing credentials in version control.

Failing to Reduce the Attack Surface

Including unnecessary tools and dependencies in an image increases its attack surface, image size, and makes it a target for exploits.

Example of an insecure Dockerfile

FROM ubuntu:22.04
RUN apt-get update && apt-get install -y \
  curl \
  vim \
  netcat \
  htop \
  iputils-ping \
  wget

Secure alternative

FROM alpine:3.17
RUN apk add --no-cache curl \
  &&

DevSecOps in Practice

A Hands-On Guide to Operationalizing DevSecOps at Scale

Enroll now to unlock current content and receive all future updates for free. Your purchase supports the author and fuels the creation of more exciting content. Act fast, as the price will rise as the course nears completion!