使用 Dockerfile 部署 Python 服务的几种方式,同时也支持通过 Docker Compose 进行构建和运行,配置可参考:dockerfile.yml。
Poetry
通过 Poetry 构建和运行:
FROM python:3.12
# 将当前工作目录设置为 /code
WORKDIR /code
# 拷贝依赖文件
COPY pyproject.toml poetry.lock /code/
RUN pip install -i https://pypi.douban.com/simple/ poetry
RUN poetry install --no-root --no-directory
# 拷贝项目数据到 code 目录
COPY . /code/
RUN poetry install --no-dev
# 声明要监听的端口
EXPOSE 5000
# 使用配置文件
CMD [ "poetry", "run", "gunicorn", "app.main:app", "--config", "config/gunicorn.py" ]
# 直接在参数中传递配置
# CMD [ "poetry", "run", "gunicorn", "app.main:app", "--workers", "2", "--worker-class", \
# "uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:5000" ]
分阶段构建:
FROM python:3.9-slim as export-reqs
WORKDIR /tmp
# 拷贝依赖文件
COPY pyproject.toml poetry.lock /tmp/
RUN pip install -i https://pypi.douban.com/simple/ poetry
# 从 Poetry 导出依赖到 requirements.txt
RUN poetry export -f requirements.txt --output requirements.txt --without-hashes
FROM python:3.12-slim-bookworm
# 将当前工作目录设置为 /code
WORKDIR /code
# 从 export-reqs 拷贝文件到工作目录
COPY --from=export-reqs /tmp/requirements.txt /code/
# 通过 pip 安装依赖
RUN pip install -i http://pypi.douban.com/simple/ --no-cache-dir --upgrade -r requirements.txt && rm requirements.txt
# 拷贝项目数据到 code 目录
COPY . /code/
# 创建保存数据的目录
RUN mkdir /data
# 声明要监听的端口
EXPOSE 5000
ENTRYPOINT [ "gunicorn", "app.main:app", "--config", "app/config/gunicorn.py" ]