Dockerfile CMDの角括弧([ ]
)の有無によって挙動が違った。
角括弧がある: PID 1のプロセスはCMDで指定したプログラムのプロセス
角括弧がない: PID 1のプロセスはshell
仕様はここに書いてある。
角括弧有り
Dockerfile
FROM ubuntu:16.04
CMD ["tail", "-f", "/dev/null"]
プロセスの様子
$ docker exec -it with_brackets ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.2 0.0 4416 748 ? Ss 09:35 0:00 tail -f /dev/null
root 7 0.0 0.1 34428 2680 pts/0 Rs+ 09:35 0:00 ps aux
PID1
CMDで指定したプログラムのプロセス
角括弧無し
Dockerfile
FROM ubuntu:16.04
CMD tail -f /dev/null
プロセスの様子
$ docker exec -it without_brackets ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.3 0.0 4512 780 ? Ss 09:37 0:00 /bin/sh -c tail
root 5 0.0 0.0 4416 784 ? S 09:37 0:00 tail -f /dev/nu
root 6 0.0 0.1 34428 2728 pts/0 Rs+ 09:37 0:00 ps aux
PID1
shellのプロセス
コンテナ起動時にコマンドをした場合
Dockerfile
角括弧有り、角括弧無し両方で試した
プロセスの様子
$ docker run --name my_container -d my_image sleep 1000
$ docker exec -it my_container ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.2 0.0 4384 744 ? Ss 03:19 0:00 sleep 1000
root 7 0.0 0.1 34428 2816 pts/0 Rs+ 03:19 0:00 ps aux
PID1
起動時に指定したプログラムのプロセス
どういう時に違いが出るか
docker stop
は、PID 1のプロセスに対してSIGTERM
を送る。その後10秒以内にプロセスが死なない場合は、SIGKILL
を送る。
実行したいプログラムでSIGTERM
をハンドリングしたい場合、角括弧無しでCMD実行すると、SIGTERM
が正しくハンドリングできない事がある。
ref: https://www.ctl.io/developers/blog/post/gracefully-stopping-docker-containers/