【Kubernetes】Podのコンテナでコマンド実行とシェル取得

スポンサーリンク

はじめに

KubernetesのPodのコンテナでコマンドを実行する方法コンテナのシェルを取得する方法を紹介します。

コンテナでコマンド実行

kubectl execコマンドを使ってコンテナ内でコマンドを実行します。--でコマンド部分と分離しています。

kubectl exec <pod name> -c <container name> –- <command>

-cでコンテナ名を指定しない場合は最初のコンテナが選ばれます。

コンテナのシェルを取得

シェルを取得する場合は-itオプションを追加します。

kubectl exec -it <pod name> -c <container name> -- <command(shell)>

試してみる

下記のマニフェストpod.ymlのPodを用意します。

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  containers:
  - name: busybox
    image: yauritux/busybox-curl
    args:
      - sleep
      - "999"
  - name: nginx
    image: nginx

Podを作成します。

kubectl apply -f pod.yml

コマンド実行

同じPod内にあるbusybox-curlからnginxへcurlコマンドを使ってみます。

❯ kubectl exec test-pod -c busybox -- curl localhost:80
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   615  100   615    0     0   593k      0 --:--:-- --:--:-- --:--:--  600k
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

シェル取得

busybox-curlnginxのシェルを取得してみます。

❯ kubectl exec -it test-pod -c busybox -- /bin/sh
/home #
❯ k exec -it test-pod -c nginx -- /bin/bash
[email protected]:/#

シェルを取得することでより自由にコンテナ内でコマンド実行ができます。

参考

タイトルとURLをコピーしました