You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ansible实现多阶段Docker构建?镜像指定冲突问题求解

问题确认

没错,你的判断完全正确。YAML语法中同一个键重复出现时,后出现的键值会直接覆盖前面的。所以你的docker_container任务实际上只加载了python:latest镜像,ubuntu:latest被直接忽略了。这也是为什么容器内显示Debian系统——官方python:latest镜像默认基于Debian发行版。

用Ansible实现多阶段Docker构建的正确方式

多阶段构建的核心是通过Dockerfile定义完整的构建流程,再用Ansible的docker_build模块执行镜像构建,而非直接在docker_container任务中指定多个镜像。具体步骤如下:

1. 编写多阶段构建的Dockerfile

比如你想要基于Ubuntu镜像搭建Python环境,将以下内容保存为./Dockerfile:

# 第一阶段:基于Ubuntu安装Python依赖
FROM ubuntu:latest AS base
RUN apt-get update && apt-get install -y python3 python3-pip
# 验证系统版本
RUN lsb_release -a

# 第二阶段(可选):如果需要轻量化镜像,复制第一阶段的产物到轻量基础镜像
# FROM python:slim
# COPY --from=base /usr/bin/python3 /usr/bin/python3
# COPY --from=base /usr/lib/python3 /usr/lib/python3

2. 在Ansible Playbook中构建镜像并启动容器

替换原来的docker_container任务,先构建自定义镜像,再基于该镜像启动容器:

tasks:
  - name: 构建多阶段Docker镜像
    docker_build:
      path: ./
      dockerfile: Dockerfile
      name: my-ubuntu-python
      tag: latest

  - name: 启动基于自定义镜像的容器
    docker_container:
      name: ubuntu-python
      image: my-ubuntu-python:latest
      state: started
      command: sleep infinity

3. 验证结果

容器启动后进入内部执行lsb_release -a,就能看到Ubuntu的系统信息了。

简化方案(无需多阶段构建场景)

如果只是需要在Ubuntu容器内运行Python,也可以跳过多阶段构建,直接用Ubuntu镜像启动容器后,在容器内安装Python:

tasks:
  - name: 启动Ubuntu容器
    docker_container:
      name: ubuntu
      image: ubuntu:latest
      state: started
      command: sleep infinity
      detach: true

  - name: 在容器内安装Python
    ansible.builtin.shell: apt-get update && apt-get install -y python3 python3-pip
    delegate_to: ubuntu

内容的提问来源于stack exchange,提问作者MijatTomić

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:22:07