このセクションでは、Kubernetes クラスタ上で Pod 内の hosts ファイルを設定する方法について紹介します。

サンプルのマニフェストファイルを新規作成し、以下コードを記述します。

[root@kube-master sample-hostschange]# vi sample-hostschange.yaml 

hostAliases に hosts に関わる設定情報を記述します。ここでは、network-gateway と gateway という名前を 192.168.11.1 のIPアドレスと紐づける設定を記述しています。

apiVersion: v1
kind: Pod
metadata:
  name: sample-pod
spec:
  containers:
    - name: nginx-container
      image: nginx:1.13
  hostAliases:
  - ip: 192.168.11.1
    hostnames:
    - network-gateway
    - gateway

Master サーバーから 作成したマニフェストを実行し、Kubernetes クラスタ上にリソースを作成します。

[root@kube-master sample-hostschange]# kubectl apply -f sample-hostschange.yaml 
pod/sample-pod created
[root@kube-master sample-hostschange]# 

Master サーバーから Kubernetes クラスタ上のリソースを確認します。

[root@kube-master sample-hostschange]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
sample-pod   1/1     Running   0          11s
[root@kube-master sample-hostschange]# 

Master サーバーから sample-pod 内の hosts ファイルを確認します。network-gateway と gateway という名前を 192.168.11.1 のIPアドレスと紐づける設定が追加されていることが確認できます。

[root@kube-master sample-hostschange]# kubectl exec -it sample-pod cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
fe00::0	ip6-mcastprefix
fe00::1	ip6-allnodes
fe00::2	ip6-allrouters
10.244.2.39	sample-pod

# Entries added by HostAliases.
192.168.11.1	network-gateway	gateway
[root@kube-master sample-hostschange]#