Spaces:
Sleeping

ledger-sg / Dockerfile.3
cursorunlim's picture
Rename Dockerfile to Dockerfile.3
c1a5849 verified
Raw History Blame Contribute Delete
11.7 kB
# LedgerSG API Dockerfile
# Optimized for Hugging Face Spaces (Single-Stage, Non-Root, Persistent Services)
# Database Configuration: PostgreSQL (ledgersg_dev) + Redis (localhost:6379)
FROM python:3.13-trixie
# ──────────────────────────────────────────────────────────────────────────────
# 1. Environment Configuration
# ──────────────────────────────────────────────────────────────────────────────
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PIP_NO_CACHE_DIR=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV DEBIAN_FRONTEND=noninteractive
ENV APP_PORT=7860
ENV XDG_RUNTIME_DIR=/tmp/runtime-user
ENV PATH="/home/user/.local/bin:/usr/local/bin:${PATH}"
# CRITICAL: Use /data for PostgreSQL (persistent & user-writable)
ENV PGDATA=/data/postgresql
ENV PGHOST=/tmp
ENV PGPORT=5432
# Database Configuration (from .env)
ENV DB_NAME=ledgersg_dev
ENV DB_USER=ledgersg
ENV DB_PASSWORD=ledgersg_secret_to_change
ENV DB_HOST=localhost
ENV DB_PORT=5432
ENV REDIS_URL=redis://localhost:6379/0
# ──────────────────────────────────────────────────────────────────────────────
# 2. System Dependencies (Database + Dev Tools)
# ──────────────────────────────────────────────────────────────────────────────
RUN apt-get update && apt-get install -y \
bash coreutils ca-certificates cron curl wget git less procps sudo vim tar zip unzip tmux openssh-client rsync \
build-essential gcc gnupg cmake pkg-config \
libpq-dev libjson-c-dev libssl-dev libwebsockets-dev \
libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b libffi-dev libjpeg-dev libopenjp2-7-dev \
# Database Servers
postgresql postgresql-contrib redis-server \
# Cleanup
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# ──────────────────────────────────────────────────────────────────────────────
# 3. Toolchain Installation (UV, Bun)
# ──────────────────────────────────────────────────────────────────────────────
RUN cd /usr/bin && \
wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/bun && \
wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uv && \
wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uvx && \
chmod a+x /usr/bin/bun /usr/bin/uv*
# ──────────────────────────────────────────────────────────────────────────────
# 4. Python Dependencies
# ──────────────────────────────────────────────────────────────────────────────
RUN pip install --upgrade pip && \
pip install django-celery-beat && \
pip install -U django djangorestframework djangorestframework-simplejwt django-cors-headers django-filter && \
pip install psycopg[binary] celery[redis] redis py-moneyed pydantic weasyprint lxml python-decouple whitenoise gunicorn structlog sentry-sdk[django] pytest pytest-django pytest-cov pytest-xdist model-bakery factory-boy faker httpx ruff mypy django-stubs djangorestframework-stubs pre-commit ipython django-debug-toolbar django-extensions && \
pip install fastapi uvicorn httpx pydantic python-multipart sqlalchemy alembic aiofiles jinja2
# ──────────────────────────────────────────────────────────────────────────────
# 5. Node.js Installation (LTS 20.x)
# ──────────────────────────────────────────────────────────────────────────────
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/* && \
node --version && \
npm --version
# ──────────────────────────────────────────────────────────────────────────────
# 6. User & Permission Setup (Hugging Face Requirement)
# ──────────────────────────────────────────────────────────────────────────────
RUN groupadd -g 1000 user && \
useradd -m -u 1000 -g user -d /home/user user && \
echo "user ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/user && \
chmod 0440 /etc/sudoers.d/user && \
# Create ALL required directories
mkdir -p ${XDG_RUNTIME_DIR} /data /app /var/run/postgresql /data/postgresql && \
# CRITICAL FIX: Own ALL postgres-related directories
chown -R user:user ${XDG_RUNTIME_DIR} /data /app /var/run/postgresql /var/lib/postgresql && \
chmod 700 /data/postgresql
# ──────────────────────────────────────────────────────────────────────────────
# 7. Global NPM & Playwright
# ──────────────────────────────────────────────────────────────────────────────
RUN npm install -g --omit=dev pnpm@latest vite@latest vitest@latest && \
npx playwright install chromium && \
npx playwright install-deps chromium
# ──────────────────────────────────────────────────────────────────────────────
# 8. Database & Server Bootstrap Scripts (Embedded)
# ──────────────────────────────────────────────────────────────────────────────
RUN mkdir -p /app/core && \
chown -R user:user /app
COPY <<EOF /app/core/boot.py
from fastapi import FastAPI
import uvicorn
import os
app = FastAPI()
@app.get("/")
def read_root():
return {"status": "alive", "service": "LedgerSG Dev Space"}
@app.get("/health")
def health():
return {"status": "healthy"}
if __name__ == "__main__":
port = int(os.getenv("APP_PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)
EOF
# Create Entrypoint Script to manage Postgres, Redis, and Web Server
COPY <<EOF /usr/local/bin/entrypoint.sh
#!/bin/bash
set -e
echo "=== LedgerSG Development Space Starting ==="
# Ensure PostgreSQL data directory exists and is owned by user
mkdir -p \$PGDATA
chown -R user:user \$PGDATA
chmod 700 \$PGDATA
# Ensure PostgreSQL socket directory is accessible
mkdir -p /var/run/postgresql
chown -R user:user /var/run/postgresql
chmod 777 /var/run/postgresql
# Initialize Postgres if not exists (as user)
if [ ! -f "\$PGDATA/PG_VERSION" ]; then
echo "Initializing PostgreSQL cluster at \$PGDATA..."
su - user -c "initdb -D \$PGDATA"
# Configure PostgreSQL for password authentication
echo "Configuring PostgreSQL authentication..."
# Allow local connections with password
cat >> \$PGDATA/pg_hba.conf << 'PGHBA'
# TYPE DATABASE USER ADDRESS METHOD
local all all trust
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
PGHBA
# Configure listen addresses
echo "listen_addresses = 'localhost'" >> \$PGDATA/postgresql.conf
echo "port = 5432" >> \$PGDATA/postgresql.conf
fi
# Start Redis in background
echo "Starting Redis on port 6379..."
redis-server --daemonize yes
# Start Postgres in background (as user)
echo "Starting PostgreSQL on port 5432..."
su - user -c "pg_ctl -D \$PGDATA -l /tmp/postgres.log start"
# Wait for Postgres to be ready
echo "Waiting for PostgreSQL to accept connections..."
for i in {1..30}; do
if su - user -c "pg_isready -h localhost -p 5432" > /dev/null 2>&1; then
echo "βœ“ PostgreSQL is ready"
break
fi
if [ \$i -eq 30 ]; then
echo "βœ— PostgreSQL failed to start within 30 seconds"
cat /tmp/postgres.log
exit 1
fi
sleep 1
done
# Create database user and database if not exists
echo "Setting up database user and database..."
su - user -c "psql -h localhost -p 5432 -d postgres -c \"SELECT 1 FROM pg_roles WHERE rolname='\$DB_USER'\" | grep -q 1 || psql -h localhost -p 5432 -d postgres -c \"CREATE ROLE \$DB_USER WITH LOGIN PASSWORD '\$DB_PASSWORD';\""
su - user -c "psql -h localhost -p 5432 -d postgres -c \"SELECT 1 FROM pg_database WHERE datname='\$DB_NAME'\" | grep -q 1 || psql -h localhost -p 5432 -d postgres -c \"CREATE DATABASE \$DB_NAME OWNER \$DB_USER;\""
# Grant all privileges
su - user -c "psql -h localhost -p 5432 -d \$DB_NAME -c \"GRANT ALL PRIVILEGES ON DATABASE \$DB_NAME TO \$DB_USER;\""
echo "βœ“ Database setup complete: \$DB_NAME (user: \$DB_USER)"
# Verify Redis is running
echo "Verifying Redis connection..."
if redis-cli ping > /dev/null 2>&1; then
echo "βœ“ Redis is ready on localhost:6379"
else
echo "βœ— Redis failed to start"
exit 1
fi
# Execute the main command (Web Server)
echo "=== Starting Web Server on port \$APP_PORT ==="
exec "\$@"
EOF
RUN chmod +x /usr/local/bin/entrypoint.sh && \
chown -R user:user /app/core
# ──────────────────────────────────────────────────────────────────────────────
# 9. Finalization
# ──────────────────────────────────────────────────────────────────────────────
USER user
WORKDIR /app
COPY --chown=user:user . /app
# Ensure .env file exists (create empty if not provided)
RUN touch /app/.env && chown user:user /app/.env
EXPOSE ${APP_PORT}
# Healthcheck against the boot.py server
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD curl -f http://localhost:${APP_PORT}/health || exit 1
# Use Entrypoint to start DBs, then run the boot.py server
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["python", "/app/core/boot.py"]