Bài 8: Sử Dụng Sidecar Và Init Container

Sau khi đã giới thiệu tổng quan về thiết kế Pod với nhiều container ở Bài 7, chúng ta sẽ đi sâu vào hai thành phần quan trọng nhất: Sidecar và Init Container. Bài này sẽ giúp bạn hiểu rõ cách triển khai chúng trong thực tế, với các ví dụ cụ thể để xây dựng ứng dụng phức tạp hơn, đồng thời tận dụng tối đa lợi ích của multi-container Pods.

Bài viết này thuộc domain Multi-Container Pods của kỳ thi CKAD (chiếm 18% trọng số), kiểm tra khả năng thiết kế và debug Pods với sidecar để hỗ trợ logging/monitoring, hoặc init containers để chuẩn bị môi trường. Trong CKAD, các task thường yêu cầu bạn viết YAML để thêm sidecar chia sẻ volume với app container, hoặc init container chờ service ready trước khi app chạy.

Sidecar Container Là Gì Và Cách Sử Dụng

Sidecar là một container phụ chạy song song với container chính (app container) trong cùng Pod, nhằm mở rộng hoặc hỗ trợ chức năng mà không thay đổi code của app chính. Sidecar thường xử lý các nhiệm vụ phụ như logging, monitoring, proxy, hoặc file synchronization. Vì chia sẻ network và storage với app, sidecar có thể giao tiếp qua localhost hoặc read/write files chung mà không cần overhead network.

Lợi ích chính của sidecar:

  • Non-invasive enhancement: Thêm tính năng như encrypt traffic hoặc ship logs mà không modify app image.
  • Modularity: Tách biệt trách nhiệm, dễ maintain (ví dụ: update logging tool riêng).
  • Common use cases: Logging (Fluentd sidecar thu thập logs từ app), Proxy (Envoy sidecar cho service mesh), Monitoring (Prometheus exporter), hoặc Backup (sidecar sync files đến storage external).
  • Limitations: Tăng resource usage cho Pod, không scale độc lập (toàn Pod scale cùng).

Ví dụ điển hình: Một web app (nginx) write logs vào volume, sidecar (busybox hoặc fluentbit) đọc logs và gửi đến central log server như Elasticsearch.

Dưới đây là diagram minh họa pattern sidecar trong Kubernetes, cho thấy cách sidecar hỗ trợ app container qua shared volume.

https://matthewpalmer.net/kubernetes-app-developer/multi-container-pod-design.png

Cấu Hình Sidecar Trong YAML

Sidecar được định nghĩa trong mảng spec.containers, cùng với app container. Sử dụng volumes để share data.

YAML ví dụ cho sidecar logging:

apiVersion: v1
kind: Pod
metadata:
  name: sidecar-pod
spec:
  containers:
  - name: app-container
    image: nginx:latest
    volumeMounts:
    - name: logs-volume
      mountPath: /var/log/nginx
  - name: logging-sidecar
    image: busybox
    command: ["/bin/sh"]
    args: ["-c", "tail -n+1 -f /var/log/nginx/access.log"]
    volumeMounts:
    - name: logs-volume
      mountPath: /var/log/nginx
  volumes:
  - name: logs-volume
    emptyDir: {}

Trong ví dụ này, app write logs vào /var/log/nginx, sidecar đọc và output (có thể thay bằng fluentd để ship real).

Dưới đây là ví dụ cụ thể về multi-container Pod với sidecar, minh họa luồng write-read logs.

https://miro.medium.com/v2/resize:fit:1400/1*LrHXpN7z0QsCdoNj_smsmQ.png

Init Container Là Gì Và Cách Sử Dụng

Init Container là container đặc biệt chạy trước app containers trong Pod, dùng để thực hiện các nhiệm vụ khởi tạo như download dependencies, generate config, hoặc wait until a service is ready. Chúng chạy sequentially (một sau một), phải hoàn thành (exit 0) trước khi app start. Nếu init fail, Kubernetes retry theo restartPolicy (default Always).

Lợi ích chính:

  • Setup precondition: Đảm bảo môi trường sẵn sàng (ví dụ: clone Git repo vào volume, check DB connection).
  • Security: Chạy với privileges cao hơn app (ví dụ: chown files), rồi app chạy least privilege.
  • One-time tasks: Không chạy liên tục như sidecar, tiết kiệm resource.
  • Common use cases: Wait for service (curl loop đến khi ready), Populate volume (wget files), hoặc Register Pod với external system.

Ví dụ: Init container download HTML file vào volume, rồi nginx app serve nó.

Dưới đây là diagram lifecycle của init containers bài trước bạn cũng đã thấy rồi, minh họa thứ tự chạy và chuyển tiếp đến app phase.

https://devopscube.com/content/images/2025/03/init-container-2.gif

Cấu Hình Init Container Trong YAML

Init containers định nghĩa trong spec.initContainers, chạy trước containers.

YAML ví dụ cho init setup:

apiVersion: v1
kind: Pod
metadata:
  name: init-pod
spec:
  initContainers:
  - name: init-downloader
    image: busybox
    command: ["/bin/sh"]
    args: ["-c", "wget -O /work-dir/index.html http://example.com/index.html"]
    volumeMounts:
    - name: work-volume
      mountPath: /work-dir
  containers:
  - name: app-container
    image: nginx
    volumeMounts:
    - name: work-volume
      mountPath: /usr/share/nginx/html
  volumes:
  - name: work-volume
    emptyDir: {}

