# ========================================== # Flying-Translation 云端 API 容器配置 # ========================================== # 优化的 Dockerfile,基于 FastAPI 最佳实践 # ========================================== # 阶段1: 构建阶段 FROM python:3.10-slim as builder # 设置工作目录 WORKDIR /app # 安装构建依赖 RUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/* # 复制依赖文件 COPY requirements.txt . # 安装 Python 依赖(使用国内镜像加速) RUN pip install --no-cache-dir --user -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # 阶段2: 生产镜像 FROM python:3.10-slim # 设置环境变量 ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PYTHONFAULTHANDLER=1 \ PIP_NO_CACHE_DIR=1 \ PIP_DISABLE_PIP_VERSION_CHECK=1 # 安装运行时依赖 RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ && rm -rf /var/lib/apt/lists/* \ && useradd --create-home --shell /bin/bash appuser # 复制构建好的 Python 包 COPY --from=builder /root/.local /home/appuser/.local # 设置 PATH ENV PATH=/home/appuser/.local/bin:$PATH # 复制应用代码 WORKDIR /app COPY --chown=appuser:appuser . . # 切换到非 root 用户 USER appuser # 健康检查 HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD curl -f http://localhost:7860/health || exit 1 # 暴露端口 EXPOSE 7860 # 启动命令 CMD ["python", "-m", "uvicorn", "app:app", \ "--host", "0.0.0.0", \ "--port", "7860", \ "--workers", "2", \ "--log-level", "info", \ "--access-log"]