Caching pre-commit Environments on a Named Volume
The pre-commit framework builds an isolated environment per hook, and rebuilding those on every container is slow. This page caches pre-commit's environment directory on a named volume, so hook environments persist across rebuilds and commits stay fast.
Prerequisites
You need a pre-commit-based devcontainer.
- The
pre-commitframework installed and wired in postCreate. - A pinned
.pre-commit-config.yaml. - A named volume for the pre-commit cache.
Step-by-Step Implementation
- Mount the pre-commit cache on a volume.
{
"mounts": ["source=devcontainer-precommit,target=/home/vscode/.cache/pre-commit,type=volume"],
"remoteUser": "vscode"
}
- Install hooks (and their envs) on create.
{ "postCreateCommand": "pip install pre-commit && pre-commit install --install-hooks" }
- Confirm the cache is used.
pre-commit run --all-files # reuses cached hook environments
- Verify a rebuild doesn't rebuild hook envs.
Common Pitfalls
Slow commits come from rebuilding hook environments each container.
| Symptom | Root Cause | Remediation |
|---|---|---|
| Hook envs rebuild each container | Cache dir not on a volume | Mount ~/.cache/pre-commit on a volume |
| Permission denied writing cache | Volume owned by root | chown the cache dir to the user |
| Cache present but ignored | Wrong cache path | Target the exact pre-commit cache dir |
| Commits still slow | Hooks run on all files | Rely on staged-file runs |
Conclusion
pre-commit's per-hook environments are the slow part; cache them on a named volume and they persist across rebuilds. Warm them in postCreateCommand, and commits stay fast enough that developers never reach for --no-verify.
FAQ
What exactly is pre-commit caching?
The pre-commit framework creates an isolated environment per hook (a Python venv, a Node install, etc.) under ~/.cache/pre-commit. Caching that directory on a named volume means those environments persist across container rebuilds instead of being rebuilt each time.
Why do my commits get slow after a rebuild?
Because a fresh container has no hook environments, so the first run rebuilds them all. Mount the cache directory on a volume and warm it in postCreateCommand, and rebuilds reuse the environments, keeping commit time low.
Does caching affect which checks run?
No — the cache only holds the hook environments, not results. Your pinned .pre-commit-config.yaml still determines which hooks run and on which files. Caching purely removes the environment-build cost, so behaviour is unchanged.
Related
- Up to Pre-commit Hook Configuration for Containerized Workflows — the hooks overview.
- Configuring pre-commit in a Multi-Language Repo — the polyglot hooks that benefit most.
- Running Pre-commit Hooks on postCreateCommand with Husky — installing hooks at the right time.