Whisper Docker セットアップ:OpenAI Whisper を Docker で動かす完全ガイド

Whisper Docker セットアップ:OpenAI Whisper を Docker で動かす完全ガイド

Eric King

Eric King

Author


はじめに

OpenAI Whisper を Docker コンテナで動かすと、一貫した隔離環境が得られ、デプロイが簡単になり、「自分のマシンでは動く」問題を減らせます。Docker では次のことができます。
  • どこでも同じようにデプロイ – Docker に対応した環境なら同じコンテナを実行できる
  • 依存関係を分離 – システムパッケージとの衝突を避けられる
  • スケールしやすい – 複数コンテナで並列処理できる
  • バージョン管理 – Whisper のバージョンや設定を固定できる
  • デプロイを単純化 – コマンド一つでまとめて起動できる
本ガイドでは、基本的なコンテナから GPU 対応の本番向け構成まで、Docker で Whisper を構築するために必要なことを説明します。

Whisper に Docker を使う理由

コンテナ化の利点

1. 一貫性
  • 開発・ステージング・本番で同じ環境になる
  • 依存関係の衝突が起きにくい
  • 再現可能なビルドになる
2. 移植性
  • Docker が動く環境ならどこでも実行できる
  • サーバー間の移行がしやすい
  • 特定のクラウドに縛られないデプロイができる
3. 隔離
  • ホスト OS を汚しにくい
  • アンインストールはコンテナを消すだけで済む
  • 隔離によるセキュリティ上のメリットがある
4. スケーラビリティ
  • 水平スケールしやすい
  • コンテナ間で負荷分散できる
  • コンテナごとにリソース上限を設定できる
5. DevOps との親和性
  • CI/CD パイプラインに組み込みやすい
  • Kubernetes への展開を想定しやすい
  • クラウド上のコンテナサービスと相性が良い

前提条件

始める前に、次を用意してください。
  • Docker(バージョン 20.10 以降)
  • Docker Compose(複数コンテナ構成の場合、任意)
  • NVIDIA Docker(GPU を使う場合、任意)
  • Docker コマンドの基礎知識

Docker のインストール

macOS:
# Install Docker Desktop from docker.com
# Or using Homebrew
brew install --cask docker
Ubuntu/Debian:
sudo apt update
sudo apt install docker.io docker-compose
sudo systemctl start docker
sudo systemctl enable docker
Windows: docker.com から Docker Desktop をダウンロードしてください。

インストールの確認

docker --version
docker-compose --version

Whisper 用の基本的な Dockerfile

まずは Whisper 向けのシンプルな Dockerfile から始めます。
FROM python:3.10-slim

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    ffmpeg \
    git \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
RUN pip install --no-cache-dir \
    openai-whisper \
    torch \
    torchaudio

# Copy application code (if you have custom scripts)
# COPY . .

# Set default command
CMD ["whisper", "--help"]

イメージのビルド

docker build -t whisper:latest .

基本コンテナの実行

docker run --rm whisper:latest whisper --version

API サーバー付き Dockerfile

本番では API サーバーが欲しくなることが多いです。より実践的な Dockerfile の例です。
FROM python:3.10-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    ffmpeg \
    git \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
RUN pip install --no-cache-dir \
    openai-whisper \
    torch \
    torchaudio \
    fastapi \
    uvicorn \
    python-multipart

# Create directories for audio and output
RUN mkdir -p /app/audio /app/output

# Copy application code
COPY app.py .
COPY requirements.txt .

# Expose API port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Run API server
CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000"]

API サーバーの例(app.py)

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import whisper
import os

app = FastAPI()

# Load Whisper model (can be configured via env)
model_name = os.getenv("WHISPER_MODEL", "base")
model = whisper.load_model(model_name)

@app.get("/health")
def health():
    return {"status": "healthy"}

@app.post("/transcribe")
async def transcribe(file: UploadFile = File(...)):
    # Save uploaded file
    file_path = f"/app/audio/{file.filename}"
    with open(file_path, "wb") as f:
        content = await file.read()
        f.write(content)
    
    # Transcribe
    result = model.transcribe(file_path)
    
    # Clean up
    os.remove(file_path)
    
    return JSONResponse(content={
        "text": result["text"],
        "language": result["language"]
    })

