制作镜像
准备服务代码man.py
文件夹结构
python
import os
from loguru import logger
from fastapi import FastAPI
import uvicorn
app = FastAPI()
# 定义日志输出目录
log_directory = os.getenv("LOG", "/work/logs/")
os.makedirs(log_directory, exist_ok=True)
logger.add(os.path.join(log_directory, "app_{time}.log"), rotation="100 MB", retention="10 days")
@app.get("/test")
async def read_root(msg):
logger.info(msg)
return {"message": "Hello, World! you input {}".format(msg)}
def main():
uvicorn.run("main:app", reload=True, host="0.0.0.0", port=8080)
if __name__ == "__main__":
main()
生成项目的requirements.txt
- 安装pipreqs模块
- 使用pipreqs生成项目的 requirements.txt
pipreqs ./ --encoding=utf-8
编辑Dockerfile
bash
FROM 192.168.93.20/devops/python:3.9.21-slim-bullseye
LABEL tag="app-depoly"
WORKDIR /work
ENV LOG=./logs
COPY ./service/* ./service/code
RUN pip install --upgrade pip && pip install -r ./service/code/requirements.txt
CMD python3 ./service/code/main.py
构建容器
- 在Dockerfile目录执行下列命令
bash
docker build -t 192.168.93.20/devops/python:deploy_app .

- 查看构建的镜像
bash
docker images

- 检验镜像是否可用
bash
docker run -itd -p 8080:8080 -v /app_logs:/work/logs --name yahoo 192.168.93.20/devops/python:deploy_app # 创建一个容器并将容器的8080端口暴露到宿主机8080端口,挂载一个宿主机共享目录/container_data到/work/service
docker ps -al # 查看容器

bash
docker logs yahoo #查看服务日志,
到这里服务起来了,验证了Dockerfile的正确性!
使用docker-compose管理服务
- 编辑docker-compose.yml
bash
version: "3.7"
services:
webapp:
build:
context: .
dockerfile: Dockerfile
labels:
- "webapp"
ports:
- "8080:8080"
restart: on-failure
volumes:
- "/app_logs:/work/logs"
- 使用docker-compose构建镜像并启动容器服务

- 检验容服务是否OK
这里就实现了docker-compose发布服务了!