LoongCollector是阿里雲Log Service(SLS)推出的新一代日誌採集 Agent,是 Logtail 的升級版。本文檔指導您如何在 Kubernetes 叢集中安裝 LoongCollector,並提供了 DaemonSet 和 Sidecar 兩種安裝模式。
準備工作
在安裝前,請在叢集節點上驗證與Log Service服務端點的網路連通性,確保LoongCollector可以正常上報資料。
擷取服務存取點:
登入Log Service控制台,在Project列表中,單擊目標Project。
單擊Project名稱右側的
進入專案概覽頁面。在基礎資訊中找到當前Project所在地區的公網和內網Endpoint。
執行連通性測試:登入到將要安裝LoongCollector組件的叢集節點上,執行以下
curl命令。請將${Project名稱}和${SLS_ENDPOINT}替換為您的實際資訊。curl https://${Project名稱}.${SLS_ENDPOINT}查看測試結果:
如果命令返回
{"Error":{"Code":"OLSInvalidMethod",...}},表明您的節點與Log Service之間的網路是通暢的。說明此測試僅驗證網路層連通性。由於請求缺少必要的 API 參數,Log Service返回錯誤響應是預期結果。
如果命令逾時或返回其他網路層錯誤(如
Connection refused),則表示網路不通,請檢查節點的網路設定、安全性群組規則或 DNS 解析。
選擇合適的安裝方式
請根據您的叢集類型和需求,選擇下表中對應的安裝方式:
安裝方式 | 適用情境 |
採集同阿里雲帳號、同地區下的 ACK 託管與專有叢集日誌。 | |
| |
需要對特定業務應用進行日誌採集,且有以下需求的情境:
|
ACK叢集安裝(DaemonSet模式)
如果您當前正在使用logtail-ds,並希望升級到 LoongCollector,請先卸載logtail-ds再安裝LoongCollector。
通過阿里雲ACKContainer Service控制台一鍵安裝LoongCollector,預設將叢集容器日誌採集到同帳號同地區的Project,如需跨帳號或跨地區採集請參考自建叢集安裝(DaemonSet模式)。
為已有ACK託管叢集安裝
登入Container Service管理主控台,在左側導覽列選擇叢集列表。
在叢集列表頁面,單擊目的地組群名稱,然後在左側導覽列,單擊組件管理。
在日誌與監控頁簽中,找到loongcollector,單擊安裝。
安裝完成後,Log Service會自動在ACK所屬地區下建立如下資源,您可登入Log Service控制台查看。
資源類型
資源名稱
作用
Project
k8s-log-${cluster_id}資源嵌入式管理單元,隔離不同業務日誌。
機器組
k8s-group-${cluster_id}loongcollector-ds的機器組,主要用於日誌採集情境。
k8s-group-${cluster_id}-clusterloongcollector-cluster的機器組,主要用於指標採集情境。
k8s-group-${cluster_id}-singleton單一實例機器組,主要用於部分單一實例採集配置。
Logstore
config-operation-log重要請勿刪除此Logstore。
用於儲存LoongCollector組件中的alibaba-log-controller日誌,其收費標準與普通Logstore完全相同,具體請參見按寫入資料量計費模式計費項目。建議不要在此Logstore下建立採集配置。
建立ACK託管叢集時安裝
登入Container Service管理主控台,在左側導覽列選擇叢集列表。
單擊建立叢集,在組件配置頁面,勾選使用Log Service。支援建立新Project或使用已有Project。
本文只描述Log Service相關配置,關於更多配置項說明,請參見建立ACK託管叢集。
當您選擇建立新Project時,Log Service會預設建立如下資源,您可登入Log Service控制台查看。
資源類型
資源名稱
作用
Project
k8s-log-${cluster_id}資源嵌入式管理單元,隔離不同業務日誌。
機器組
k8s-group-${cluster_id}loongcollector-ds的機器組,主要用於日誌採集情境。
k8s-group-${cluster_id}-clusterloongcollector-cluster的機器組,主要用於指標採集情境。
k8s-group-${cluster_id}-singleton單一實例機器組,主要用於部分單一實例採集配置。
Logstore
config-operation-log重要請勿刪除此Logstore。
用於儲存LoongCollector組件中的alibaba-log-controller日誌,其收費標準與普通Logstore完全相同,具體請參見按寫入資料量計費模式計費項目。建議不要在此Logstore下建立採集配置。
自建叢集安裝(DaemonSet模式)
適用情境
自建 IDC 機房中的 Kubernetes 叢集
部署在其他雲廠商的 Kubernetes 叢集
跨帳號或跨地區採集阿里雲 ACK 叢集容器日誌
請確保您的自建叢集滿足Kubernetes 1.6及以上版本。
操作指南
下載並解壓安裝包:在安裝並配置了kubectl的機器上,根據叢集所在地區選擇命令下載LoongCollector及其他相依元件。
#中國地區 wget https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongcollector/k8s-custom-pkg/3.0.12/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh #海外地區 wget https://aliyun-observability-release-ap-southeast-1.oss-ap-southeast-1.aliyuncs.com/loongcollector/k8s-custom-pkg/3.1.6/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh修改設定檔
values.yaml:進入loongcollector-custom-k8s-package目錄,修改設定檔./loongcollector/values.yaml。參數說明
values.yaml
# ===================== 必需要補充的內容 ===================== # 本叢集要採集的Project名,例如 k8s-log-custom-sd89ehdq projectName: "" # Project所屬地區,例如上海:cn-shanghai region: "" # Project所屬主帳號uid,請用引號包圍,例如"123456789" aliUid: "" # 使用網路,選擇性參數:公網Internet,內網Intranet,預設使用公網 net: Internet # 主帳號或者子帳號的AK,SK accessKeyID: "" accessKeySecret: "" # 自訂叢集ID,命名只支援大小寫,數字,短劃線(-)。 clusterID: "" # ...省略非必填參數...projectName
String(必填)Project名稱,LoongCollector將上傳日誌到該Project中。命名規則如下:
專案名稱僅支援小寫字母、數字和連字號(-)。
必須以小寫字母開頭,以小寫字母和數字結尾。
名稱長度為3~63個字元。
region
String(必填)Project所屬地區ID,請參考地區查看Project所在地區的ID。
aliUid
String(必填)Project所屬的阿里雲主帳號ID。
net
String(必填)日誌資料轉送使用的網路類型。
Internet(預設值):公網。
Intranet:內網。
accessKeyID
String(必填)Project所屬帳號的AccessKey ID。推薦使用RAM使用者的AccessKey,並授予RAM使用者AliyunLogFullAccess系統策略許可權。RAM相關概念請參見RAM使用者概覽。
accessKeySecret
String(必填)Project所屬帳號的AccessKey Secret。
clusterID
String(必填)自訂叢集ID,命名只支援大小寫字母、數字、短劃線(-)。
重要不同的Kubernetes叢集,請勿配置相同的叢集ID。
執行安裝指令碼:在
loongcollector-custom-k8s-package目錄下執行如下命令,安裝LoongCollector及其他相依元件。bash k8s-custom-install.sh install驗證安裝結果:安裝完成後,執行如下命令查看組件狀態:
# 檢查Pod狀態 kubectl get po -n kube-system | grep loongcollector-ds返回結果樣本:
loongcollector-ds-gnmnh 1/1 Running 0 63s若組件未成功啟動(非Running):
檢查配置:請確認
values.yaml配置項是否正確。檢查鏡像:通過如下命令查看
Events確認容器鏡像是否成功拉取。kubectl describe pod loongcollector-ds -n kube-system
組件安裝成功後,Log Service會自動建立如下資源,您可登入Log Service控制台查看。
資源類型
資源名稱
作用
Project
values.yaml檔案中自訂的projectName的值資源嵌入式管理單元,隔離不同業務日誌。
機器組
k8s-group-${cluster_id}日誌採集節點集合。
k8s-group-${cluster_id}-clusterloongcollector-cluster的機器組,主要用於指標採集情境。
k8s-group-${cluster_id}-singleton單一實例機器組,主要用於部分單一實例採集配置。
Logstore
config-operation-log重要請不要刪除該Logstore。
用於儲存LoongCollector組件中的alibaba-log-controller日誌,其收費標準與普通Logstore完全相同,具體請參見按寫入資料量計費模式計費項目。建議不要在此Logstore下建立採集配置。
Sidecar模式安裝
當您需要對特定應用的日誌進行精細化管理、實現多租戶隔離或確保日誌採集與應用生命週期嚴格綁定時,Sidecar 模式是理想的日誌採集方案。該模式通過在業務 Pod 中注入一個獨立的 LoongCollector(Logtail) 容器,實現對該 Pod 內日誌的專屬採集。若尚未部署業務應用,或僅用於測試,可直接使用附錄:YAML樣本快速驗證流程。
1. 修改業務Pod YAML配置
定義共用卷
在
spec.template.spec.volumes中添加三個共用卷(與containers同級):volumes: # 共用日誌目錄(業務容器寫入,Sidecar 讀取) - name: ${shared_volume_name} # <-- 名稱需與volumeMounts中的name一致 emptyDir: {} # 容器間通訊信令目錄(用於優雅啟停) - name: tasksite emptyDir: medium: Memory # 使用記憶體作為介質,效能更高 sizeLimit: "50Mi" # 共用主機時區配置:同步Pod內所有容器的時區 - name: tz-config # <-- 名稱需與volumeMounts中的name一致 hostPath: path: /usr/share/zoneinfo/Asia/Shanghai # 請按需修改時區配置業務容器掛載
在業務容器(如
your-business-app-container)的volumeMounts中添加以下掛載項:確保業務容器將日誌寫入
${shared_volume_path}目錄,LoongCollector 才能正確採集。volumeMounts: # 掛載共用記錄磁碟區到業務日誌輸出目錄 - name: ${shared_volume_name} mountPath: ${shared_volume_path} # 例如:/var/log/app # 掛載通訊目錄 - name: tasksite mountPath: /tasksite # 與 Loongcollector容器通訊的共用目錄 # 掛載時區檔案 - name: tz-config mountPath: /etc/localtime readOnly: true注入LoongCollector Sidecar容器
在
spec.template.spec.containers數組中追加以下 Sidecar 容器定義:- name: loongcollector image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun command: ["/bin/bash", "-c"] args: - | echo "[$(date)] LoongCollector: Starting initialization" # 啟動LoongCollector服務 /etc/init.d/loongcollectord start # 等待配置下載和服務就緒 sleep 15 # 驗證服務狀態 if /etc/init.d/loongcollectord status; then echo "[$(date)] LoongCollector: Service started successfully" touch /tasksite/cornerstone else echo "[$(date)] LoongCollector: Failed to start service" exit 1 fi # 等待業務容器完成(通過 tombstone 檔案訊號) echo "[$(date)] LoongCollector: Waiting for business container to complete" until [[ -f /tasksite/tombstone ]]; do sleep 2 done # 留出時間上傳剩餘日誌 echo "[$(date)] LoongCollector: Business completed, waiting for log transmission" sleep 30 # 停止服務 echo "[$(date)] LoongCollector: Stopping service" /etc/init.d/loongcollectord stop echo "[$(date)] LoongCollector: Shutdown complete" # 健全狀態檢查 livenessProbe: exec: command: ["/etc/init.d/loongcollectord", "status"] initialDelaySeconds: 30 periodSeconds: 10 timeoutSeconds: 5 failureThreshold: 3 # 資源配置 resources: requests: cpu: "100m" memory: "128Mi" limits: cpu: "2000m" memory: "2048Mi" # 環境變數配置 env: - name: ALIYUN_LOGTAIL_USER_ID value: "${your_aliyun_user_id}" - name: ALIYUN_LOGTAIL_USER_DEFINED_ID value: "${your_machine_group_user_defined_id}" - name: ALIYUN_LOGTAIL_CONFIG value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json" # 啟用全量排空,確保 Pod 終止前發送所有日誌 - name: enable_full_drain_mode value: "true" # 追加 Pod 環境資訊作為日誌標籤 - name: ALIYUN_LOG_ENV_TAGS value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_" # 自動注入 Pod 和 Node 中繼資料作為日誌標籤 - name: "_pod_name_" valueFrom: fieldRef: fieldPath: metadata.name - name: "_pod_ip_" valueFrom: fieldRef: fieldPath: status.podIP - name: "_namespace_" valueFrom: fieldRef: fieldPath: metadata.namespace - name: "_node_name_" valueFrom: fieldRef: fieldPath: spec.nodeName - name: "_node_ip_" valueFrom: fieldRef: fieldPath: status.hostIP # 卷掛載(與業務容器共用) volumeMounts: # 唯讀掛載業務日誌目錄 - name: ${shared_volume_name} # <-- 共用日誌目錄名 mountPath: ${dir_containing_your_files} # <-- 共用目錄在sidercar中的路徑 readOnly: true # 掛載通訊目錄 - name: tasksite mountPath: /tasksite # 掛載時區 - name: tz-config mountPath: /etc/localtime readOnly: true
2. 改造業務容器生命週期邏輯
根據工作負載類型,需改造業務容器以支援與Sidecar協同退出:
短生命週期任務(Job/CronJob)
# 1. 等待 LoongCollector 準備就緒
echo "[$(date)] Business: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
sleep 1
done
echo "[$(date)] Business: LoongCollector is ready, starting business logic"
# 2. 執行核心商務邏輯(確保日誌寫入共用目錄)
echo "Hello, World!" >> /app/logs/business.log
# 3. 儲存退出碼
retcode=$?
echo "[$(date)] Business: Task completed with exit code: $retcode"
# 4. 通知LoongCollector業務完成
touch /tasksite/tombstone
echo "[$(date)] Business: Tombstone created, exiting"
exit $retcode長生命週期服務(Deployment / StatefulSet)
# 定義訊號處理函數
_term_handler() {
echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
# 發送QUIT訊號給Nginx進行優雅停止
if [ -n "$NGINX_PID" ]; then
kill -QUIT "$NGINX_PID" 2>/dev/null || true
echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
# 等待Nginx優雅停止
wait "$NGINX_PID"
EXIT_CODE=$?
echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
fi
# 通知LoongCollector業務容器已停止
echo "[$(date)] [nginx-demo] Writing tombstone file"
touch /tasksite/tombstone
exit $EXIT_CODE
}
# 註冊訊號處理
trap _term_handler SIGTERM SIGINT SIGQUIT
# 等待LoongCollector準備就緒
echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
sleep 1
done
echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting business logic"
# 啟動Nginx
echo "[$(date)] [nginx-demo] Starting Nginx..."
nginx -g 'daemon off;' &
NGINX_PID=$!
echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
# 等待Nginx進程
wait $NGINX_PID
EXIT_CODE=$?
# 非訊號導致的退出也要通知LoongCollector
if [ ! -f /tasksite/tombstone ]; then
echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
touch /tasksite/tombstone
fi
exit $EXIT_CODE3. 設定優雅終止時間
在 spec.template.spec 中設定足夠的終止寬限期,以確保 LoongCollector 有足夠時間上傳剩餘日誌。
spec:
# ... 您現有的其他 spec 配置 ...
template:
spec:
terminationGracePeriodSeconds: 600 # 10分鐘優雅停止時間4. 變數說明
變數 | 說明 |
| 設定為您的阿里雲帳號(主帳號)ID。更多資訊,請參見配置使用者標識。 |
| 自訂設定機器組的自訂標識,用於建立自訂機器組。例如 重要 請確保該標識在您的Project所在地區內唯一。 |
| 請根據Log ServiceProject所在地區和訪問的網路類型填寫。其中,地區資訊請參見開服地區。 樣本:若Project位於華東1(杭州),則以阿里雲內網訪問時為 |
| 自訂設定卷的名稱。 重要
|
| 設定掛載路徑,即容器待採集文本日誌所在目錄。 |
5. 應用配置並驗證
執行以下命令部署變更:
kubectl apply -f <YOUR-YAML>查看 Pod 狀態,確認 LoongCollector 容器已成功注入:
kubectl describe pod <YOUR-POD-NAME>若看到兩個容器(業務容器 +
loongcollector),且狀態正常,則注入成功。
6. 建立使用者自訂標識機器組
登入Log Service控制台,單擊目標Project。
在左側導覽列中,選擇,單擊機器組右側的。
在建立機器組對話方塊中,配置如下參數,單擊確定。
名稱:機器組名稱,建立後不可修改。命名規則如下:
只能包括小寫字母、數字、短劃線(-)和底線(_)。
必須以小寫字母或者數字開頭和結尾。
長度必須在 2~128 字元之間。
機器組標識:選擇使用者自訂標識。
使用者自訂標識:填入您在1. 修改業務Pod YAML配置YAML檔案中為 LoongCollector 容器設定的環境變數
ALIYUN_LOGTAIL_USER_DEFINED_ID的值。必須完全一致,否則無法關聯成功。
檢查機器組心跳狀態:建立完成後,單擊目標機器組名稱,在機器組狀態區域,查看心跳狀態。
OK:表示LoongCollector 已成功串連到Log Service,機器組註冊成功。
FAIL:
可能是配置未生效,配置生效時間大約需要2分鐘,請稍後重新整理頁面重試。
如果2分鐘後仍為FAIL,請參考Logtail機器組問題排查思路進行診斷。
每個 Pod 對應一個獨立的 LoongCollector 執行個體,建議為不同業務或環境使用不同的自訂標識,便於精細化管理。
常見問題
ACK託管叢集如何修改LoongCollector配置以實現跨帳號或跨地區採集?
如何採集阿里雲ACK Edge、ACK One、ACS、ACK Serverless 叢集容器日誌?
後續步驟
安裝完LoongCollector後,您可以查看Kubernetes叢集容器日誌採集須知瞭解Kubernetes容器日誌採集的核心原理、關鍵流程、選型建議和最佳實務,並選擇合適的方式建立採集配置:
附錄:YAML樣本
本樣本展示了一個完整的 Kubernetes Deployment 配置,包含業務容器(Nginx)和 LoongCollector Sidecar 容器,適用於通過 Sidecar 模式採集容器日誌。
使用前請完成以下三項關鍵替換:
將
${your_aliyun_user_id}替換為您的阿里雲主帳號 UID;將
${your_machine_group_user_defined_id}替換為步驟三中建立的機器組自訂標識,必須完全一致。將
${your_region_config}替換為與Log Service Project 所在地區及網路類型匹配的配置名。樣本:Project 位於 華東1(杭州),內網訪問——>
cn-hangzhou;公網訪問——>cn-hangzhou-internet。
短生命週期(Job/CronJob)
apiVersion: batch/v1
kind: Job
metadata:
name: demo-job
spec:
backoffLimit: 3
activeDeadlineSeconds: 3600
completions: 1
parallelism: 1
template:
spec:
restartPolicy: Never
terminationGracePeriodSeconds: 300
containers:
# 業務容器
- name: demo-job
image: debian:bookworm-slim
command: ["/bin/bash", "-c"]
args:
- |
# 等待LoongCollector準備就緒
echo "[$(date)] Business: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
sleep 1
done
echo "[$(date)] Business: LoongCollector is ready, starting business logic"
# 執行商務邏輯
echo "Hello, World!" >> /app/logs/business.log
# 儲存退出碼
retcode=$?
echo "[$(date)] Business: Task completed with exit code: $retcode"
# 通知LoongCollector業務完成
touch /tasksite/tombstone
echo "[$(date)] Business: Tombstone created, exiting"
exit $retcode
# 資源限制
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500"
memory: "512Mi"
# 卷掛載
volumeMounts:
- name: app-logs
mountPath: /app/logs
- name: tasksite
mountPath: /tasksite
# LoongCollector Sidecar容器
- name: loongcollector
image: aliyun-observability-release-registry.cn-hongkong.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
command: ["/bin/bash", "-c"]
args:
- |
echo "[$(date)] LoongCollector: Starting initialization"
# 啟動LoongCollector服務
/etc/init.d/loongcollectord start
# 等待配置下載和服務就緒
sleep 15
# 驗證服務狀態
if /etc/init.d/loongcollectord status; then
echo "[$(date)] LoongCollector: Service started successfully"
touch /tasksite/cornerstone
else
echo "[$(date)] LoongCollector: Failed to start service"
exit 1
fi
# 等待業務容器完成
echo "[$(date)] LoongCollector: Waiting for business container to complete"
until [[ -f /tasksite/tombstone ]]; do
sleep 2
done
echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
# 給足夠時間傳輸剩餘日誌
sleep 30
echo "[$(date)] LoongCollector: Stopping service"
/etc/init.d/loongcollectord stop
echo "[$(date)] LoongCollector: Shutdown complete"
# 健全狀態檢查
livenessProbe:
exec:
command: ["/etc/init.d/loongcollectord", "status"]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
# 資源配置
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
# 環境變數配置
env:
- name: ALIYUN_LOGTAIL_USER_ID
value: "your-user-id"
- name: ALIYUN_LOGTAIL_USER_DEFINED_ID
value: "your-user-defined-id"
- name: ALIYUN_LOGTAIL_CONFIG
value: "/etc/ilogtail/conf/cn-hongkong/ilogtail_config.json"
- name: ALIYUN_LOG_ENV_TAGS
value: "_pod_name_|_pod_ip_|_namespace_|_node_name_"
# Pod資訊注入
- name: "_pod_name_"
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: "_pod_ip_"
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: "_namespace_"
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: "_node_name_"
valueFrom:
fieldRef:
fieldPath: spec.nodeName
# 卷掛載
volumeMounts:
- name: app-logs
mountPath: /app/logs
readOnly: true
- name: tasksite
mountPath: /tasksite
- name: tz-config
mountPath: /etc/localtime
readOnly: true
# 卷定義
volumes:
- name: app-logs
emptyDir: {}
- name: tasksite
emptyDir:
medium: Memory
sizeLimit: "10Mi"
- name: tz-config
hostPath:
path: /usr/share/zoneinfo/Asia/Shanghai
長生命週期(Deployment / StatefulSet)
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-demo
namespace: production
labels:
app: nginx-demo
version: v1.0.0
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
selector:
matchLabels:
app: nginx-demo
template:
metadata:
labels:
app: nginx-demo
version: v1.0.0
spec:
terminationGracePeriodSeconds: 600 # 10分鐘優雅停止時間
containers:
# 業務容器 - Web應用
- name: nginx-demo
image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
# 啟動命令和訊號處理
command: ["/bin/sh", "-c"]
args:
- |
# 定義訊號處理函數
_term_handler() {
echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
# 發送QUIT訊號給Nginx進行優雅停止
if [ -n "$NGINX_PID" ]; then
kill -QUIT "$NGINX_PID" 2>/dev/null || true
echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
# 等待Nginx優雅停止
wait "$NGINX_PID"
EXIT_CODE=$?
echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
fi
# 通知LoongCollector業務容器已停止
echo "[$(date)] [nginx-demo] Writing tombstone file"
touch /tasksite/tombstone
exit $EXIT_CODE
}
# 註冊訊號處理
trap _term_handler SIGTERM SIGINT SIGQUIT
# 等待LoongCollector準備就緒
echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
sleep 1
done
echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting business logic"
# 啟動Nginx
echo "[$(date)] [nginx-demo] Starting Nginx..."
nginx -g 'daemon off;' &
NGINX_PID=$!
echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
# 等待Nginx進程
wait $NGINX_PID
EXIT_CODE=$?
# 非訊號導致的退出也要通知LoongCollector
if [ ! -f /tasksite/tombstone ]; then
echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
touch /tasksite/tombstone
fi
exit $EXIT_CODE
# 資源配置
resources:
requests:
cpu: "200m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "1Gi"
# 卷掛載
volumeMounts:
- name: nginx-logs
mountPath: /var/log/nginx
- name: tasksite
mountPath: /tasksite
- name: tz-config
mountPath: /etc/localtime
readOnly: true
# LoongCollector Sidecar容器
- name: loongcollector
image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
command: ["/bin/bash", "-c"]
args:
- |
echo "[$(date)] LoongCollector: Starting initialization"
# 啟動LoongCollector服務
/etc/init.d/loongcollectord start
# 等待配置下載和服務就緒
sleep 15
# 驗證服務狀態
if /etc/init.d/loongcollectord status; then
echo "[$(date)] LoongCollector: Service started successfully"
touch /tasksite/cornerstone
else
echo "[$(date)] LoongCollector: Failed to start service"
exit 1
fi
# 等待業務容器完成
echo "[$(date)] LoongCollector: Waiting for business container to complete"
until [[ -f /tasksite/tombstone ]]; do
sleep 2
done
echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
# 給足夠時間傳輸剩餘日誌
sleep 30
echo "[$(date)] LoongCollector: Stopping service"
/etc/init.d/loongcollectord stop
echo "[$(date)] LoongCollector: Shutdown complete"
# 健全狀態檢查
livenessProbe:
exec:
command: ["/etc/init.d/loongcollectord", "status"]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
# 資源配置
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "2000m"
memory: "2048Mi"
# 環境變數配置
env:
- name: ALIYUN_LOGTAIL_USER_ID
value: "${your_aliyun_user_id}"
- name: ALIYUN_LOGTAIL_USER_DEFINED_ID
value: "${your_machine_group_user_defined_id}"
- name: ALIYUN_LOGTAIL_CONFIG
value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json"
# 啟用全量排空模式,確保Pod停止時發送所有日誌
- name: enable_full_drain_mode
value: "true"
# 追加 Pod 環境資訊作為日誌標籤
- name: "ALIYUN_LOG_ENV_TAGS"
value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_"
# 擷取 Pod 和 Node 的資訊
- name: "_pod_name_"
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: "_pod_ip_"
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: "_namespace_"
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: "_node_name_"
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: "_node_ip_"
valueFrom:
fieldRef:
fieldPath: status.hostIP
# 卷掛載
volumeMounts:
- name: nginx-logs
mountPath: /var/log/nginx
readOnly: true
- name: tasksite
mountPath: /tasksite
- name: tz-config
mountPath: /etc/localtime
readOnly: true
# 卷定義
volumes:
- name: nginx-logs
emptyDir: {}
- name: tasksite
emptyDir:
medium: Memory
sizeLimit: "50Mi"
- name: tz-config
hostPath:
path: /usr/share/zoneinfo/Asia/Shanghai
> 建立機器組