2
4

More than 1 year has passed since last update.

[入門]Dockerfile からpython環境構築

Last updated at Posted at 2022-10-16

背景

docker の練習として、docker container 内に python の環境構築をしてみます。

やること

  • python の dockerfile 作成
    • dockerfile の作成
      • ubuntu 22.04
      • python 3.10系
  • dockerfile から dockerimage の build
  • docker image から コンテナの起動
  • コンテナに入り python の起動

Dockerfile とはなんぞや

  • dockerimage を作るためのファイル
  • docker build コマンドでドッカーファイルを build すると dockerimage が生成できる

Dockerfile

FROM ubuntu:22.04

RUN apt update
RUN apt install -y python3.10
RUN apt install -y python3-pip

Dockerfile の build

build

docker build -t tagname .
  • -t はタグの名前
  • . は Dockerfile の配置されているパスで、カレントディレクトを表す.

build 結果

  • docker imagesコマンドで作成結果を確認
  • tagname という名前のimgage が出来上がっていることを確認できる
REPOSITORY               TAG       IMAGE ID       CREATED          SIZE
tagname                  latest    acc321b28688   38 minutes ago   464MB

Docker image とはなんぞや

  • 一言でいうと、docker image: コンテナの設計図
  • 上で作った image は ubuntu22.04 に python3.10, pip をインストールするというコンテナの設計図

image からコンテナを作ってみる

  • docker run コマンドで image からコンテナを作ることができる
    • run は pull create start コマンドをラップしたもの。ただし、pull に関してはimageがない場合に行われる模様.
docker run --name container_name -itd tagname

コンテナの作成結果

docker ps コマンドでコンテナの状況が確認できる.

CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS          PORTS     NAMES
36c6f70a68ef   tagname   "bash"    3 seconds ago    Up 2 seconds              container_name

作ったコンテナに入ってみる

下記コマンドで入れる.

docker exec -it container_name /bin/bash
  • exec: 実行中のコンテナ内でプログラムを実行する.
  • -i: コンテナ内でキーボードによる操作を可能にする
  • -t: コンテナ内で特殊キーを使用可能にする
  • /bin/bash: bash を起動する

結果

  • root@CONTAINER ID でbashが起動できている.
root@36c6f70a68ef:/# 
  • python3 のバージョンを確認してみる
    • dockerfile で指定した3.10系がインストールされていることが確認できた.
root@36c6f70a68ef:/# python3 -V
Python 3.10.6

次回

docker compose を使って、楽にコンテナの生成実施

2
4
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
2
4