Where IT meets innovation, IT-INFO lights the path to technological brilliance
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.
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:
app/main.py
).env
)
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:
setup.py
script to compile the 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:
Created on Aug. 28, 2024, 9:15 a.m.