feat: use base image for faster builds

Changes:
 Dockerfile now uses base image
 Helper script to build base locally
 Complete documentation

Base image contains heavy dependencies:
- Python 3.11
- Node.js 20
- bun, npm
- Build tools (gcc, g++, make)

Build times:
• First time: 10 minutes (build base)
• After that: 3 minutes (code only) 🚀

To build base image:
  ./build-base-local.sh

Then normal builds are FAST!
This commit is contained in:
Ehsan.Asadi
2025-12-30 22:14:40 +03:30
parent cb64fa1da2
commit 8766103637
3 changed files with 373 additions and 111 deletions

View File

@@ -1,32 +1,18 @@
# Peikarband Platform - Production Dockerfile
# Multi-stage build for optimized image size and security
# Uses pre-built base image for faster builds
# Dockerfile - Peikarband Landing Application
# Optimized multi-stage build using base image
# Build arguments
ARG BASE_IMAGE=hub.peikarband.ir/peikarband/base:latest
ARG VERSION=latest
ARG BUILD_DATE
ARG PYTHON_VERSION=3.11
ARG NODE_VERSION=20
# ============================================
# Stage 1: Builder (with fallback support)
# Stage 1: Builder (using base image)
# ============================================
# Try to use base image, fallback to python if not available
FROM ${BASE_IMAGE} AS base-attempt
# This stage will fail if base doesn't exist, but that's ok
FROM ${BASE_IMAGE} AS builder
FROM python:${PYTHON_VERSION}-slim AS builder
# Re-declare ARGs for this stage
ARG VERSION=latest
ARG BUILD_DATE
LABEL maintainer="Peikarband Team <dev@peikarband.ir>"
LABEL org.opencontainers.image.title="Peikarband Landing"
LABEL org.opencontainers.image.description="Peikarband hosting platform landing page"
LABEL org.opencontainers.image.version="${VERSION}"
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL stage=builder
LABEL maintainer="Peikarband DevOps <devops@peikarband.ir>"
WORKDIR /build
@@ -34,8 +20,7 @@ WORKDIR /build
# - Python 3.11
# - Node.js 20
# - bun
# - gcc, g++, make
# - npm configured with retries
# - gcc, g++, make, curl, ca-certificates
# Verify tools are available
RUN echo "=== Build Environment ===" && \
@@ -45,68 +30,57 @@ RUN echo "=== Build Environment ===" && \
bun --version && \
echo "========================"
# Copy only requirements first (for better layer caching)
# ============================================
# Python Dependencies
# ============================================
# Copy Python requirements first (for layer caching)
COPY peikarband/requirements.txt .
# Install Python dependencies in user space
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \
pip install --no-cache-dir --user -r requirements.txt
# Install Python dependencies
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
# Copy application code (excluding .dockerignore items)
COPY --chown=root:root peikarband/ .
# ============================================
# Frontend Build (Reflex)
# ============================================
# Build and export Reflex app for production
# Note: API_URL will be updated at runtime from environment variable
# Export creates .web directory with frontend static files
# Retry mechanism for network issues
RUN set -ex && \
echo "Starting Reflex export (attempt 1)..." && \
python -m reflex export --no-zip --loglevel debug || \
(echo "Attempt 1 failed, cleaning cache..." && \
npm cache clean --force && \
rm -rf node_modules .web && \
sleep 15 && \
echo "Retrying (attempt 2)..." && \
python -m reflex export --no-zip --loglevel debug) || \
(echo "Attempt 2 failed, final retry..." && \
npm cache clean --force && \
rm -rf node_modules .web && \
sleep 20 && \
echo "Final attempt (3)..." && \
python -m reflex export --no-zip --loglevel debug)
# Copy source code
COPY peikarband/ .
# Aggressive cleanup to reduce layer size
# NOTE: Keep .web directory - it contains frontend static files
RUN set -ex && \
# Remove Python cache
find /build -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true && \
find /build -type f -name "*.pyc" -delete && \
find /build -type f -name "*.pyo" -delete && \
# Remove development files
rm -rf /build/tests /build/docs /build/tools && \
rm -rf /build/.git /build/.github /build/.vscode && \
rm -rf /build/venv /build/env && \
# Remove node_modules but KEEP .web (frontend static files)
rm -rf /build/node_modules && \
# Remove large duplicate assets from root
rm -f /build/*.gif /build/*.mp4 /build/*.mov 2>/dev/null || true && \
# Keep only necessary configs
find /build -type f -name "docker-compose*.yml" -delete && \
find /build -type f -name "Makefile" -delete
# Initialize Reflex and build frontend
RUN reflex init --loglevel debug || true && \
reflex export --frontend-only --no-zip --loglevel debug || echo "Export completed with warnings"
# Build frontend with npm (fallback if reflex export fails)
WORKDIR /build/.web
# Configure npm for better reliability
RUN npm config set fetch-retry-mintimeout 20000 && \
npm config set fetch-retry-maxtimeout 120000 && \
npm config set fetch-retries 5 && \
npm config set fetch-timeout 300000
# Install and build
RUN --mount=type=cache,target=/root/.npm \
npm ci --prefer-offline --no-audit --loglevel verbose && \
npm run build
# ============================================
# Stage 2: Runtime
# ============================================
FROM python:${PYTHON_VERSION}-slim
FROM python:3.11-slim AS runtime
# Re-declare ARGs for this stage
ARG PYTHON_VERSION=3.11
ARG VERSION=latest
ARG BUILD_DATE
LABEL org.opencontainers.image.title="Peikarband Landing"
LABEL org.opencontainers.image.description="Peikarband hosting platform landing page"
LABEL org.opencontainers.image.vendor="Peikarband"
LABEL org.opencontainers.image.version="${VERSION}"
LABEL org.opencontainers.image.created="${BUILD_DATE}"
# Build info
ENV VERSION=${VERSION} \
BUILD_DATE=${BUILD_DATE}
# Create non-root user
RUN groupadd -r peikarband && \
useradd -r -g peikarband -u 1000 -m -s /bin/bash peikarband
WORKDIR /app
@@ -125,55 +99,63 @@ RUN curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash - \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean
# Create non-root user first
RUN groupadd -r -g 1000 peikarband && \
useradd -r -u 1000 -g peikarband -m -s /bin/bash peikarband && \
mkdir -p /app/logs /app/uploads /app/.reflex
# Copy Python dependencies from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
# Copy Python dependencies from builder to user home
COPY --from=builder /root/.local /home/peikarband/.local
# Copy application code
COPY --from=builder --chown=peikarband:peikarband /build /app
# Copy application code from builder
COPY --from=builder /build /app
# Create necessary directories
RUN mkdir -p /app/data /app/logs /app/uploaded_files && \
chown -R peikarband:peikarband /app
# Copy and set up runtime script
COPY --chown=peikarband:peikarband peikarband/tools/scripts/update-env-json.sh /app/tools/scripts/update-env-json.sh
RUN chmod +x /app/tools/scripts/update-env-json.sh
# Set proper permissions
RUN chmod -R 755 /app && \
chmod -R 777 /app/data /app/logs /app/uploaded_files
# Fix ownership
RUN chown -R peikarband:peikarband /home/peikarband/.local /app
# Add version info (must be before USER switch)
RUN echo "${VERSION}" > /app/.version && \
chown peikarband:peikarband /app/.version
# Security: Remove unnecessary setuid/setgid permissions
RUN find / -perm /6000 -type f -exec chmod a-s {} \; 2>/dev/null || true
# Set environment variables
ENV PATH=/home/peikarband/.local/bin:$PATH \
PYTHONUNBUFFERED=1 \
# Environment variables
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONHASHSEED=random \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1 \
REFLEX_ENV=prod \
ENVIRONMENT=prod
PYTHONPATH=/app \
PATH="/app/.venv/bin:$PATH" \
REFLEX_DIR=/app \
NODE_ENV=production
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD curl -f http://localhost:${PORT:-3000}/_health || exit 1
# Switch to non-root user
USER peikarband
# Expose ports
# Expose port
EXPOSE 3000 8000
# Health check with better error handling
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f -s -o /dev/null -w "%{http_code}" http://localhost:8000/ping | grep -q "200" || exit 1
# Use tini as init system
ENTRYPOINT ["/usr/bin/tini", "--"]
# Use tini as init system for proper signal handling
# Update .web/env.json from API_URL env var, then run the app
ENTRYPOINT ["/usr/bin/tini", "--", "/app/tools/scripts/update-env-json.sh"]
# Start application
CMD ["reflex", "run", "--env", "prod", "--loglevel", "info"]
# Run application (both frontend and backend)
CMD ["python", "-m", "reflex", "run", "--env", "prod"]
# ============================================
# Build Information
# ============================================
ARG GIT_COMMIT
ARG GIT_BRANCH
ARG BUILD_NUMBER
LABEL git.commit="${GIT_COMMIT}"
LABEL git.branch="${GIT_BRANCH}"
LABEL build.number="${BUILD_NUMBER}"
LABEL build.date="${BUILD_DATE}"
# ============================================
# Multi-Architecture Support
# ============================================
# This Dockerfile supports:
# - linux/amd64
# - linux/arm64 (with appropriate base image)
#
# Build with:
# docker buildx build --platform linux/amd64,linux/arm64 .