LoginSignup
22
20

More than 3 years have passed since last update.

Ubuntu+Python3(任意のバージョン)の実行環境を構築するDockerfile

Posted at

この記事は

他人と同じ実行環境を構築するために、Ubuntuイメージをベースとして、任意バージョンのPython3環境を構築したかったので、勉強も兼ねていろいろ試してみた。前も同じようなことをやりましたが、こちらの内容の方が汎用性が高そうなのでまとめます。
同じような状況の方の参考になれば幸いです。もっと良い方法があればぜひ教えていただきたいです。
Python3の実行環境をDockerで立ち上げるだけなら、公式のPythonイメージを使用するのが簡単だと思います。

実行環境

Docker version 20.10.5

Dokerfile

以下のDockerfileからイメージをbuildする。今回はUbuntu20.04のイメージを使用し、Python3.9.5をインストールする。このあたりは、適宜自分の構築したい環境にあわせて変更してください。

Dockerfile
FROM ubuntu:20.04

# 必要そうなものをinstall
RUN apt-get update && apt-get install -y --no-install-recommends wget build-essential libreadline-dev \ 
libncursesw5-dev libssl-dev libsqlite3-dev libgdbm-dev libbz2-dev liblzma-dev zlib1g-dev uuid-dev libffi-dev libdb-dev

#任意バージョンのpython install
RUN wget --no-check-certificate https://www.python.org/ftp/python/3.9.5/Python-3.9.5.tgz \
&& tar -xf Python-3.9.5.tgz \
&& cd Python-3.9.5 \
&& ./configure --enable-optimizations\
&& make \
&& make install

#サイズ削減のため不要なものは削除
RUN apt-get autoremove -y

#必要なpythonパッケージをpipでインストール
#RUN pip3 install --upgrade pip && pip3 install --no-cache-dir jupyterlab

#requirements.txtなら以下のように
#RUN pip3 install -r ./requirements.txt

上のDockerfileと同じディレクトリで

docker build .

でbuildする。

簡単な説明

FROM ubuntu:20.04でUbuntuのベースイメージを引っ張ってくる。
そのあとは必要なパッケージ群をintall、ここはあまり自信がない、余計なものが多いかもしれないです。
Python3のインストール自体はapt-get install python3 pipでインストールが簡単だけど、任意のバージョンを扱いづらかったので、Pythonの公式サイトから.tgzをダウンロードしてきて、それを展開してインストールする。
あとは、自分が必要なパッケージをpipでinstallなどして使ってください。

参考

https://qiita.com/yniji/items/8e392103a6f2a4152606
https://docs.python.org/ja/3/using/unix.html

22
20
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
22
20