How to precompile Python code in Dockerfile

In order to precompile Python code in a Dockerfile, you can use the compileall module. This is useful if you want to avoid the overhead of compiling Python code at runtime:

RUN python -m compileall /app

Full example

Here’s an example Dockerfile that precompiles Python code:

FROM python:3.12

WORKDIR /app

COPY . .

RUN python -m compileall /app

CMD ["python", "app.py"]