[ PROMPT_NODE_26828 ]
Modal 图像
[ SKILL_DOCUMENTATION ]
# Modal 镜像
## 概述
Modal 镜像定义了代码运行的环境 - 即安装了依赖项的容器。镜像通过从基础镜像开始的方法链构建。
## 基础镜像
从基础镜像开始并链式调用方法:
python
image = (
modal.Image.debian_slim(python_version="3.13")
.apt_install("git")
.uv_pip_install("torch<3")
.env({"HALT_AND_CATCH_FIRE": "0"})
.run_commands("git clone https://github.com/modal-labs/agi")
)
可用的基础镜像:
- `Image.debian_slim()` - 带有 Python 的 Debian Linux
- `Image.micromamba()` - 带有 Micromamba 包管理器的基础镜像
- `Image.from_registry()` - 从 Docker Hub, ECR 等拉取
- `Image.from_dockerfile()` - 从现有的 Dockerfile 构建
## 安装 Python 包
### 使用 uv(推荐)
使用 `.uv_pip_install()` 进行快速包安装:
python
image = (
modal.Image.debian_slim()
.uv_pip_install("pandas==2.2.0", "numpy")
)
### 使用 pip
如果需要,可回退到标准 pip:
python
image = (
modal.Image.debian_slim(python_version="3.13")
.pip_install("pandas==2.2.0", "numpy")
)
严格锁定依赖项(例如 `"torch==2.8.0"`)以确保可复现性。
## 安装系统包
使用 apt 安装 Linux 包:
python
image = modal.Image.debian_slim().apt_install("git", "curl")
## 设置环境变量
将字典传递给 `.env()`:
python
image = modal.Image.debian_slim().env({"PORT": "6443"})
## 运行 Shell 命令
在镜像构建期间执行命令:
python
image = (
modal.Image.debian_slim()
.apt_install("git")
.run_commands("git clone https://github.com/modal-labs/gpu-glossary")
)
## 在构建时运行 Python 函数
下载模型权重或执行设置:
python
def download_models():
import diffusers
model_name = "segmind/small-sd"
pipe = diffusers.StableDiffusionPipeline.from_pretrained(model_name)
hf_cache = modal.Volume.from_name("hf-cache")
image = (
modal.Image.debian_slim()
.pip_install("diffusers[torch]", "transformers")
.run_function(
download_models,
secrets=[modal.Secret.from_name("huggingface-secret")],
volumes={"/root/.cache/huggingface": hf_cache},
)
)
## 添加本地文件
### 添加文件或目录
python
image = modal.Image.debian_slim().add_local_dir(
"/user/erikbern/.aws",
remote_path="/root/.aws"
)
默认情况下,文件在容器启动时添加。使用 `copy=