Py2Native Python to native compilerPython-zu-Native-Compiler

← All posts

2026-11-20

Protect Python Code in a Docker Build with a Single Command

Protect Python Code in a Docker Build with a Single Command
python compiler cython code protection open source

Protect Python Code in a Docker Build with a Single Command

Somewhere in your Dockerfile there is a step that protects your Python source — and it is almost certainly the most fragile line in the file. It probably involves a .pyx that someone regenerated on a laptop, a cythonize invocation that only works when the working directory is exactly right, and a comment that says “don’t touch, this took two days to get right.”

That is the manual version of Python code protection, and it fails the moment a second person touches the build.

The automated version is one command inside a build stage:

uv run py2native build main.py "app/**/*.py" --library --wheel dist/wheel

Py2Native compiles your own Python modules to native machine code (.pyd on Windows, .so on Linux, .dylib on macOS) and hides the whole Cython toolchain behind that command. You write plain Python. There are no .pyx files to maintain, no manual cythonize step, and no C extensions to hand-write — doing all of that yourself is the hard way, and it is exactly the workflow this article replaces.

Why Manual Code Protection Breaks Your Docker Workflow

The failure mode is always the same: protection lives outside the build graph.

  • Drift between local and CI. You compile on your machine, commit the generated artifacts, and CI runs on a different architecture or interpreter version. The artifacts go stale, or they simply don’t load.
  • Dockerfile churn. Every new source directory needs a new COPY, a new glob, another compiler flag. The file grows a tail of one-off fixes nobody wants to refactor.
  • Broken layer caching. Copying the whole repo before installing dependencies invalidates the expensive layers on every commit, so builds get slower exactly when you iterate more.
  • No single source of truth. Half your protection is a checked-in binary, half is a build script, and nobody can say which one ships.

What you actually want is a repeatable step that behaves identically on a laptop, in CI, and inside the image: same inputs, same output, no intermediate files under version control.

Py2Native’s model is deliberately boring in the good way — one CLI command, sources in, native artifact out. The compiler is open source (MIT), so the core pipeline is auditable; the commercial Pro plugin adds signed-JWT license verification when you need to gate usage.

One-Time Setup: Prepare Your Project for Automated Compilation

You configure the project once. After that, the Dockerfile step never changes.

1. Install uv and add Py2Native

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

uv init --package mypkg
cd mypkg
uv add py2native

The build needs a platform C compiler and linker (MSVC on Windows, GCC on Linux, Clang on macOS) plus CPython 3.11–3.15 — including the free-threaded 3.14t and 3.15t builds. In Docker, that is a single apt-get install build-essential in the build stage, nothing more.

2. Keep a standard package layout

Py2Native expects what you already have: an entry module plus package sources, with no two modules sharing a name across the tree.

mypkg/
├── main.py
├── pyproject.toml
├── uv.lock
└── app/
    ├── __init__.py
    ├── billing.py
    ├── pricing.py
    └── reporting.py

__init__.py files are skipped during compilation — they’re namespace markers, not compilable code.

3. Add the Pro plugin if you need license verification

uv add py2nativepro
uv run py2native keygen private.pem public.pem
uv run py2native sign --private private.pem payload.json license.dat
uv run py2native show --public public.pem license.dat

keygen produces an EC P-256 keypair. sign turns a JWT payload into license.dat. show prints the claims, optionally verifying the signature against the public key. Only the public key ever goes into the executable — the private key stays with you, never in an image layer, never in the repo.

4. Declare the verification function in a .pxd file

This is the one small piece of Cython-adjacent syntax in the whole project, and it is a declaration, not an implementation. Drop the _p2n_bootstrap.pxd shipped with the Pro plugin into your source tree:

# _p2n_bootstrap.pxd
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)

Then write a single bridge module that calls it. Everything else in your codebase stays plain .py.

# license_gate.pyx
from _p2n_bootstrap cimport _runtime_verify_es256_jwt