requirements.txt

fastapi==0.104.1
uvicorn[standard]==0.24.0
python-multipart==0.0.6
openai-whisper
torch
torchaudio

Docker Compose の設定

複数サービスをまとめて動かすには Docker Compose を使います。

docker-compose.yml

version: '3.8'

services:
  whisper-api:
    build: .
    container_name: whisper-api
    ports:
      - "8000:8000"
    volumes:
      - ./audio:/app/audio
      - ./output:/app/output
    environment:
      - WHISPER_MODEL=base
      - CUDA_VISIBLE_DEVICES=0
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  # Optional: Redis for queue management
  redis:
    image: redis:7-alpine
    container_name: whisper-redis
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    restart: unless-stopped

volumes:
  redis-data:

Docker Compose で起動する

# Start services
docker-compose up -d

# View logs
docker-compose logs -f whisper-api

# Stop services
docker-compose down

Docker での GPU 対応

GPU 加速には NVIDIA Container Toolkit(旧 NVIDIA Docker)のランタイムが必要です。

NVIDIA Docker のインストール

Ubuntu/Debian:
# Add NVIDIA Docker repository
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
    sudo tee /etc/apt/sources.list.d/nvidia-docker.list

# Install
sudo apt-get update
sudo apt-get install -y nvidia-docker2
sudo systemctl restart docker

GPU 対応 Dockerfile

FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04

WORKDIR /app

# Install Python
RUN apt-get update && apt-get install -y \
    python3.10 \
    python3-pip \
    ffmpeg \
    git \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies with CUDA support
RUN pip3 install --no-cache-dir \
    openai-whisper \
    torch \
    torchaudio \
    --index-url https://download.pytorch.org/whl/cu118

# Install API dependencies
RUN pip3 install --no-cache-dir \
    fastapi \
    uvicorn \
    python-multipart

COPY app.py .
EXPOSE 8000

CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000"]

GPU で実行する

# Using docker run
docker run --gpus all -p 8000:8000 whisper-gpu:latest

# Using docker-compose

GPU 用 docker-compose.yml

version: '3.8'

services:
  whisper-api:
    build: .
    container_name: whisper-api-gpu
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
    ports:
      - "8000:8000"
    volumes:
      - ./audio:/app/audio
      - ./output:/app/output
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]

本番向けに最適化した Dockerfile

