# Base Python image with correct version FROM python:3.12-slim-bookworm AS base # Set up environment variables according to HF guidelines ENV PYTHONDONTWRITEBYTECODE=1 \ POETRY_VERSION=1.8.4 \ POETRY_HOME=/opt/poetry \ POETRY_CACHE_DIR=/tmp/poetry_cache \ POETRY_NO_INTERACTION=1 \ POETRY_VIRTUALENVS_IN_PROJECT=true \ POETRY_VIRTUALENVS_CREATE=true \ POETRY_REQUESTS_TIMEOUT=15 # Create non-root user early (HF requirement) RUN useradd -m -u 1000 user WORKDIR /app/api # Install Poetry and dependencies in a single layer RUN pip install --no-cache-dir "poetry==${POETRY_VERSION}" && \ apt-get update && \ apt-get install -y --no-install-recommends \ gcc g++ libc-dev libffi-dev libgmp-dev libmpfr-dev libmpc-dev \ postgresql postgresql-contrib curl git nodejs npm && \ rm -rf /var/lib/apt/lists/* # Set up directories and permissions RUN mkdir -p /var/run/postgresql /var/lib/postgresql/data /data/storage && \ chown -R postgres:postgres /var/run/postgresql /var/lib/postgresql/data && \ chmod 2777 /var/run/postgresql && \ chmod 700 /var/lib/postgresql/data && \ chown -R user:user /app /opt/poetry /tmp/poetry_cache # Switch to user for Poetry operations USER user # Copy dependency files with correct ownership COPY --chown=user pyproject.toml poetry.lock poetry.toml ./ # Install Python dependencies RUN poetry install --no-root --no-dev # Initialize PostgreSQL as postgres user USER postgres RUN /usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/data && \ echo "host all all 0.0.0.0/0 md5" >> /var/lib/postgresql/data/pg_hba.conf && \ echo "listen_addresses='*'" >> /var/lib/postgresql/data/postgresql.conf # Switch back to user USER user # Set up user environment (HF requirement) ENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH # Copy source code COPY --chown=user . . # Copy entrypoint script COPY --chown=user docker/entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # Set required environment variables ENV FLASK_APP=app.py \ EDITION=SELF_HOSTED \ DEPLOY_ENV=PRODUCTION \ MODE=api \ DB_USERNAME=postgres \ DB_PASSWORD=difyai123456 \ DB_HOST=localhost \ DB_PORT=5432 \ DB_DATABASE=dify \ MIGRATION_ENABLED=true # Expose HF required port EXPOSE 7860 WORKDIR /app ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]