🏗️ Architecture

Sidecar Pattern

Sidecar Pattern

A microservices architecture pattern that places an auxiliary container (sidecar) next to the main application container to separate cross-cutting concerns such as logging, monitoring, proxying, and security. Implemented in a Kubernetes Pod by placing multiple containers in a single Pod.

📖 Detailed Explanation

Pattern principle: The sidecar pattern is named after the sidecar attached to the side of a motorcycle. The main application (the motorcycle) focuses solely on business logic, while the auxiliary functions (the passenger) are handled by the sidecar container. Because the two containers share the same network namespace and storage, they can communicate over localhost and share a file system.

Usage scenarios: The most representative use case is deploying an Envoy proxy as a sidecar in a Service Mesh (Istio, Linkerd). As all network traffic passes through the sidecar, mTLS encryption, traffic control, and observability are applied automatically. Log collection (Fluentd), configuration synchronization (Config Sync), and secret injection (Vault Agent) are also implemented as sidecars.

Advantages: Features can be added without modifying the application code. Because it is independent of language and framework, it provides consistent infrastructure functionality in a polyglot environment. Only the sidecar needs to be upgraded, so maintenance is easy, and the separation of concerns makes testing and debugging easier.

Disadvantages: The number of containers increases, which causes resource overhead. Managing the startup order among containers within a Pod is complex, and a sidecar failure can affect the main application. An additional network hop slightly increases latency.

Starting with Kubernetes 1.28, native sidecar containers are supported, which resolved the startup/shutdown order problem of sidecars combined with initContainer. Cloud vendors such as AWS App Mesh and Google Cloud Traffic Director also offer sidecar-based service meshes.

💻 Code Example

# Kubernetes Sidecar Pattern 기본 예제
apiVersion: v1
kind: Pod
metadata:
  name: web-app-with-sidecar
  labels:
    app: web-app
spec:
  containers:
    # 메인 애플리케이션 컨테이너
    - name: main-app
      image: my-web-app:v1.0
      ports:
        - containerPort: 8080
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/app
        - name: shared-data
          mountPath: /data
      resources:
        requests:
          memory: "256Mi"
          cpu: "250m"
        limits:
          memory: "512Mi"
          cpu: "500m"

    # 사이드카 컨테이너 1: 로그 수집
    - name: log-collector
      image: fluentd:v1.16
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/app
          readOnly: true
        - name: fluentd-config
          mountPath: /fluentd/etc
      env:
        - name: ELASTICSEARCH_HOST
          value: "elasticsearch.logging.svc.cluster.local"
      resources:
        requests:
          memory: "64Mi"
          cpu: "50m"
        limits:
          memory: "128Mi"
          cpu: "100m"

    # 사이드카 컨테이너 2: 프록시
    - name: envoy-proxy
      image: envoyproxy/envoy:v1.28.0
      ports:
        - containerPort: 9901  # Envoy admin
        - containerPort: 10000 # Listener
      volumeMounts:
        - name: envoy-config
          mountPath: /etc/envoy
      resources:
        requests:
          memory: "64Mi"
          cpu: "50m"
        limits:
          memory: "128Mi"
          cpu: "100m"

  # Kubernetes 1.28+ 네이티브 사이드카 (restartPolicy: Always)
  initContainers:
    - name: vault-agent
      image: hashicorp/vault:1.15
      restartPolicy: Always  # 사이드카로 동작
      volumeMounts:
        - name: shared-data
          mountPath: /data
      env:
        - name: VAULT_ADDR
          value: "https://vault.default.svc.cluster.local:8200"

  volumes:
    - name: shared-logs
      emptyDir: {}
    - name: shared-data
      emptyDir: {}
    - name: fluentd-config
      configMap:
        name: fluentd-config
    - name: envoy-config
      configMap:
        name: envoy-config

---
# Service - 메인 앱 포트만 노출
apiVersion: v1
kind: Service
metadata:
  name: web-app-service
spec:
  selector:
    app: web-app
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
# Envoy Sidecar 설정 - Service Mesh 패턴
# envoy-config.yaml

static_resources:
  listeners:
    # 인바운드 트래픽 (외부 → 앱)
    - name: inbound_listener
      address:
        socket_address:
          address: 0.0.0.0
          port_value: 10000
      filter_chains:
        - filters:
            - name: envoy.filters.network.http_connection_manager
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
                stat_prefix: inbound_http
                access_log:
                  - name: envoy.access_loggers.stdout
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog
                route_config:
                  name: local_route
                  virtual_hosts:
                    - name: local_service
                      domains: ["*"]
                      routes:
                        - match:
                            prefix: "/"
                          route:
                            cluster: local_app
                http_filters:
                  # 분산 추적 (Tracing)
                  - name: envoy.filters.http.router
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

    # 아웃바운드 트래픽 (앱 → 외부)
    - name: outbound_listener
      address:
        socket_address:
          address: 127.0.0.1
          port_value: 15001
      filter_chains:
        - filters:
            - name: envoy.filters.network.http_connection_manager
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
                stat_prefix: outbound_http
                route_config:
                  name: outbound_route
                  virtual_hosts:
                    - name: external_services
                      domains: ["*"]
                      routes:
                        - match:
                            prefix: "/"
                          route:
                            cluster: external_service
                            # 재시도 정책
                            retry_policy:
                              retry_on: "5xx,connect-failure"
                              num_retries: 3
                              per_try_timeout: 2s
                            # 타임아웃
                            timeout: 30s
                http_filters:
                  - name: envoy.filters.http.router
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

  clusters:
    # 로컬 애플리케이션
    - name: local_app
      type: STATIC
      connect_timeout: 1s
      lb_policy: ROUND_ROBIN
      load_assignment:
        cluster_name: local_app
        endpoints:
          - lb_endpoints:
              - endpoint:
                  address:
                    socket_address:
                      address: 127.0.0.1
                      port_value: 8080
      # 헬스체크
      health_checks:
        - timeout: 1s
          interval: 10s
          healthy_threshold: 2
          unhealthy_threshold: 3
          http_health_check:
            path: /health

    # 외부 서비스 (Circuit Breaker 적용)
    - name: external_service
      type: STRICT_DNS
      connect_timeout: 5s
      lb_policy: ROUND_ROBIN
      load_assignment:
        cluster_name: external_service
        endpoints:
          - lb_endpoints:
              - endpoint:
                  address:
                    socket_address:
                      address: api.external.com
                      port_value: 443
      transport_socket:
        name: envoy.transport_sockets.tls
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
      # Circuit Breaker 설정
      circuit_breakers:
        thresholds:
          - priority: DEFAULT
            max_connections: 100
            max_pending_requests: 100
            max_requests: 100
            max_retries: 3

