Using Poetry Dependency Groups to Keep Production Installs Lean
Learn how to declare dependency groups in pyproject.toml, install only runtime deps for production, and verify a lean environment.
05 Dec 2025, 11:54 UTC

The Problem: Bloated Production Images
Including development tools like pytest, black, or sphinx in a production environment increases attack surface and image size. Separate requirements files can drift, causing version conflicts.
Prerequisites
- Poetry 1.2.0 or newer (2.x recommended).
- A Python project initialized with
poetry init. - Optional:
poetry-plugin-exportinstalled viapoetry self add poetry-plugin-exportif you need to generaterequirements.txtfor Docker.
Configuring Dependency Groups
Define groups under [tool.poetry.group..dependencies]. The [tool.poetry.dependencies] section is the implicit "main" group.
[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.100.0"
uvicorn = "^0.22.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.0.0"
black = "^23.0.0"
httpx = "^0.24.0"
[tool.poetry.group.docs]
optional = true
[tool.poetry.group.docs.dependencies]
sphinx = "^6.0.0"
sphinx-rtd-theme = "^1.2.0"
Note: A group marked optional = true is not installed by default; omit the flag to install it only when requested.
Installation Strategies
Run these commands in the project root where pyproject.toml resides.
Local Development (all non‑optional groups)
poetry install
Local Development with optional docs
poetry install --with docs
CI Testing (main + dev)
poetry install --only main,dev
Production Deployment (leanest)
poetry install --only main
Risk: Using --without dev leaves any other non‑optional groups installed; --only main guarantees exclusivity.
Exporting for Docker (Non‑Poetry Runtimes)
Generate a requirements file containing only the main group:
poetry export --only main --without-hashes -f requirements.txt -o requirements.txt
Use the output in a Dockerfile with pip install -r requirements.txt.
Verification and Diagnostics
- Environment check: After
poetry install --only main, runpoetry run pytest --version. Expect a "command not found" error. - Lock file validation: Run
poetry checkto ensurepyproject.tomlandpoetry.lockare synchronized. - Dependency graph: Run
poetry show --treeto inspect which groups are present.
Rollback (State Change)
If you installed the wrong groups, reset the virtual environment:
poetry env remove $(poetry env info --path)
poetry install --only main
This removes the current env and recreates it with only the main group.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.