[docker]封装python的docker镜像

前言

基于alpine的python镜像封装。

docker pull python:3.10-alpine

准备

  • requirements.txt内容:
fastapi
uvicorn
  • server.py内容
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "world"}

if __name__ == '__main__':
    uvicorn.run("server:app",host="0.0.0.0",port=8000)
  • Dockerfile内容
FROM python:3.10-alpine
LABEL author="heruos"
WORKDIR /app
ADD . /app
EXPOSE 8000
RUN python3 -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
CMD python3 /app/server.py

打包

build方式

# 使用主机网络,避免容器内访问不到外网的奇怪问题
docker build --network=host -t mypy:1.0 .

commit方式

docker run -it --rm --network=host python:3.10-alpine sh

python3 -m pip install fastapi uvicorn -i https://pypi.tuna.tsinghua.edu.cn/simple

# docker cp将文件放到容器内

# 依据修改后的容器封装成新的镜像
docker commit -a "heruos" -m "install fastapi" 容器id myfastapi:1.0

compose方式

在docker-compose文件中添加封装配置,封装后直接启动。

  • docker-compose.yaml内容
version: "3"
services:
  fastapi:
    build:
      context: .
      dockerfile: Dockerfile
      # 使用主机网络
      network: host
    # 指定的镜像就是封装后的镜像文件名
    image: fastapi:1.0
    container_name: fa_app
    hostname: fa_app
    ports:
      - 8000:8000
  • 构建并启动
docker-compose up -d

测试

# 查看镜像和容器
docker images
docker ps -a

# curl测试
curl http://127.0.0.1:8000
posted @ 2022-07-26 10:29  花酒锄作田  阅读(999)  评论(0编辑  收藏  举报