【Kubernetes】Podのコンテナにアタッチ

2022.03.03
2024.03.24
Kubernetes
kubectl

はじめに

Podのコンテナにアタッチ(接続)して、直接出力を確認する方法を紹介します。

コンテナにアタッチ

下記コマンドでPod名とコンテナ名を指定してアタッチすることで、コンテナの出力を直接確認できます。

1kubectl attach <pod name> -c <container name>

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

試してみる

実際に試してみます。

下記のDeploymentのマニフェストdeployment.ymlを作成します。

1apiVersion: apps/v1
2kind: Deployment
3metadata:
4  name: test-deployment
5spec:
6  replicas: 2
7  selector:
8    matchLabels:
9      app: app
10  template:
11    metadata:
12      labels:
13        app: app
14    spec:
15      containers:
16        - name: nginx
17          image: nginx:latest
18        - name: redis
19          image: redis:latest

Deploymentを作成します。

1kubectl apply -f deployment.yml

Podにポートフォワードします。

1kubectl port-forward test-deployment-8c8989c98-vjc49 8080:80

ローカルホストにアクセスすることでnginxコンテナのログが出力されます。

1curl localhost:8080

同時にkubectl attachでコンテナにアタッチしていると直接出力が確認できています。

1❯ kubectl attach test-deployment-8c8989c98-vjc49 -c nginx
2If you don't see a command prompt, try pressing enter.
3127.0.0.1 - - [03/Mar/2022:13:49:33 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.77.0" "-"
4127.0.0.1 - - [03/Mar/2022:13:49:36 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.77.0" "-"
5127.0.0.1 - - [03/Mar/2022:13:49:37 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.77.0" "-"
6127.0.0.1 - - [03/Mar/2022:13:49:38 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.77.0" "-"
7127.0.0.1 - - [03/Mar/2022:13:49:39 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.77.0" "-"

参考

Support

\ この記事が役に立ったと思ったら、サポートお願いします! /

buy me a coffee
Share

Profile

author

Masa

都内のIT企業で働くエンジニア
自分が学んだことをブログでわかりやすく発信していきながらスキルアップを目指していきます!

buy me a coffee