def check(licenseString):
    license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
    return license

The plugin bakes the signature verification code and the public key into the executable, using compiled code with no third-party crypto libraries at runtime. You get the security of native verification plus the flexibility to call it from wherever your application decides entitlement.

From plain Python, the gate looks like any other import:

# main.py
import os
from license_gate import check

licenseString = os.environ.get("MYPKG_LICENSE", "")
if not check(licenseString):
    raise SystemExit("No valid license for this installation")

from app.pricing import run
run()

The Automated Pipeline: One Command in Your Dockerfile

Here is the whole thing. Build stage compiles, runtime stage ships the artifact and nothing else.

# syntax=docker/dockerfile:1

# ---------- build stage ----------
FROM python:3.13-slim AS build

RUN apt-get update \
 && apt-get install -y --no-install-recommends build-essential \
 && rm -rf /var/lib/apt/lists/*

COPY --from=ghcr.io/astral-sh/uv:0.11.8 /uv /usr/local/bin/uv

WORKDIR /src
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev

COPY . .

RUN --mount=type=secret,id=pro_license \
    --mount=type=secret,id=pro_public \
    uv run py2native build main.py "app/**/*.py" \
      --library \
      --wheel /out/wheel \
      --license /run/secrets/pro_license \
      --public /run/secrets/pro_public

# ---------- runtime stage ----------
FROM python:3.13-slim AS runtime
WORKDIR /app

COPY --from=ghcr.io/astral-sh/uv:0.11.8 /uv /usr/local/bin/uv
COPY --from=build /out/wheel /tmp/wheel
RUN uv pip install --system /tmp/wheel/*.whl && rm -rf /tmp/wheel

ENTRYPOINT ["python", "-m", "mypkg"]

No compiler in the runtime image. No .py sources either — just the compiled shared library plus the two files the wheel builder generates.

What that single command does

  1. Glob sources — build.py expands app/**/*.py (relative to --base if you set one).
  2. Plugin dispatch — pluginManager.extendBuild() runs, which is where Pro license checks happen.
  3. Cython → C — the compiler generates a bootstrap module, invokes Cython, and transpiles your modules to C.
  4. C → objects — the platform compiler builds each .c file with the right flags for Windows, Linux, or macOS.
  5. Link — link_shared_object() for --library mode, link_executable() for an executable.
  6. Wheel — whl.py assembles a PEP 427 wheel containing the compiled .pyd/.so.
  7. Embed — embed.py creates a uv-managed deployment directory when you pass --embed <dir>.

--library mode produces a wheel with one compiled shared library holding all your modules, plus __init__.py (a meta-path finder that redirects import mypkg.submodule into the native library) and __main__.py (which makes python -m mypkg work). Both are required; both are generated for you. Note that in library mode __main__.py is excluded from the source globs, since the wheel builder owns that file.

Third-party libraries stay untouched

Py2Native compiles your code. Dependencies like requests, pydantic, or sqlalchemy remain standard Python packages installed by uv sync — unchanged, unpatched, requiring no build configuration from you. This is the practical difference from protection tools that want a bespoke build file per dependency.

Monitoring and Failure Handling in CI/CD

A single command is only useful if it fails loudly. Wire the build so a broken protection step stops the pipeline.

name: release-image
on:
  push:
    tags: ["v*"]

jobs:
  build:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

      - name: Install uv
        run: curl -LsSf https://astral.sh/uv/install.sh | sh

      - name: Compile and smoke test
        run: |
          uv sync --frozen
          uv run py2native build main.py "app/**/*.py" \
            --library --wheel dist/wheel \
            --license license.dat --public public.pem 2>&1 | tee build.log
          uv run smoketest.py 2>&1 | tee -a build.log

      - name: Build runtime image
        run: |
          docker buildx build \
            --secret id=pro_license,src=license.dat \
            --secret id=pro_public,src=public.pem \
            --tag registry.example.com/mypkg:${{ github.sha }} \
            --load . 2>&1 | tee -a build.log

      - name: Upload build log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: build-log
          path: build.log

