mvn clean: Remove the target Directory (Maven)
mvn clean runs the clean lifecycle, which deletes the target/ directory so the next build starts from no prior outputs.
clean belongs to its own lifecycle, separate from the default one. CI commonly prefixes it (clean install, clean verify) to guarantee a fresh build.
What it does
clean triggers the clean lifecycle (pre-clean, clean, post-clean). The maven-clean-plugin's clean goal deletes the build output directory (target/ by default). It is a separate lifecycle, so mvn clean install runs clean first, then the default lifecycle up to install.
Common usage
mvn clean
mvn clean package
mvn clean verify
mvn clean install -DskipTestsFlags
| Flag / config | What it does |
|---|---|
| clean (phase) | Delete target/ before the next build |
| -Dmaven.clean.skip=true | Skip the clean even if invoked |
| <filesets> in plugin config | Delete extra paths beyond target/ |
| -B | Batch mode for CI |
In CI
On ephemeral runners a workspace is already empty, so clean is often redundant and just costs time; you can drop it when the runner is fresh. On reused/self-hosted runners, prefix clean to avoid stale outputs. Either way, ~/.m2/repository (the dependency cache) is outside target/ and is not touched by clean, so keep caching it.
Common errors in CI
"Failed to clean project: Failed to delete .../target/..." usually means a file is locked by a still-running process (a leftover Java process or an antivirus scanner on Windows). "Permission denied" deleting target/ means the directory is owned by another user, common when a prior container step ran as root. The dependency cache is unaffected by clean.