ᕕ( ᐛ )ᕗ Jimyag's Blog

在 pod 中操作宿主机

要在 pod 中操作宿主机,有以下几种方式:

  1. 在 pod 中使用 ssh 连接到物理机,然后使用物理机的命令
  2. 物理机上有 agent,pod 调用 agent 执行命令
  3. 使用 特权 pod 操作宿主机

下面只介绍第三种方式。

apiVersion: v1
kind: Pod
metadata:
  name: host-shell
spec:
  containers:
  - command:
    - nsenter
    - --target
    - "1"
    - --mount
    - --uts
    - --ipc
    - --net
    - --pid
    - --
    - bash
    - -c
    - cd ~ && exec bash -l
    image: busybox:latest
    name: host-shell
    securityContext:
      privileged: true
    stdin: true
    stdinOnce: true
    tty: true
  hostIPC: true
  hostNetwork: true
  hostPID: true
  restartPolicy: Never
nsenter --target 1 --mount --uts --ipc --net --pid -- bash -c 'cd ~ && exec bash -l'

进入宿主机所有 namespace,然后执行一个交互式 bash 终端。

参数 含义
nsenter 工具,用于进入指定进程的命名空间
–target 1 进入 PID 为 1 的进程(即宿主机的 init 或 systemd)
–mount 指定要进入的命名空间类型(共享所有主机命名空间)
之后是你要执行的命令
bash -c ‘cd ~ && exec bash -l’ 在主机命名空间中打开一个 Bash shell
stdin: true
stdinOnce: true
tty: true

这些让 Pod 可以交互:

#K8s