Three habits make this reliable:

  • Fail fast on licensing. Passing --license <file> makes the build refuse to proceed without a valid Pro license JWT. A bad key or an expired token surfaces in the build stage, not on a customer’s machine after deployment.
  • Test the compiled output, not the source. The repo’s smoketest.py pattern builds and then exercises the compiled package, which is the only way to catch a linking problem before shipping. Import your main module from the wheel and assert a known return value.
  • Cache the expensive parts. --mount=type=cache,target=/root/.cache/uv keeps the uv download cache across builds; keeping pyproject.toml and uv.lock in their own COPY layer means dependency resolution is reused until the lockfile changes. Py2Native downloads Python distributions and libraries on first use, so a warm cache matters.

Most build failures in this setup are mundane and visible in build.log: a missing build-essential in the build stage, a missing pyproject.toml copy, or a JWT whose iss/aud don’t match the expected values in your bridge module.

Best Practices for Secure and Maintainable Docker Builds

  • Separate compilation from runtime. Multi-stage is not optional here. Build stage: compilers, headers, keys. Runtime stage: the wheel and a Python interpreter.
  • Never bake in the private key. Use BuildKit secrets (--mount=type=secret) for both the build license and the public key. The private key never enters a layer, because signing happens before the build, on your workstation or in your release job.
  • Pick the right output. --wheel <dir> gives you a distributable artifact that installs cleanly with uv pip install. --embed <dir> gives you a uv-managed deployment directory when you want a self-contained folder to hand off.
  • Version your build license separately from your product license. The JWT passed to --license gates the compiler. The JWT your application verifies at runtime gates the customer. Rotating one shouldn’t touch the other.
  • Keep module names unique. Two files named utils.py in different source directories will collide during compilation. Namespace them.
  • Upgrade on a schedule. uv lock --upgrade-package py2native py2nativepro picks up compiler fixes and Cython updates; the supported matrix moves, and staying current is cheaper than debugging an old toolchain against CPython 3.15.
  • Accept the boundaries. Monkey-patching still works because third-party libraries remain Python source, and LGPL libraries stay replaceable by end users for compliance. Py2Native protects your code, not the ecosystem around it.

FAQ

Can I use Py2Native with existing Docker multi-stage builds?

Yes. Py2Native integrates seamlessly into multi-stage Docker builds. You can compile your Python code in a build stage using uv run py2native build, then copy only the resulting native binary or wheel into a minimal runtime stage, keeping your final image small and secure.

How does license verification work in a compiled Docker image?

With the Pro plugin, you embed license verification directly into your compiled code. You include a .pxd file that declares the verification function, then call _runtime_verify_es256_jwt with your license token and expected issuer/audience. The plugin bakes the public key and verification logic into the executable, so no third-party libraries are needed at runtime.

What if my project uses third-party libraries?

Py2Native leaves third-party Python libraries unmodified and works with them as-is. You don’t need to configure anything special; the compiler only transforms your custom code into native machine code, while dependencies remain as standard Python packages.

Is cross-compilation supported for different architectures?

Py2Native compiles natively for the platform and architecture of the build environment. To target multiple architectures, you can use Docker’s multi-platform build features (e.g., buildx) to run the compilation separately for each target platform.

Conclusion

Code protection belongs in the build, not in a README section that starts with “run this locally first.” One uv run py2native build line in a build stage gives you a compiled artifact, a reproducible pipeline, and a runtime image with no sources and no compiler in it.

Start by adding the dependency and running the command against your own project:

uv add py2native
uv run py2native build main.py "app/**/*.py" --library --wheel dist/wheel

Then move that exact line into your Dockerfile — and delete the manual steps for good. If you need to gate the output behind a signed license, add py2nativepro and the .pxd bridge above; the license verification walkthrough covers the runtime side in depth.

Related posts

EU label: AI-generated content