84 lines
2.5 KiB
Docker
84 lines
2.5 KiB
Docker
# 使用多阶段构建,先安装构建依赖
|
|
FROM python:3.9-slim AS builder
|
|
|
|
# 设置时区
|
|
ENV TZ=Asia/Shanghai
|
|
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
|
|
|
# 设置工作目录
|
|
WORKDIR /build
|
|
|
|
# 安装netcat用于网络连接检查
|
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
curl \
|
|
build-essential \
|
|
default-libmysqlclient-dev \
|
|
netcat-openbsd \
|
|
&& apt-get clean \
|
|
&& rm -rf /var/lib/apt/lists/*
|
|
|
|
# 复制项目依赖文件
|
|
COPY requirements.txt .
|
|
|
|
# 安装Python依赖
|
|
RUN pip install --no-cache-dir -r requirements.txt
|
|
|
|
# 最终阶段,使用轻量镜像
|
|
FROM python:3.9-slim
|
|
|
|
# 设置时区
|
|
ENV TZ=Asia/Shanghai
|
|
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
|
|
|
# 清空所有默认源
|
|
RUN rm -rf /etc/apt/sources.list.d/* && \
|
|
rm -f /etc/apt/sources.list
|
|
|
|
# 替换为阿里云源
|
|
RUN echo "\
|
|
deb https://mirrors.aliyun.com/debian/ bookworm main non-free-firmware contrib\n\
|
|
deb-src https://mirrors.aliyun.com/debian/ bookworm main non-free-firmware contrib\n\
|
|
deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free-firmware contrib\n\
|
|
deb-src https://mirrors.aliyun.com/debian/ bookworm-updates main non-free-firmware contrib\n\
|
|
deb https://mirrors.aliyun.com/debian/ bookworm-backports main non-free-firmware contrib\n\
|
|
deb-src https://mirrors.aliyun.com/debian/ bookworm-backports main non-free-firmware contrib\n\
|
|
deb https://mirrors.aliyun.com/debian-security bookworm-security main non-free-firmware contrib\n\
|
|
deb-src https://mirrors.aliyun.com/debian-security bookworm-security main non-free-firmware contrib\n\
|
|
" > /etc/apt/sources.list
|
|
|
|
|
|
# 安装运行时依赖
|
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
curl \
|
|
default-libmysqlclient-dev \
|
|
netcat-openbsd \
|
|
&& apt-get clean \
|
|
&& rm -rf /var/lib/apt/lists/*
|
|
|
|
# 设置工作目录
|
|
WORKDIR /app
|
|
|
|
# 从构建阶段复制已安装的依赖
|
|
COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages
|
|
COPY --from=builder /usr/local/bin /usr/local/bin
|
|
|
|
# 复制应用代码
|
|
COPY . .
|
|
|
|
# 确保脚本可执行
|
|
RUN chmod +x entrypoint.sh
|
|
|
|
# 设置环境变量
|
|
ENV PYTHONPATH=/app:$PYTHONPATH
|
|
ENV PORT=8000
|
|
ENV HOST=0.0.0.0
|
|
|
|
# 暴露端口
|
|
EXPOSE 8000
|
|
|
|
# 添加健康检查
|
|
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
|
|
CMD curl -f http://localhost:8000/health || exit 1
|
|
|
|
# 设置入口点
|
|
ENTRYPOINT ["./entrypoint.sh"] |