# DOCKER-BP-014: Remove apt Package Lists

> **Severity:** LOW | **CWE:** CWE-710

- **Language:** Docker
- **Category:** Best Practice
- **URL:** https://codepathfinder.dev/registry/docker/best-practice/DOCKER-BP-014
- **Detection:** `pathfinder scan --ruleset docker/DOCKER-BP-014 --project .`

## Description

Detects 'apt-get install' without removing /var/lib/apt/lists/*.
Package lists contain repository metadata that is not needed at runtime and wastes space.
This is specific to Debian/Ubuntu based images.

## Vulnerable Code

```python
FROM ubuntu:22.04

# Bad: Leaves package lists, increases image size
RUN apt-get update && apt-get install -y nginx
```

## Secure Code

```python
FROM ubuntu:22.04

# Good: Removes package lists in same layer
RUN apt-get update && apt-get install -y nginx \\
    && rm -rf /var/lib/apt/lists/*
```

## Detection Rule (Python SDK)

```python
from rules.container_decorators import dockerfile_rule
from rules.container_matchers import instruction
from rules.container_combinators import all_of


@dockerfile_rule(
    id="DOCKER-BP-014",
    name="Remove apt Package Lists",
    severity="LOW",
    cwe="CWE-710",
    category="best-practice",
    tags="docker,dockerfile,apt-get,package-manager,ubuntu,debian,cache,cleanup,image-size,optimization,best-practice",
    message="apt-get install without removing /var/lib/apt/lists/*. This wastes image space."
)
def remove_package_lists():
    return all_of(
        instruction(type="RUN", contains="apt-get install"),
        instruction(type="RUN", not_contains="/var/lib/apt/lists/")
    )
```

## How to Fix

- Use apt-get instead of apt in Dockerfiles for stable CLI behavior
- Always run apt-get update && apt-get install in the same RUN instruction
- Add --no-install-recommends to minimize installed packages
- Clean up with rm -rf /var/lib/apt/lists/* in the same layer

## FAQ

**Q: Why use apt-get instead of apt?**

apt is designed for interactive use and its output format may change between versions. apt-get provides a stable CLI interface suitable for scripting and Dockerfiles.

**Q: Why combine update and install in one RUN?**

Docker caches layers. If apt-get update is in a separate RUN, the package index cache may be stale when install runs, causing package-not-found errors.

## References

- [Docker Best Practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [Dockerfile Best Practice: Remove apt package lists after install](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get)

---

Source: https://codepathfinder.dev/registry/docker/best-practice/DOCKER-BP-014
Code Pathfinder — Open source, type-aware SAST with cross-file dataflow analysis