マルチステージビルドを使った本番向けの例です。
# Multi-stage build for smaller image
FROM python:3.10-slim as builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    git \
    && rm -rf /var/lib/apt/lists/*

# Install Python packages
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

# Final stage
FROM python:3.10-slim

WORKDIR /app

# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
    ffmpeg \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Copy Python packages from builder
COPY --from=builder /root/.local /root/.local

# Make sure scripts in .local are usable
ENV PATH=/root/.local/bin:$PATH

# Create non-root user for security
RUN useradd -m -u 1000 whisper && \
    mkdir -p /app/audio /app/output && \
    chown -R whisper:whisper /app

USER whisper

# Copy application code
COPY --chown=whisper:whisper app.py .
COPY --chown=whisper:whisper requirements.txt .

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000"]

マルチステージビルドの利点

  • イメージが小さい – 最終イメージには実行時に必要なものだけが入る
  • ビルドが速くなりやすい – ビルド用依存関係を別途キャッシュできる
  • セキュリティが向上 – 非 root ユーザー、攻撃面の縮小

環境変数の設定

環境変数で Docker 構成を切り替えやすくします。

Dockerfile

FROM python:3.10-slim

WORKDIR /app

RUN apt-get update && apt-get install -y \
    ffmpeg \
    git \
    curl \
    && rm -rf /var/lib/apt/lists/*

RUN pip install --no-cache-dir \
    openai-whisper \
    torch \
    torchaudio \
    fastapi \
    uvicorn \
    python-multipart

COPY app.py .

# Environment variables with defaults
ENV WHISPER_MODEL=base
ENV MAX_FILE_SIZE=100MB
ENV LOG_LEVEL=INFO

EXPOSE 8000

CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000"]

環境変数付き docker-compose.yml

version: '3.8'

services:
  whisper-api:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - ./audio:/app/audio
      - ./output:/app/output
    environment:
      - WHISPER_MODEL=small
      - MAX_FILE_SIZE=200MB
      - LOG_LEVEL=DEBUG
      - CUDA_VISIBLE_DEVICES=0
    env_file:
      - .env
    restart: unless-stopped

.env ファイル

WHISPER_MODEL=small
MAX_FILE_SIZE=200MB
LOG_LEVEL=INFO
CUDA_VISIBLE_DEVICES=0

ボリューム管理

適切なボリューム設定でデータを永続化できます。

ボリューム付き docker-compose.yml

version: '3.8'

services:
  whisper-api:
    build: .
    ports:
      - "8000:8000"
    volumes:
      # Bind mount for development
      - ./audio:/app/audio
      - ./output:/app/output
      
      # Named volume for model cache (persists across containers)
      - whisper-models:/root/.cache/whisper
      
      # Config volume
      - ./config:/app/config:ro
    environment:
      - WHISPER_MODEL=base

volumes:
  whisper-models:
    driver: local

メリット

  • モデルキャッシュ – 一度ダウンロードすればコンテナをまたいで再利用できる
  • データの永続化 – コンテナを再起動しても出力が残る
  • 設定の柔軟性 – イメージを作り直さず設定を更新できる

ヘルスチェックと監視

ヘルスチェック付き Dockerfile

FROM python:3.10-slim

WORKDIR /app

RUN apt-get update && apt-get install -y \
    ffmpeg \
    curl \
    && rm -rf /var/lib/apt/lists/*

RUN pip install --no-cache-dir \
    openai-whisper \
    fastapi \
    uvicorn

COPY app.py .

# Health check endpoint
HEALTHCHECK --interval=30s \
            --timeout=10s \
            --start-period=40s \
            --retries=3 \
            CMD curl -f http://localhost:8000/health || exit 1

EXPOSE 8000
CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000"]

ヘルスチェック用エンドポイント

from fastapi import FastAPI
import whisper

app = FastAPI()
model = whisper.load_model("base")

@app.get("/health")
def health():
    try:
        # Quick test transcription
        return {"status": "healthy", "model": "base"}
    except Exception as e:
        return {"status": "unhealthy", "error": str(e)}, 503

よくあるユースケース

ユースケース 1:開発環境

version: '3.8'

services:
  whisper-dev:
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - .:/app
      - /app/__pycache__
    ports:
      - "8000:8000"
    environment:
      - WHISPER_MODEL=tiny
      - DEBUG=true
    command: uvicorn app.py:app --reload --host 0.0.0.0 --port 8000

ユースケース 2:キュー付き本番構成

version: '3.8'

services:
  whisper-api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - REDIS_URL=redis://redis:6379
      - WHISPER_MODEL=small
    depends_on:
      - redis
      - worker

  worker:
    build: .
    command: python worker.py
    environment:
      - REDIS_URL=redis://redis:6379
      - WHISPER_MODEL=small
    volumes:
      - ./audio:/app/audio
    depends_on:
      - redis

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data

volumes:
  redis-data:

ユースケース 3:複数モデル

version: '3.8'

services:
  whisper-fast:
    build: .
    ports:
      - "8001:8000"
    environment:
      - WHISPER_MODEL=tiny
      - PORT=8000

  whisper-balanced:
    build: .
    ports:
      - "8002:8000"
    environment:
      - WHISPER_MODEL=base
      - PORT=8000

  whisper-accurate:
    build: .
    ports:
      - "8003:8000"
    environment:
      - WHISPER_MODEL=large
      - PORT=8000

ベストプラクティス

1. ベースイメージを固定する

悪い例:
FROM python:latest
良い例:
FROM python:3.10-slim

2. レイヤーを減らす

悪い例:
RUN apt-get update
RUN apt-get install -y ffmpeg
RUN apt-get install -y git
良い例:
RUN apt-get update && apt-get install -y \
    ffmpeg \
    git \
    && rm -rf /var/lib/apt/lists/*

3. .dockerignore を使う

.dockerignore を作成します。
__pycache__
*.pyc
*.pyo
*.pyd
.Python
.env
.venv
venv/
.git
.gitignore
README.md
*.md
.DS_Store

4. リソース上限を設定する

services:
  whisper-api:
    build: .
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 4G
        reservations:
          cpus: '1'
          memory: 2G

5. ヘルスチェックを入れる

本番コンテナには必ずヘルスチェックを入れましょう。
HEALTHCHECK --interval=30s --timeout=10s CMD curl -f http://localhost:8000/health || exit 1

6. 非 root ユーザーで動かす

RUN useradd -m -u 1000 whisper
USER whisper

7. モデルをキャッシュする

ダウンロードしたモデルはボリュームでキャッシュします。
volumes:
  - whisper-models:/root/.cache/whisper

よくあるトラブルと対処

問題 1:コンテナがすぐ終了する

症状: 起動した直後に終了する
対処:
# Check logs
docker logs <container-id>

# Run interactively to debug
docker run -it whisper:latest /bin/bash

問題 2:GPU が使えない

症状: コンテナ内で GPU が認識されない
対処:
# Verify NVIDIA Docker
docker run --rm --gpus all nvidia/cuda:11.8.0-base-ubuntu22.04 nvidia-smi

# Check runtime
docker info | grep -i runtime

問題 3:メモリ不足

症状: コンテナがメモリ不足になる
対処:
# Increase memory limit
deploy:
  resources:
    limits:
      memory: 8G

問題 4:モデルのダウンロードが遅い/毎回かかる

症状: 起動のたびにモデルを取り直している
対処:
# Use volume for model cache
volumes:
  - whisper-models:/root/.cache/whisper

問題 5:Permission denied

症状: ボリュームに書き込めない
対処:
# Fix permissions in Dockerfile
RUN chown -R whisper:whisper /app

パフォーマンス最適化

1. モデルのプリロード

ビルド時にモデルを取得します。
# Download model during build
RUN python -c "import whisper; whisper.load_model('base')"

2. faster-whisper を使う

高速化には faster-whisper が有効です。
RUN pip install --no-cache-dir faster-whisper

3. マルチスレッド/ワーカー

ワーカー数を設定します。
CMD ["uvicorn", "app.py:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]

4. リソース割り当て

負荷に合わせて CPU・メモリを割り当てます。
deploy:
  resources:
    limits:
      cpus: '4'
      memory: 8G

セキュリティの考慮

1. 公式ベースイメージを使う

FROM python:3.10-slim  # Official Python image

2. 脆弱性スキャン

docker scan whisper:latest

3. イメージを更新する

ベースイメージと依存関係を定期的に更新します。
FROM python:3.10-slim  # Use latest patch version
RUN pip install --upgrade pip

4. ネットワークを制限する

services:
  whisper-api:
    build: .
    networks:
      - internal
    # No external ports if accessed via reverse proxy

まとめ

Whisper を Docker 化すると、音声テキスト化を堅牢かつスケールしやすく運用できます。押さえるべき点は次のとおりです。
  1. シンプルに始める – まずは基本的な Dockerfile から
  2. Docker Compose を活用する – 複数サービスをまとめて管理する
  3. GPU を有効にする – 本番のスループットが必要なら
  4. ベストプラクティスを守る – セキュリティ・最適化・監視
  5. 本番前に十分テストする
Docker を適切に組み合わせれば、ローカル開発からクラウド本番まで、環境を問わず一貫して Whisper をデプロイできます。

次のステップ

  • 最初のコンテナをビルドする – 基本の Dockerfile から
  • GPU 対応を追加する – NVIDIA GPU がある場合
  • Docker Compose を整える – アプリ全体のスタック用
  • クラウドにデプロイする – ECS、GKE、AKS などのコンテナサービス
その他のデプロイ戦略は、Whisper Cloud DeploymentWhisper API vs Local Deployment のガイドも参照してください。

今すぐ無料で試す

当社のAI音声・オーディオ/ビデオサービスを今すぐお試しください。高精度な音声文字起こし、多言語翻訳、話者分離に対応するだけでなく、自動動画字幕生成、音声・映像コンテンツのインテリジェント編集、音声と映像を組み合わせた同期解析も実現します。会議記録、ショート動画制作、ポッドキャスト制作など、あらゆるシーンをこれ一つでカバーできます。今すぐ無料トライアルを始めましょう!