IT-INFO

Where IT meets innovation, IT-INFO lights the path to technological brilliance

Compiling Your Application With cx_freeze

Compiling Your Application With cx_freeze

Compiling Your Application

To compile a FastAPI application, we'll use the cx_Freeze library and Docker. This process allows us to create a standalone executable of our application, which can be run without requiring a full Python environment.

1. Create setup.py

First, we create a setup.py file at the same level as your Dockerfile. This file defines how cx_Freeze should compile our application.

from cx_Freeze import setup, Executable

# Define the executable and build options
executables = [Executable("app/main.py", base=None)]
build_options = {
    "packages": ["fastapi", "uvicorn", "sqlalchemy", "passlib"],
    "excludes": [],
    "include_files": [(".env", ".env")],
}
setup(
    name="FastAPIApp",
    version="0.1",
    description="A FastAPI application",
    options={"build_exe": build_options},
    executables=executables,
)

This script specifies:

  • The main Python file to be compiled (app/main.py)
  • Required packages to be included in the build
  • Any files to be included (like .env)
  • Metadata about the application

2. Build the Compiled Version

Next, we use a Python image as a builder in our Dockerfile:

# Stage 1: Build the FastAPI application with cx_Freeze
FROM python:3.10-alpine AS builder
WORKDIR /var/www/api

# Install dependencies for building
RUN apk add --no-cache postgresql-libs libpq postgresql-dev gcc musl-dev

# Copy application files
COPY . .

# Install Python dependencies including cx_Freeze
RUN --mount=type=cache,target=/root/.cache pip install -r requirements.txt

# Compile the application
RUN python setup.py build

This stage:

  • Uses a Python Alpine image for a smaller footprint
  • Installs necessary system dependencies
  • Copies the application files
  • Installs Python dependencies
  • Runs the setup.py script to compile the application

3. Run the Compiled Application

In the same Dockerfile, we use another Python image to run the compiled app:

# Stage 2: Create the final image
FROM python:3.10-alpine
WORKDIR /var/www/api

# Copy the built application from the builder stage
COPY --from=builder /var/www/api/build/exe.linux-x86_64-3.10 /var/www/api

# Install runtime dependencies
RUN apk add --no-cache postgresql-libs

# Ensure the executable is runnable
RUN chmod +x /var/www/api/main

# Expose the application port
EXPOSE 8080

# Command to run the compiled application
CMD ["/var/www/api/main"]

This stage:

  • Starts with a fresh Python Alpine image
  • Copies only the compiled application from the builder stage
  • Installs minimal runtime dependencies
  • Makes the main executable runnable
  • Exposes the necessary port
  • Sets the command to run the compiled application

Created on Aug. 28, 2024, 9:15 a.m.