Init download file, rồi app serve nó.

Dưới đây là diagram Pod với init containers, cho thấy cách init populate volume cho main containers.

https://devopscube.com/content/images/2025/03/image-71-7.png

Bảng So Sánh Sidecar Và Init Container

Tiêu chí Sidecar Container Init Container
Vị trí trong YAML spec.containers (cùng app) spec.initContainers (riêng)
Thời gian chạy Song song và liên tục với app Trước app, one-time đến hoàn thành
Mục đích Hỗ trợ/enhance app (logging, proxy) Khởi tạo/setup (download, wait)
Restart policy Theo Pod (Always/OnFailure/Never) Default Always nếu fail
Probes Hỗ trợ liveness/readiness Không hỗ trợ (vì one-time)
Resource usage Chạy lâu dài, chia sẻ resource Ngắn hạn, release sau hoàn thành
Use case ví dụ Ship logs đến external Clone repo vào volume

Kết Hợp Sidecar Và Init Container Trong Một Pod

Bạn có thể dùng cả hai trong cùng Pod: Init setup ban đầu, rồi app + sidecar chạy.

YAML kết hợp:

apiVersion: v1
kind: Pod
metadata:
  name: combined-pod
spec:
  initContainers:
  - name: init-setup
    image: busybox
    command: ['sh', '-c', 'echo "Init done" > /data/init.txt']
    volumeMounts:
    - name: shared-data
      mountPath: /data
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: shared-data
      mountPath: /usr/share/nginx/html
  - name: sidecar
    image: busybox
    command: ['sh', '-c', 'while true; do echo "Sidecar running" >> /data/log.txt; sleep 5; done']
    volumeMounts:
    - name: shared-data
      mountPath: /data
  volumes:
  - name: shared-data
    emptyDir: {}

Dưới đây là diagram tổng quan về container strategies bao gồm sidecar và init.

531e8689-1d7f-4ce4-b202-3bf2e6d49b8a

Các Lệnh Kubectl Để Quản Lý Sidecar Và Init Container

  • Logs cụ thể: kubectl logs combined-pod -c sidecar (lấy logs sidecar/init).
  • Exec vào container: kubectl exec -it combined-pod -c app -- /bin/bash.
  • Describe Pod: kubectl describe pod combined-pod (xem status mỗi container, events init).
  • Debug init fail: Nếu Pod stuck ở Init:0/1, dùng logs -c init-setup xem lỗi.
  • Get all containers: kubectl get pod combined-pod -o jsonpath='{.spec.containers[*].name} {.spec.initContainers[*].name}'.

Liên Hệ Với Chứng Chỉ CKAD

Domain Multi-Container Pods (18%) thường có task yêu cầu sử dụng sidecar/init, như:

  • Thêm init container để wget file vào volume cho app đọc.
  • Tạo sidecar chia sẻ volume để tail logs từ app.
  • Debug Pod với init fail bằng describe/logs.

Mẹo thi:

  • Luôn chỉ định -c cho logs/exec, vì default là container đầu tiên.
  • Init không có probes, nên dùng command đơn giản để check success.
  • Thời gian: 5-7 phút/task, verify bằng exec ls/cat vào volume.
  • Luyện: kubectl explain pod.spec.initContainers cho docs YAML.
  • Kết hợp với volumes (emptyDir/hostPath) để share data.

Thực Hành Thực Tế Trên Minikube

  1. Tạo YAML cho sidecar: Sao chép YAML sidecar vào sidecar.yaml, apply: kubectl apply -f sidecar.yaml.
  2. Kiểm tra:
    kubectl get pods  # Chờ Running
    kubectl logs sidecar-pod -c logging-sidecar  # Xem output tail
  3. Tạo YAML cho init: Sao chép YAML init vào init.yaml, apply.
  4. Kiểm tra init:
    kubectl describe pod init-pod  # Xem init complete
    kubectl exec -it init-pod -- cat /usr/share/nginx/html/index.html  # Xem file
  5. Kết hợp: Apply YAML combined, logs -c sidecar, exec -c app ls /usr/share/nginx/html.
  6. Cleanup: kubectl delete pod sidecar-pod init-pod combined-pod.

Nếu init fail, Pod không Running, sửa YAML và reapply.

Kết Luận

Bài này mình đã hướng dẫn chi tiết sử dụng Sidecar và Init Container, từ khái niệm đến YAML thực tế. Bạn giờ có thể thiết kế Pods linh hoạt hơn, sẵn sàng cho các task Multi-Container Pods trong CKAD. Tiếp theo, ở Bài 9: Chia Sẻ Tài Nguyên Giữa Các Container, chúng ta sẽ tìm hiểu cách share network, storage, và process giữa containers (phần này quan trọng lắm nhé).

Điều hướng chuỗi bài viết<< Bài 7: Thiết Kế Pod Với Nhiều Container>> Bài 9: Chia Sẻ Tài Nguyên Giữa Các Container

Thông tin nổi bật

Báo cáo quan trọng

Sự kiện đang hiện hành

Chia sẻ bài viết:
Theo dõi
Thông báo của
0 Góp ý
Được bỏ phiếu nhiều nhất
Mới nhất Cũ nhất
Phản hồi nội tuyến
Xem tất cả bình luận