Python アプリケーションのコンテナー化
前提条件
- Docker Desktop の最新版をインストールしていること。
- Git クライアント が利用可能であること。 本節の利用例ではコマンドラインベースの Git クライアントを用いていきますが、別のクライアントを用いてもかまいません。
概要
本節では Python アプリケーションをコンテナー化して実行する手順を示していきます。
サンプルアプリケーションの入手
サンプルアプリケーションでは、人気の FastAPI フレームワークを利用しています。
本ガイドにおいて利用するサンプルアプリケーションをクローンします。 端末画面を開いて、作業を行うディレクトリに移動します。 そして以下のコマンドを実行してリポジトリをクローンします。
$ git clone https://github.com/estebanx64/python-docker-example && cd python-docker-example
Docker アセットの初期化
アプリケーションの入手はできました。 次はアプリケーションのコンテナー化に必要となる Docker アセットを生成します。 Docker Desktop にはビルトインの Docker Init 機能があるので、効率的に作業を進められます。 あるいは手動でアセットを生成することもできます。
端末画面内の python-docker-example ディレクトリにおいて docker init コマンドを実行します。
docker init はデフォルトの設定をいくつか行いますが、アプリケーション内容についていくつか質問が行われるので、それに答えます。
たとえばこのアプリケーション実行のために FastAPI を利用することなどです。
以下の利用例において docker init の質問への答えを示しているので、これを参考に同様の入力を行ってください。
Before editing your Dockerfile, you need to choose a base image. You can use the Python Docker Official Image, or a Docker Hardened Image (DHI).
Docker Hardened Images (DHIs) are minimal, secure, and production-ready base images maintained by Docker. They help reduce vulnerabilities and simplify compliance. For more details, see Docker Hardened Images.
$ docker init
Welcome to the Docker Init CLI!
This utility will walk you through creating the following files with sensible defaults for your project:
- .dockerignore
- Dockerfile
- compose.yaml
- README.Docker.md
Let's get started!
? What application platform does your project use? Python
? What version of Python do you want to use? 3.12
? What port do you want your app to listen on? 8000
? What is the command to run your app? python3 -m uvicorn app:app --host=0.0.0.0 --port=8000
.gitignore という名前のファイルを生成して、その内容を以下のようにします。
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# ディストリビューション / パッケージ
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# ユニットテスト / カバレッジリポート
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# 環境
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/If you don't have Docker Desktop installed or prefer creating the assets manually, you can create the following files in your project directory.
Create a file named Dockerfile with the following contents.
# syntax=docker/dockerfile:1
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/
# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7
# This Dockerfile uses Docker Hardened Images (DHI) for enhanced security.
# For more information, see https://docs.docker.com/dhi/
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim
# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1
# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1
WORKDIR /app
# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser
# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=bind,source=requirements.txt,target=requirements.txt \
python -m pip install -r requirements.txt
# Switch to the non-privileged user to run the application.
USER appuser
# Copy the source code into the container.
COPY . .
# Expose the port that the application listens on.
EXPOSE 8000
# Run the application.
CMD ["python3", "-m", "uvicorn", "app:app", "--host=0.0.0.0", "--port=8000"]Create a file named compose.yaml with the following contents.
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/
# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
server:
build:
context: .
ports:
- 8000:8000Create a file named .dockerignore with the following contents.
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.com/go/build-context-dockerignore/
**/.DS_Store
**/__pycache__
**/.venv
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose.y*ml
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.mdCreate a file named .gitignore with the following contents.
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# ディストリビューション / パッケージ
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# ユニットテスト / カバレッジリポート
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# 環境
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/Docker Hardened Images (DHIs) are available for Python in the Docker Hardened Images catalog. Docker Hardened Images are freely available to everyone with no subscription required. You can pull and use them like any other Docker image after signing in to the DHI registry. For more information, see the DHI quickstart guide.
Sign in to the DHI registry:
$ docker login dhi.ioPull the Python DHI (check the catalog for available versions):
$ docker pull dhi.io/python:3.12.12-debian13-fips-dev
Create a file named Dockerfile with the following contents.
# syntax=docker/dockerfile:1
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/
# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7
# This Dockerfile uses Docker Hardened Images (DHI) for enhanced security.
# For more information, see https://docs.docker.com/dhi/
ARG PYTHON_VERSION=3.12.12-debian13-fips-dev
FROM dhi.io/python:${PYTHON_VERSION}
# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1
# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1
#Add dependencies for adduser
RUN apt update -y && apt install adduser -y
WORKDIR /app
# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser
# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=bind,source=requirements.txt,target=requirements.txt \
python -m pip install -r requirements.txt
# Switch to the non-privileged user to run the application.
USER appuser
# Copy the source code into the container.
COPY . .
# Expose the port that the application listens on.
EXPOSE 8000
# Run the application.
CMD ["python3", "-m", "uvicorn", "app:app", "--host=0.0.0.0", "--port=8000"]Create a file named compose.yaml with the following contents.
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/
# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
server:
build:
context: .
ports:
- 8000:8000Create a file named .dockerignore with the following contents.
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.com/go/build-context-dockerignore/
**/.DS_Store
**/__pycache__
**/.venv
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose.y*ml
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.mdCreate a file named .gitignore with the following contents.
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/上により python-docker-example ディレクトリ内は、最低でも以下の構成となるはずです。
├── python-docker-example/
│ ├── app.py
│ ├── requirements.txt
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── Dockerfile
│ └── README.md各ファイルについての詳細は以下を参照してください。
アプリケーションの実行
端末画面内の python-docker-example ディレクトリから以下のコマンドを実行します。
$ docker compose up --build
ブラウザーを開いて http://localhost:8000 にアクセスし、アプリケーションを確認します。 シンプルな FastAPI アプリケーションが表示されたはずです。
端末画面から ctrl+c を押下してアプリケーションを停止します。
バックグラウンドでのアプリケーション実行
アプリケーションは端末から切り離して実行することができます。
それには -d オプションをつけます。
端末画面内の python-docker-example ディレクトリから以下のコマンドを実行します。
$ docker compose up --build -d
ブラウザーを開いて http://localhost:8000 にアクセスし、アプリケーションを確認します。
OpenAPI ドキュメントを確認する場合は http://localhost:8000/docs にアクセスします。
シンプルな FastAPI アプリケーションが表示されたはずです。
端末画面から以下のコマンドを実行してアプリケーションを停止します。
$ docker compose down
Compose コマンドの詳細は Compose CLI リファレンス を参照してください。
まとめ
本節では Docker を使って Python アプリケーションをコンテナー化して実行する方法について学びました。
関連情報
次のステップ
次の節では、Docker コンテナーを使ったローカル開発環境の構築方法について見ていきます。