Using Safety Firewall in Docker
This guide explains how to integrate Safety Firewall into your Docker builds to protect package installations during image creation.
Overview
Safety Firewall wraps your package manager (e.g. pip and uv) to automatically scan packages for vulnerabilities and block malicious packages before they're installed. In Docker, you install Safety first, then use it to protect your package installations.
Prerequisites
A Safety API key (available from your Safety dashboard)
Docker with BuildKit support (recommended for secure secret handling)
Basic Setup
The simplest approach is to install Safety and then use it to wrap your pip install command:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install safety
RUN safety --key "YOUR_API_KEY" pip install --no-cache-dir -r requirements.txtRecommended: Using Docker BuildKit Secrets
Docker BuildKit secrets allow you to pass sensitive values to your build without embedding them in the image or Dockerfile.
Option 1: Environment Variable
Pass your API key as an environment variable at build time.
Dockerfile:
Build command:
Option 2: Using a .env File
If you prefer to store your API key in a file (useful for local development or when using .env files), you can source it directly.
Dockerfile:
Create a secrets file (e.g., safety-api-key.env):
Build command:
CI/CD Integration
In CI/CD pipelines, store your Safety API key as a secret in your CI platform (GitHub Actions, GitLab CI, etc.) and pass it to the Docker build using the environment variable approach shown above.
For example, in GitHub Actions:
Troubleshooting
safety: command not found
Ensure pip install safety runs before the Safety Firewall command
Authentication errors
Verify your API key is valid and properly passed to the build
BuildKit not enabled
Set DOCKER_BUILDKIT=1 or configure Docker to use BuildKit by default
Last updated
Was this helpful?

