LoginSignup
1
0

More than 1 year has passed since last update.

DockerでPython実行環境を爆速で作ってみる

Last updated at Posted at 2022-12-04

概要

「Pythonのライブラリを使って色々実験したい!でもローカル環境汚したくないしなー」と思うことがあったので、DockerによるPython実行環境の型を作ってみました

ディレクトリツリー

.
├── app
│   └── main.py
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── .env

appディレクトリの中に好きなだけpythonファイルを入れてやるというイメージです

使いたいライブラリをrequirements.txtに記述

requirements.txt
pandas
numpy
tensorflow
...

Dockerfile

FROM python:3.9

COPY requirements.txt .
COPY ./app/ ./app/

RUN pip install --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

WORKDIR /app

requirements.txtに記述したライブラリをまとめてpipでインストールしてくれます

docker-compose.yml

docker-compose.yml
version: '3'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: python-sandbox
    working_dir: '/app'
    volumes:
        - ./app:/app
    env_file: .env

環境変数を使う場合は、env_fileで.envを読み込ませてあげます。
コンテナ名はお好きなものにしてください。(今回はpython-sandboxという名前にしました)

コンテナを構築

コンテナ・イメージを作成
docker-compose up -d

コンテナ内に入る
docker-compose exec python-sandbox bash

コンテナ内に入れたら作成したpythonファイルをすぐに実行することができます。

参考・関連記事

1
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
1
0