Interview Prep/Build Tools (Java, Node.js, Python, .NET)/Python builds (pip, venv, requirements.txt)

A Docker build fails with "error: command 'gcc' failed" while installing a Python package. Why?

IntermediateTroubleshootingPython builds (pip, venv, requirements.txt)
Answer

Short answer

The package has C extensions and no pre-built wheel was available for your Python version/platform, so pip tried to compile it from source — but the slim/alpine image has no compiler or headers. Fix it by installing build tools in a build stage, using a package variant with wheels (e.g. psycopg2-binary), or a base image with wheels available.

Typical culprits

psycopg2, mysqlclient, lxml, cryptography (older versions), numpy on very new Python or on Alpine.

Options

  1. Install build dependencies (best done in a build stage):
    RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev
    
  2. Use a binary variant: psycopg2-binary or psycopg[binary].
  3. Avoid Alpine for Python — it uses musl libc, so many manylinux wheels don't apply and everything compiles slowly. python:3.12-slim (Debian) usually gets wheels.
  4. Upgrade pip (pip install --upgrade pip) — older pips don't recognise newer wheel tags.

What to say in the interview

"pip fell back to building from source because no wheel matched, and the image lacks gcc and headers. I either add build-essential and the dev headers in a build stage, switch to a binary wheel package, or use a Debian slim base instead of Alpine."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Python apps: pip, venv & requirements.txt

More on Python builds (pip, venv, requirements.txt)