0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ハッカソン個人備忘録㉒:FastAPI × Docker で pip が使えないときのトラブルシューティングまとめ

Posted at

はじめに

FastAPIをDockerで構築している際、python:3.11-slim イメージを使っていたにも関わらず、コンテナ内で pip コマンドが使えないという事態に遭遇することがあります。以下では、その原因と対処法について解説します。

※本記事はあくまで個人の備忘録として記録しています。

現象

bash-5.1# pip --version
bash: pip: command not found

python:3.11-slim イメージでは通常 pip はインストールされているはずですが、バージョンやタイミングによっては含まれていないことがあります。

対処法:pip を手動でインストールする

Dockerfileに以下のような記述を追加することで、pip を明示的にインストールできます。

FROM python:3.11-slim

WORKDIR /app

# pipをインストールするために必要なパッケージを追加
RUN apt-get update && \
    apt-get install -y curl && \
    curl -sS https://bootstrap.pypa.io/get-pip.py | python3 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# requirements.txtのコピーとインストール
COPY app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app/ .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

解説

  • curl を使って get-pip.py をダウンロードし、Pythonで実行することで pip をインストール。
  • apt-get cleanrm -rf /var/lib/apt/lists/* により不要なキャッシュを削除し、Dockerイメージを軽量に保ちます。

まとめ

python:3.11-slim を使っていても pip が使えない場合があるため、上記の方法で手動インストールを行うのが安全です。

FastAPIなどのアプリケーションをDocker上で構築する際は、pip の有無も確認しておくとトラブルを防げると思いますので、試してみてください!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?