0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dockerfileを使おう

Dockerfile は一言で言うと、

実行環境の作り方をコードで書いたレシピ

です。

  • Dockerfile とは何か
  • 基本構文と役割
  • 最小構成から実用例まで

について解説します。

Dockerfile とは?

DockerfileはDockerイメージを作成するための設計図です。

  • OS
  • 言語ランタイム
  • ライブラリ
  • 起動コマンド
    をすべて宣言的に記述します。

Dockerfile の最小構成

FROM ubuntu:24.04

CMD ["echo", "Hello Dockerfile"]

ビルド

docker build -t hello .

実行

docker run hello

Dockerの基本命令

FROM(必須)

FROM python:3.12-slim
  • ベースとなる OS / 環境
  • 最初に必ず書く

WORKDIR

WORKDIR /app
  • 作業ディレクトリを指定
  • cd の代わり

COPY / ADD

COPY main.py /app/
  • ホスト → コンテナへコピー
  • 基本は COPY 推奨

ADDはCOPYの他、URLがら直接ダウンロード、圧縮ファイルの自動展開などの機能を兼ね備えたものになっています。

RUN

RUN apt update && apt install -y curl
  • ビルド時に実行
  • パッケージインストール等

CMD / ENTRYPOINT

CMD ["python", "main.py"]
  • コンテナ起動時に実行
  • CMD は上書き可能
  • ENTRYPOINT は強制実行

Python アプリの Dockerfile 例

FROM python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
CMD ["python", "app.py"]

追記

軽量なイメージを作るには

  • slim / alpine を使う
  • 不要なファイルをコピーしない
  • RUN をまとめる(不要なレイヤーの作成を避けるため)
RUN apt update \
 && apt install -y git \
 && apt clean \
 && rm -rf /var/lib/apt/lists/*
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?