Docker for Macをインストールする。
kind
、kubectl
をインストールする。
kind
はKubernetesをローカルでテストしたりすることができるツール。
kubectl
はKubernetesのコマンドラインツール。
brew install kind
brew install kubectl
kind version
kubectl version --short
kind create cluster --image docker.io/kindest/node:v1.26.0
kubectl get node
NAME STATUS ROLES AGE VERSION
kind-control-plane Ready control-plane 22m v1.26.0
nginxコンテナを作成したクラスタにデプロイしていきます。
Kubernetesでコンテナをデプロイするにはマニフェストファイルを作成する必要がある。
myapp.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- image: docker.io/nginx:1.23
name: nginx
env:
- name: MY_ENV
valueFrom:
secretKeyRef:
name: myapp-secret
key: MY_ENV
volumeMounts:
- name: myapp-config
mountPath: /etc/nginx/templates
volumes:
- name: myapp-config
configMap:
name: myapp-config
Kubernetesで設定情報を扱うにはConfigMapリソースを使う
myapp-config.yaml
kind: ConfigMap
metadata:
name: myapp-config
data:
default.conf.template: |
server {
location / {
return 200 'Hello $MY_ENV';
add_header Content-Type text/plain;
}
}
docker.io/nginxイメージには/etc/nginx/templates
に*.template
の名前で設定ファイルのテンプレートを
配置すると、テンプレートに含まれる環境変数をその値で変換し、/etc/nginx/conf.d
に配置する。
ConfigMapを/etc/nginx/templates
にマウントするように変更している。
Kubernetesで秘匿情報を扱う場合はSecretリソースを使う。
Secretリソースのdataフィールドに値をBase64エンコードして設定する。
myapp-secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: myapp-secret
data:
MY_ENV: a3ViZXJuZXRlcw==
以下のコマンドでクラスタにPodの作成、変更ができる。
kubectl apply -f myapp-config.yaml -f myapp.yaml -f myapp-secret.yaml
kubectl get deployments
kubectl get pods
kubectl logs [Pod Name]
kubectl port-forward [Pod Name] 8080:80
別ターミナルを開いて確認すると、
Hello kubernetes
が出力される。
curl -s http://127.0.0.1:8080/
Hello kubernetes
kind delete cluster