在开发Kubernetes应用时,我们有时需要操作node level resources, 这时候就不能做个简单的 pod deployment (类似沙盒 不会碰node resources)。 现在就可以用 node-shell这一插件。

Start a root shell in the node's host OS running.

一个用例就是主动删掉旧的 docker images, 虽然k8s有Garbage Collection机制, 但它是被动的按disk usage 百分比触发的。也就是说,当我们需要主动删掉旧image时就可以使用 node-shell


echo "Cleaning up old images..."
echo "Installing kubectl node shell..."
# https://github.com/kvaps/kubectl-node-shell
curl -LO https://github.com/kvaps/kubectl-node-shell/raw/master/kubectl-node_shell
chmod +x ./kubectl-node_shell
sudo mv ./kubectl-node_shell /usr/local/bin/kubectl-node_shell
echo "Done"

names=$(kubectl get node -o json | jq '.items[].metadata.name' -r)
nodecount=$(echo "$names" | wc -l)
echo "Kubernetes underlay has $nodecount vm instances, going to prune docker images one by one"

# loop 
while IFS= read -r nodename; do
    echo "**************** prude node: $nodename ****************"
    kubectl node-shell $nodename -- sh -c 'yes | docker image prune'
    echo "**************** Done ****************"
done <<< "$names"
echo "********************** END **************************"
echo "Prune finished"

更新,新版本的kubernetes已经将容器层从docker替换成了containerd,这时候docker cli就不适用了,取而代之的是 $ctr$crictlContainer Runtime Interface (CRI) CLI。 上述的代码就要修改为:

kubectl node-shell $nodename -- sh -c 'crictl rmi --prune'