Kubernetes 獲取正在運行容器的Shell

2022-05-27 13:49 更新

在開始之前

你必須擁有一個 Kubernetes 的集群,同時你的 Kubernetes 集群必須帶有 kubectl 命令行工具。 建議在至少有兩個節(jié)點的集群上運行本教程,且這些節(jié)點不作為控制平面主機。 如果你還沒有集群,你可以通過 Minikube 構(gòu)建一個你自己的集群,或者你可以使用下面任意一個 Kubernetes 工具構(gòu)建:

要檢查版本,請輸入 ??kubectl version??。

獲取容器的 Shell 

在本練習中,你將創(chuàng)建包含一個容器的 Pod。容器運行 nginx 鏡像。下面是 Pod 的配置文件:

apiVersion: v1
kind: Pod
metadata:
  name: shell-demo
spec:
  volumes:
  - name: shared-data
    emptyDir: {}
  containers:
  - name: nginx
    image: nginx
    volumeMounts:
    - name: shared-data
      mountPath: /usr/share/nginx/html
  hostNetwork: true
  dnsPolicy: Default

創(chuàng)建 Pod:

kubectl create -f https://k8s.io/examples/application/shell-demo.yaml

檢查容器是否運行正常:

kubectl get pod shell-demo

獲取正在運行容器的 Shell:

kubectl exec -it shell-demo -- /bin/bash
Note:
雙破折號 "--" 用于將要傳遞給命令的參數(shù)與 kubectl 的參數(shù)分開。

在 shell 中,打印根目錄:

root@shell-demo:/# ls /

在 shell 中,實驗其他命令。下面是一些示例:

root@shell-demo:/# ls /
root@shell-demo:/# cat /proc/mounts
root@shell-demo:/# cat /proc/1/maps
root@shell-demo:/# apt-get update
root@shell-demo:/# apt-get install -y tcpdump
root@shell-demo:/# tcpdump
root@shell-demo:/# apt-get install -y lsof
root@shell-demo:/# lsof
root@shell-demo:/# apt-get install -y procps
root@shell-demo:/# ps aux
root@shell-demo:/# ps aux | grep nginx

編寫 nginx 的根頁面

再看一下 Pod 的配置文件。該 Pod 有個 ?emptyDir ?卷,容器將該卷掛載到了 ?/usr/share/nginx/html?。

在 shell 中,在 ?/usr/share/nginx/html? 目錄創(chuàng)建一個 ?index.html? 文件:

root@shell-demo:/# echo Hello shell demo > /usr/share/nginx/html/index.html

在 shell 中,向 nginx 服務器發(fā)送 GET 請求:

root@shell-demo:/# apt-get update
root@shell-demo:/# apt-get install curl
root@shell-demo:/# curl localhost

輸出結(jié)果顯示了你在 ?index.html? 中寫入的文本。

Hello shell demo

當用完 shell 后,輸入 ?exit ?退出。

在容器中運行單個命令

在普通的命令窗口(而不是 shell)中,打印環(huán)境運行容器中的變量:

kubectl exec shell-demo env

實驗運行其他命令。下面是一些示例:

kubectl exec shell-demo ps aux
kubectl exec shell-demo ls /
kubectl exec shell-demo cat /proc/1/mounts

當 Pod 包含多個容器時打開 shell

如果 Pod 有多個容器,?--container? 或者 ?-c? 可以在 ?kubectl exec? 命令中指定容器。 例如,你有個名為 my-pod 的 Pod,該 Pod 有兩個容器分別為 main-app 和 healper-app。 下面的命令將會打開一個 shell 訪問 main-app 容器。

kubectl exec -it my-pod --container main-app -- /bin/bash


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號