はじめに

Dockerコンテナ側からホストのプロセスを確認したいということがあったのでメモ書き。

環境

1
2
3
Windows 11 Professional
WSL2 Ubuntu 24.04 LTS
Docker Desktop 4.33.1 (161083)

構築

Dockerfile

1
2
3
4
5
6
FROM alpine:latest

# Install ps command
RUN apk add --no-cache procps

CMD [ "sh" ]

プロセスを確認するのみなので、ベースイメージはalpineを選定した。
psコマンドを使えるようにするには、procpsパッケージを入れる必要があるため入れる。

compose.yml

1
2
3
4
5
6
7
services:
  monitor:
    build:
      context: .
    stdin_open: true
    tty: true
    pid: host

stdin_open: true, tty: true については、シェルを起動させるために必要な設定。
大事なのはpid: host、これでホスト側とPID名前空間を共有できるようだ。

試す

pid:host ありの場合

compose.yml, Dockerfileを同じ階層に配置し、下記コマンドを実行する。

1
docker compose up -d

コンテナが起動したら、monitorコンテナに入る。

1
docker compose exec monitor sh

コンテナで ps aux を実行する。

1
ps aux

PID:1initプロセスが確認できる。
WSL2 の プロセスが見えている。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0 1258764 29912 pts/0   Sl+  13:46   0:00 /init
root        18  0.2  0.3 1333416 112064 pts/0  Sl+  13:46   0:04 /init services
root        30  0.0  0.0   1644    80 pts/0    S+   13:46   0:00 /bin/sh /usr/bin/rungetty.sh
root        31  0.0  0.0   1612   904 ?        Ss   13:46   0:00 /bin/login -f -- root
root        37  0.0  0.0   1724  1128 ?        S+   13:46   0:00 -sh
root        42  0.0  0.0 706620 11084 pts/0    Sl+  13:46   0:00 /usr/bin/devenv-server -socket /run/guest-services/devenv-volumes.sock
root        62  0.0  0.0 1383784 20720 pts/0   Sl+  13:46   0:00 /usr/bin/runc run --preserve-fds=3 01-docker
root        77  0.0  0.0   1008     4 ?        Ss   13:46   0:00 /usr/libexec/docker/docker-init /usr/bin/entrypoint.sh
root        83  0.0  0.0   3924  3076 ?        S    13:46   0:00 /bin/sh /usr/bin/entrypoint.sh
root        87  0.1  0.1 1262584 37108 ?       Sl   13:46   0:02 /usr/bin/lifecycle-server
root        99  0.6  0.1 2835376 58540 ?       Sl   13:46   0:09 /usr/local/bin/containerd --config /etc/containerd/containerd.toml
100        121  0.0  0.0  16076  2444 ?        Ss   13:46   0:00 /sbin/rpcbind -w
.
.
.

pid:host なしの場合

同じようにコンテナをビルドして ps auxをコンテナ内で実行する。

1
ps aux
1
2
3
4
5
/ # ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0   1724   968 pts/0    Ss+  14:14   0:00 sh
root         7  0.0  0.0   1696  1040 pts/1    Ss   14:14   0:00 sh
root        13  0.0  0.0   2508  1712 pts/1    R+   14:14   0:00 ps aux

こちらでは、PID名前空間を共有していないのでコンテナ内のプロセスしか見られない。

参考

おわりに

コンテナ側とホスト側のプロセスを共有する形になるので、コンテナ側でホストのプロセスをkillすることもできる。
コンテナセキュリティ的にどういうところに気を付けたほうが良いのかとかも考えておきたい。