iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
DevOps

其實我真的沒想過要利用夾縫中求生存的 30 天K8s可以怎麼用系列 第 3

Oh My Logs ! 談談如何在K8s中收集logs - 3

  • 目錄
    • Introduce and analysis
    • cluster level ELK
    • @ sidecar mode @
    • integrate log collecting component into an app

HI 大家今天過得好嗎?
今天要來動手做個sidecar

以下這張來自官網的圖很清楚地解釋了sidecar on K8s的運作模式

大部分的pod只運行一個container, 但在某些情況下
我們必須要在一個pod運行兩個以上的containers, 這種multi-container的模式又可以衍伸至三種design patterns:

  • sidecar pattern: 最簡單的方式, 兩個container利用volume的方式share同一個檔案目錄
  • adapter pattern: 利用另外一個container做接口, 把要輸出的資料格式化, 例如同一套log system便可以處理不同pods的log
  • ambassador pattern: 假若開發環境是在local, 此種模式可以將pod要輸出的資料直接寫在local的資料庫等

此圖出自這裡, 這張圖蠻清楚的描述了三種模式的不同,但由於篇幅以及時間關係,我就先講sidecar mode


這邊就利用上面文件裡的範例寫一個帶有nginx sidecar的pod yaml.

apiVersion: v1
kind: Pod
metadata:
  name: pod-with-sidecar
spec:
  # Create a volume called 'shared-logs' that the
  # app and sidecar share.
  volumes:
  - name: shared-logs 
    emptyDir: {}

  # In the sidecar pattern, there is a main application
  # container and a sidecar container.
  containers:

  # Main application container
  - name: app-container
    # Simple application: write the current date
    # to the log file every five seconds
    image: alpine # alpine is a simple Linux OS image
    command: ["/bin/sh"]
    args: ["-c", "while true; do date >> /var/log/app.txt; sleep 5;done"]

    # Mount the pod's shared log file into the app 
    # container. The app writes logs here.
    volumeMounts:
    - name: shared-logs
      mountPath: /var/log

  # Sidecar container
  - name: sidecar-container
    # Simple sidecar: display log files using nginx.
    # In reality, this sidecar would be a custom image
    # that uploads logs to a third-party or storage service.
    image: nginx:1.7.9
    ports:
      - containerPort: 80

    # Mount the pod's shared log file into the sidecar
    # container. In this case, nginx will serve the files
    # in this directory.
    volumeMounts:
    - name: shared-logs
      mountPath: /usr/share/nginx/html # nginx-specific mount path

在這邊請注意 volumes 裡的 emptyDir 是建立pod時會自動生成的一個目錄,該pod下所有container都可以讀取這目錄的內容

直接創建:

跑起來之後下這個指令查看pod的詳細內容:

接著透過詳細內容中的訊息分別進入兩個containers中查看紀錄logs的目錄:

可以看到在app-container產生的時間log被同步進nginx這個container了

這就是最簡單的sidecar mode
下篇來講app level的log收集

Reference

官方文件-Pod Overview:
https://kubernetes.io/docs/concepts/workloads/pods/pod-overview/
Multi-container design pattern:https://matthewpalmer.net/kubernetes-app-developer/articles/multi-container-pod-design-patterns.html


上一篇
Oh My Logs ! 談談如何在K8s中收集logs - 2
下一篇
Oh My Logs ! 談談如何在K8s中收集logs - 4
系列文
其實我真的沒想過要利用夾縫中求生存的 30 天K8s可以怎麼用12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
chichi
iT邦新手 3 級 ‧ 2019-09-18 08:31:34

這邊的 design patterns 是針對微服務設計的嗎 ?

ccshih iT邦新手 4 級 ‧ 2019-09-25 10:03:57 檢舉

是針對 pod 的特性設定的。當一個 pod 裡可以佈署多個 container,我們可以拆分不同功能到各個 container 中,然後套用軟體工程中的拆分模式,如:adapter, facade,來設計這些 container

我要留言

立即登入留言