Skip to content

🚀 CUDA 基础镜像配置指南

📋 概述

这是一个基于 NVIDIA CUDA 12.4.1 + cuDNN + Ubuntu 22.04 的深度学习基础镜像配置,预装了 PyTorch 2.7.0 和相关工具。


🐳 Dockerfile 配置

dockerfile
# 🏗️ 使用 NVIDIA CUDA 12.4.1 + cuDNN + Ubuntu 22.04 基础镜像
FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04

# ⚙️ 设置环境变量
ENV DEBIAN_FRONTEND=noninteractive

# 🔧 更新并安装基础工具
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    wget \
    git \
    build-essential \
    software-properties-common \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# 🐍 添加 deadsnakes PPA 并安装 Python 3.12
RUN add-apt-repository -y ppa:deadsnakes/ppa && \
    apt-get update && \
    apt-get install -y --no-install-recommends \
    python3.12 \
    python3.12-dev \
    && rm -rf /var/lib/apt/lists/*

# 🔄 设置 Python 3.12 为默认版本
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1

# 📦 安装 pip 和 setuptools(替代 distutils)
RUN wget https://bootstrap.pypa.io/get-pip.py && \
    python3.12 get-pip.py && \
    rm get-pip.py && \
    pip install --no-cache-dir setuptools

# 🔥 安装 PyTorch 及相关库
RUN pip install torch==2.7.0 torchvision==0.22.0 torchaudio==2.7.0 --index-url https://download.pytorch.org/whl/cu128

# 📁 设置工作目录
WORKDIR /workspace

🛠️ 构建脚本

bash
#!/bin/bash

# 🏷️ 镜像标签定义
TAG="cuda:12.4.1-cudnn-devel-ubuntu22.04-torch2.7.0"

echo "🧹 清理旧镜像..."
docker rmi $TAG 2>/dev/null || true

echo "🔨 开始构建镜像..."
docker build -t $TAG .

echo "✅ 镜像构建完成!"
echo "📦 镜像标签: $TAG"

📊 镜像包含内容

🎯 核心组件

  • CUDA 12.4.1 - NVIDIA GPU 计算平台
  • cuDNN - 深度神经网络加速库
  • Ubuntu 22.04 - 操作系统基础

🐍 Python 环境

  • Python 3.12 - 最新稳定版 Python
  • pip - Python 包管理器
  • setuptools - Python 包构建工具

🔥 深度学习框架

  • PyTorch 2.7.0 - 深度学习框架
  • torchvision 0.22.0 - 计算机视觉库
  • torchaudio 2.7.0 - 音频处理库

🛠️ 开发工具

  • git - 版本控制系统
  • wget - 文件下载工具
  • build-essential - 编译工具链
  • ca-certificates - SSL 证书

🚀 使用方法

1️⃣ 构建镜像

bash
chmod +x build.sh
./build.sh

2️⃣ 运行容器

bash
# 使用 GPU 运行
docker run --gpus all -it --rm \
  -v $(pwd):/workspace \
  cuda:12.4.1-cudnn-devel-ubuntu22.04-torch2.7.0 \
  python3 -c "import torch; print(f'PyTorch版本: {torch.__version__}'); print(f'CUDA可用: {torch.cuda.is_available()}')"

3️⃣ 验证安装

bash
# 进入容器交互模式
docker run --gpus all -it --rm \
  -v $(pwd):/workspace \
  cuda:12.4.1-cudnn-devel-ubuntu22.04-torch2.7.0 \
  bash

# 在容器内验证
python3 -c "import torch; print(f'PyTorch版本: {torch.__version__}')"
python3 -c "import torch; print(f'CUDA版本: {torch.version.cuda}')"
python3 -c "import torch; print(f'GPU数量: {torch.cuda.device_count()}')"

💡 注意事项

  1. 📏 镜像大小 - 由于包含完整的 CUDA 和 cuDNN,镜像体积较大
  2. ⚡ GPU 要求 - 需要 NVIDIA GPU 和正确的驱动程序
  3. 🔧 构建时间 - 首次构建可能需要较长时间下载依赖
  4. 🔄 版本更新 - 定期检查 PyTorch 和 CUDA 的更新版本

🔗 相关资源


🎯 适用场景

  • 🧠 深度学习研究 - 训练和推理模型
  • 🔬 AI 实验 - 快速搭建实验环境
  • 🏭 生产部署 - 一致的运行环境
  • 👨‍💻 团队协作 - 统一的开发环境

💡 提示: 此镜像适合需要 GPU 加速的深度学习项目,确保你的系统已安装正确的 NVIDIA 驱动和 Docker GPU 支持。