3

以下两种情况下授予容器的权限有什么区别

  1. sudo docker run -d --privileged --pid=host alpine:3.8 tail -f /dev/null
  2. 使用 Kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: nsenter-alpine
spec:
  hostPID: true
  containers:
    - name: nsenter-alpine
      image: alpine:3.8
      resources:
        limits:
          cpu: "500m"
          memory: "200Mi"
        requests:
          cpu: "100m"
          memory: "100Mi"
      command: ["tail"]
      args: ["-f", "/dev/null"]
      securityContext:
        privilege: true

在情况 1)

/ # ps -ef | wc -l
604

在情况 2)

[root@localhost /]# ps -ef | wc -l
266

显然,当特权容器直接使用 docker 实例化时,它能够看到主机的进程,但是当它使用 kubernetes 启动时,它只能看到少数进程。背后的原因是什么?

4

1 回答 1

3

编辑:

我看到你有--pid=host指挥docker run权和hostPID: truekubernetes pod 规范。在这种情况下,如果容器在同一主机上运行,​​则两个数字应该相似。检查容器是否在同一主机上运行。Kubernetes 可能已将 pod 调度到不同的节点。


上一个答案

sudo docker run -d --privileged --pid=host alpine:3.8 tail -f /dev/null

在上面的命令中,您使用--pid=host的是在主机 pid 命名空间中运行容器的参数。因此,您可以查看主机上的所有进程。您可以使用hostPIDkubernetes 的 pod 规范中的选项来实现相同的目的。


以特权模式运行容器意味着容器中的进程本质上等同于主机上的 root。默认情况下,不允许容器访问主机上的任何设备,但“特权”容器可以访问主机上的所有设备。

$ kubectl exec -it no-privilege ls /dev
core             null             stderr           urandom
fd               ptmx             stdin            zero
full             pts              stdout
fuse             random           termination-log
mqueue           shm              tty
$ kubectl exec -it privileged ls /dev
autofs              snd                 tty46
bsg                 sr0                 tty47
btrfs-control       stderr              tty48
core                stdin               tty49
cpu                 stdout              tty5
cpu_dma_latency     termination-log     tty50
fd                  tty                 tty51
full                tty0                tty52
fuse                tty1                tty53
hpet                tty10               tty54
hwrng               tty11               tty55
...

容器仍然在它自己的 pid 命名空间、ipc 命名空间和网络命名空间等中运行。因此,即使在特权模式下运行,您也不会看到容器内的主机进程。如果要在主机命名空间中运行,可以使用Kubernetes 中pod spechostPID的, hostNetwork,hostIPC字段。

于 2020-01-27T17:14:19.827 回答