admin:
  address:
    socket_address:
      address: 0.0.0.0
      port_value: 9901
# 로깅 사이드카 패턴 - Fluentd 예제
# 메인 앱이 파일로 로그를 쓰면, 사이드카가 수집하여 중앙 저장소로 전송

---
# Fluentd ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluentd-sidecar-config
data:
  fluent.conf: |
    # 애플리케이션 로그 수집
    
      @type tail
      path /var/log/app/*.log
      pos_file /var/log/fluentd/app.log.pos
      tag app.logs
      
        @type json
        time_key timestamp
        time_format %Y-%m-%dT%H:%M:%S.%NZ
      
    

    # 액세스 로그 수집
    
      @type tail
      path /var/log/app/access.log
      pos_file /var/log/fluentd/access.log.pos
      tag app.access
      
        @type regexp
        expression /^(?[^ ]*) - (?[^ ]*) \[(?
    

    # 메타데이터 추가
    
      @type record_transformer
      
        hostname "#{Socket.gethostname}"
        pod_name "#{ENV['POD_NAME']}"
        namespace "#{ENV['POD_NAMESPACE']}"
        container_name "#{ENV['CONTAINER_NAME']}"
      
    

    # Elasticsearch로 전송
    
      @type elasticsearch
      host "#{ENV['ELASTICSEARCH_HOST']}"
      port 9200
      index_name fluentd-${tag}-%Y.%m.%d
      
        @type file
        path /var/log/fluentd/buffer
        flush_interval 5s
        chunk_limit_size 5MB
        total_limit_size 500MB
        retry_max_interval 30s
        retry_forever true
      
    

---
# 실제 Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-with-logging-sidecar
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        # 메인 애플리케이션
        - name: app
          image: my-app:v1.0
          ports:
            - containerPort: 8080
          volumeMounts:
            - name: log-volume
              mountPath: /var/log/app
          env:
            - name: LOG_PATH
              value: /var/log/app/app.log
            - name: LOG_FORMAT
              value: json

        # Fluentd 사이드카
        - name: fluentd-sidecar
          image: fluent/fluentd-kubernetes-daemonset:v1.16-debian-elasticsearch8
          volumeMounts:
            - name: log-volume
              mountPath: /var/log/app
              readOnly: true
            - name: fluentd-config
              mountPath: /fluentd/etc
            - name: fluentd-buffer
              mountPath: /var/log/fluentd
          env:
            - name: ELASTICSEARCH_HOST
              value: elasticsearch.logging.svc.cluster.local
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          resources:
            requests:
              memory: "100Mi"
              cpu: "100m"
            limits:
              memory: "200Mi"
              cpu: "200m"

      volumes:
        - name: log-volume
          emptyDir: {}
        - name: fluentd-config
          configMap:
            name: fluentd-sidecar-config
        - name: fluentd-buffer
          emptyDir: {}

🗣️ Say It Like This in Practice

💬 In a Service Mesh Adoption Meeting
"If you adopt Istio, an Envoy sidecar is automatically injected into every Pod. mTLS, traffic control, and distributed tracing become possible without modifying application code. However, each sidecar has an overhead of about 50–100MB of memory, so factor that into your resource planning."
💬 When Designing a Logging Architecture
"There are two approaches: attaching a Fluentd sidecar to each Pod to collect logs, or deploying one per node as a DaemonSet. The sidecar approach offers better isolation but uses more resources. If the log volume is not large, we recommend a DaemonSet."
💬 In a Vault Secret Management Discussion
"If you deploy Vault Agent as a sidecar, it automatically refreshes secrets and writes them to a shared volume. The application only needs to read files, so it can use secrets without the Vault SDK. There is also no need to restart the app when secrets are refreshed."

⚠️ Cautions & Best Practices

❌
Unmanaged Startup Order

It becomes a problem if the main app starts before the sidecar is ready. Use the native sidecar in Kubernetes 1.28+ or an initContainer, and implement app-level retry logic.

❌
Resource Over-allocation

Allocating CPU/memory to every sidecar leads to a shortage of resources across the entire cluster. Measure actual usage through profiling and set appropriate requests/limits.

❌
Sidecar Failure Propagation

If the proxy sidecar dies, the main app also cannot communicate. Configure liveness/readiness probes for the sidecar, and consider a fallback mode that works even without the sidecar.

✅
Sidecar Pattern Best Practices

Use lightweight sidecar images, communicate efficiently through shared volumes, manage sidecar versions in bulk (Helm/Kustomize), and track sidecar resources through monitoring.

🔗 Related Terms

📚 Learn More