---
# System prepended metadata

title: PV 使用 Hostpath 方式創建
tags: [K8S]

---

# PV 使用 Hostpath 方式創建

* 創建以下 sample
```
kind: PersistentVolume
apiVersion: v1
metadata:
  name: hostpath-pv
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  reclaimPolicy:
    - Recycle
  hostPath:
    path: "/tmp/data1"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: hostpath-pvc
spec:
  storageClassName: ""
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-server
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web-server
  template:
    metadata:
      labels:
        app: web-server
    spec:
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
            claimName: hostpath-pvc
      containers:
        - name: task-pv-container
          image: nginx
          ports:
            - containerPort: 80
              name: "http-server"
          volumeMounts:
            - mountPath: "/usr/share/nginx/html"
              name: task-pv-storage
```
* 檢查
```
$ kubectl get pv,pvc
NAME                           CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                  STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
persistentvolume/hostpath-pv   1Gi        RWO            Retain           Bound    default/hostpath-pvc                  <unset>                          2m45s

NAME                                 STATUS   VOLUME        CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
persistentvolumeclaim/hostpath-pvc   Bound    hostpath-pv   1Gi        RWO                           <unset>                 2m45s


$ kubectl get pod -owide
NAME                          READY   STATUS    RESTARTS   AGE   IP             NODE      NOMINATED NODE   READINESS GATES
web-server-57bb9fdf86-xwgfr   1/1     Running   0          84s   10.42.55.199   rke2-w1   <none>           <none>
```

* 透過 hostpath 的方式 pod 就不會像 local 一樣，被限制在同一個節點上。pod 允許飄移，但資料還是只會存在原本的節點上。

```
$ kubectl exec web-server-57bb9fdf86-xwgfr -- sh -c "echo 123 > /usr/share/nginx/html/index.html"

$ curl 10.42.55.199
123

$ kubectl cordon rke2-w1

$ kubectl delete pod web-server-57bb9fdf86-xwgfr

# pod 可以漂移了，但是資料並不會跟者同步
$ kubectl get pod -owide
NAME                          READY   STATUS    RESTARTS   AGE   IP             NODE      NOMINATED NODE   READINESS GATES
web-server-57bb9fdf86-86ljs   1/1     Running   0          11s   10.42.82.105   rke2-w3   <none>           <none>

$ curl 10.42.82.105
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.27.4</center>
</body>
</html>

$ kubectl uncordon rke2-w1
```
