K8s 資料掛載 - hostpath

💡
下面這篇教學有「一般無範本資料」的教學,如果想要在 init database 的時候有資料,可以參考我
 

為什麼 hostpath 只適合開發用,來說明一下優缺點

優:最直觀的就是設定相對簡單,畢竟綁在本機的話就不用考慮多台機器的複雜情況了
缺:
  1. 機器耦合性高:
    1. 如果今天在生產環境下需要十台 worker node,則當今天存放資料的 node 掛掉了,整個 volume 也就跟著沒了
    2. 在 node 故障的時候 Kubernetes 會重新分配資源,這時如果要確保資料的一致性,就只能等該 node 重開機了
  1. 資安問題:如果存放資料的 node 被駭,加上本地檔案系統也沒有妥善管理權限,資料可能會被掏走
 

init container,你放置 sample data 的好夥伴

💡

Initializing a fresh instance

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh.sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.
 

db-pv-claim.yaml設定 pv, pvc,供未來 volume 使用(要不要加範本資料都要做)

💡
pv 是實際的儲存空間,pvc 是跟這塊儲存空間索取空間來用
apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv-volume namespace: jpetstore-dev labels: type: local spec: storageClassName: manual capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/jpetstore/data" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim namespace: jpetstore-dev spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 10Gi
 

db-configmap.yaml設定 configMap (加 sample data 才要做)

apiVersion: v1 kind: ConfigMap metadata: name: mysql-init-config namespace: jpetstore-dev data: init.sql: | 以下為你的 .sql 內容
 
 

db-deployment.yml : 詳情參考註解

apiVersion: apps/v1 kind: Deployment metadata: name: mysql namespace: jpetstore-dev spec: replicas: 1 selector: matchLabels: app: mysql strategy: type: Recreate template: metadata: labels: app: mysql spec: containers: - name: mysql image: mysql:5.7 ports: - containerPort: 3306 env: - name: MYSQL_ROOT_PASSWORD value: YOUR_PWD volumeMounts: # init container,會把你的 configmap 內的資料放進去 /docker-entrypoint-initdb.d 目錄 - name: mysql-init-db # configMap mountPath: /docker-entrypoint-initdb.d # volume,你的資料都會在這了 - name: mysql-pv-volume # pv mountPath: /var/lib/mysql resources: limits: cpu: 1000m memory: 512Mi volumes: - name: mysql-pv-volume # pv persistentVolumeClaim: claimName: mysql-pv-claim # pvc - name: mysql-init-db # configMap configMap: name: mysql-init-config
 
 

進去 pod 看看是否成功

kk exec --stdin --tty {POD ID} -n {Namespace} -- /bin/sh
再來就用一般登入手法,檢查 database 是否存在
mysql -u root -p
show databases;
use XXX;
show tables;

踩坑:不知道怎麼把已經 mount 上去的 .sql 倒進去 mysql

  • 把 hostpath 的 volume 資料夾刪掉
  • 移除 pv, pvc
kubectl edit pv (pv name) Find the following in the manifest file finalizers: - kubernetes.io/pv-protection ... and delete it.