# DOCKER-BP-017: Use WORKDIR Instead of cd

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

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

## Description

Detects use of 'cd' command in RUN instructions when WORKDIR is not used.
Using 'cd' in RUN commands is error-prone, less clear, and doesn't persist
across instructions. WORKDIR is the proper way to set working directory.

## Vulnerable Code

```python
FROM node:18

COPY . .

# Bad: cd doesn't persist, must chain all commands
RUN cd /app && npm install
RUN cd /app && npm build  # Must repeat cd
```

## Secure Code

```python
FROM node:18

# Good: WORKDIR persists across all subsequent instructions
WORKDIR /app
COPY . .
RUN npm install
RUN npm build  # Already in /app directory
```

## Detection Rule (Python SDK)

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


@dockerfile_rule(
    id="DOCKER-BP-017",
    name="Use WORKDIR Instead of cd",
    severity="LOW",
    cwe="CWE-710",
    category="best-practice",
    tags="docker,dockerfile,workdir,cd,directory,best-practice,maintainability,clarity,anti-pattern",
    message="Use WORKDIR instruction instead of 'cd' in RUN commands."
)
def use_workdir():
    return all_of(
        any_of(
            instruction(type="RUN", contains=" cd "),
            instruction(type="RUN", regex=r"\bcd\s+")
        ),
        missing(instruction="WORKDIR")
    )
```

## How to Fix

- Review your Dockerfile to address the use workdir instead of cd issue
- Follow Docker official best practices for image building
- Use docker build --check to validate Dockerfile syntax and best practices

## FAQ

**Q: Why does this rule flag use workdir instead of cd?**

Use WORKDIR instruction instead of 'cd' in RUN commands.

**Q: How do I fix this?**

Review the secure code example in the playground above and apply the recommended pattern to your Dockerfile or docker-compose.yml.

## References

- [Docker Best Practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [Dockerfile Best Practice: Use WORKDIR instead of cd](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#workdir)

---

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