Docker ( 6 ) ~ Dockerfile ~

November 02, 2017

Dockerfile とは

作業履歴を残したイメージ生成を実現したり、同じイメージを異なる Docker 環境で繰り返し生成したい場合は Dockerfile という設定ファイルを使ってイメージを生成する。

既存イメージに基づくイメージ生成

$ cat Dockerfile
FROM ubuntu
RUN apt-get -y update
RUN apt-get -y upgrade

$ sudo docker build -t myubuntu test
Sending build context to Docker daemon 3.072 kB
Step 1/3 : FROM ubuntu
latest: Pulling from library/ubuntu
Digest: sha256:506e2d5852de1d7c90d538c5332bd3cc33b9cbd26f6ca653875899c505c82687
Status: Downloaded newer image for ubuntu:latest
 ---> 747cb2d60bbe
Step 2/3 : RUN apt-get -y update
 ---> Running in 5f81a5fedbdd
Get:1 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Get:2 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
...

Step 3/3 : RUN apt-get -y upgrade
 ---> Running in e9c3ff8467a4
Reading package lists...
Building dependency tree...
Reading state information...
Calculating upgrade...
The following packages will be upgraded:
  libsystemd0 libudev1 systemd systemd-sysv
4 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 3899 kB of archives.
After this operation, 4096 B of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 libsystemd0 amd64 229-4ubuntu21 [205 kB]
Get:2 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 systemd amd64 229-4ubuntu21 [3628 kB]
Get:3 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 systemd-sysv amd64 229-4ubuntu21 [12.1 kB]
Get:4 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 libudev1 amd64 229-4ubuntu21 [54.6 kB]
...

date コマンドを実行するイメージをゼロから作成

まず、date コマンドを実行するために必要なライブラリを調べる。

$ which date
/bin/date
$ ldd /bin/date
	linux-vdso.so.1 =>  (0x00007ffff7ffb000)
	libc.so.6 => /lib64/libc.so.6 (0x00007f8d5cd24000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f8d5d0e8000)

date コマンド及びライブラリファイルを Dockerfile が配置されているディレクトリにコピーし、Dockerfile から、イメージを作成し、コンテナを作成。

$ cat ~/FromScratch/Dockerfile
FROM scratch
COPY date /bin/
COPY libc.so.6 /lib64/
COPY ld-linux-x86-64.so.2 /lib64/
ENTRYPOINT ["/bin/date"]

$ sudo docker build -t mydate FromScratch/
Sending build context to Docker daemon 2.351 MB
Step 1/5 : FROM scratch
 ---> 
Step 2/5 : COPY date /bin/
 ---> e498f25db2ab
Removing intermediate container e7959c95b78f
Step 3/5 : COPY libc.so.6 /lib64/
 ---> a7537e4ea924
Removing intermediate container 3157482ef0ec
Step 4/5 : COPY ld-linux-x86-64.so.2 /lib64/
 ---> dedbdd6ea406
Removing intermediate container 17d3fe6b9489
Step 5/5 : ENTRYPOINT /bin/date
 ---> Running in 182c649b3037
 ---> 38f879cdff6f
Removing intermediate container 182c649b3037
Successfully built 38f879cdff6f

作成したイメージを基にコンテナを作成。

$ sudo docker run mydate
Wed Nov  1 18:55:43 UTC 2017

 © 2023, Dealing with Ambiguity