Dockerを利用して Python の環境構築
以下の操作は macOS にて作業しており、Docker や tree コマンドがインストールされていることが前提です。
作業ディレクトを作成
$ mkdir docker-python $ cd docker-python
ファイル作成
Dockerfile の作成。
FROM python:3
USER root
RUN apt-get update
RUN apt-get -y install locales && \
localedef -f UTF-8 -i ja_JP ja_JP.UTF-8
ENV LANG ja_JP.UTF-8
ENV LANGUAGE ja_JP:ja
ENV LC_ALL ja_JP.UTF-8
ENV TZ JST-9
ENV TERM xterm
RUN apt-get install -y vim less
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN python -m pip install jupyterlab
docker-compose.yml の作成。
version: '3'
services:
python3:
restart: always
build: .
container_name: 'python3'
working_dir: '/root/'
tty: true
volumes:
- ./opt:/root/opt
opt/hello.py の作成。
# hello.py
def main():
message = 'hello, world!'
print(message)
if __name__ == '__main__':
main()
実行
Dockerイメージの作成、コンテナのビルド、そしてコンテナの起動/接続/終了。
$ tree . ├── Dockerfile ├── docker-compose.yml └── opt └── hello.py 1 directory, 3 files $ docker-compose up -d --build $ docker-compose exec python3 bash root@python3$ python opt/hello.py hello, world! root@python3$ python >>> import math >>> def check_prime_num(number): ... sqrt_number = math.sqrt(number) ... number_float = float(number) ... for i in range(2, int(sqrt_number)+1): ... if (number_float / i).is_integer(): ... return False ... return True ... >>> check_prime_num(12) False >>> check_prime_num(3) True >>> ^D root@python3$ exit $ docker-compose down
最後に
一連の作業を簡単に行えるように、シェルスクリプトやMakefileを作っておくと良いかもしれません。