본문 바로가기
Big Data

k8s deployment에 sidecar 적용해보기

by 유주원 2023. 9. 25.

대부분의 pod는 1 pod = 1 container가 기본이나 동작 방식이나 응용 방식에 따라서 1pod안에 여러 개의 container를 두는 경우가 있다. 이러한 경우를 sidecar라고 하며 아래의 구조와 같다.

 

그냥 nginx를 별도 pod로 띄우고 micro service를 하면 되지 않을까?? 라는 생각을 잠시 하였으나, web application의 경우 nginx와 통신하기 위해서는 cross domain 문제도 설정해야 하는 이슈 등이 있기 때문에 일단 간편하게 위와 같은 방식으로 사용했다.

sidecar를 설정하기 위해서는 아래와 같이 deployment.yaml을 작성해 주면 된다.

 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: prod-deployment
  namespace: default
spec:
  selector:
    matchLabels:
      app: prod-app
  replicas: 2
  template:
    metadata:
      labels:
        app: prod-app
    spec:
      volumes:
      - name: static-files
        emptyDir: {}
      initContainers:
      - name: copy-static-files
        image: busybox
        command: ["/bin/sh", "-c", "cp -R /static/* /static-files"]
        imagePullPolicy: Always
        volumeMounts:
        - name: static-files
          mountPath: /static-files
      containers:
      - name: prod-main
        image: django:latest
        command: ["gunicorn", "--workers", "4", "--bind", "0.0.0.0:8000", "--access-logfile", "-", "app.wsgi"]
        imagePullPolicy: Always
        resources:
          requests:
            cpu: 500m
            memory: 128Mi
        ports:
        - containerPort: 8000
      - name: prod-nginx
        image: nginx
        imagePullPolicy: IfNotPresent
        resources:
          requests:
            cpu: 500m
            memory: 128Mi
        ports:
        - containerPort: 80
        volumeMounts:
        - mountPath: /static-files
          readOnly: true
          name: static-files

 

init container를 통해 nginx에서 사용될 static file을 마운트 해주고, nginx와 django app을 각각 띄웠다. django app은 gunicorn을 사용해서 1 container에서 4개의 worker가 동작되게 구성했다. 결과적으로 1개의 deployment pod는 4개의 app service와 nginx를 가지고 있고, 이 4개의 app은 한개의 nginx를 바라보게 서비스가 구성되어 있다.

 

그럼 이제 sidecar로 구성된 pod의 확인은 어떻게 해야 할까? 아래의 형태로 작성해 주면 sidecar 접근이 가능하다.

// kubectl exec -it [deploy 명] -c [sidecar container 명] [실행 명령어]
$> kubectl exec -it prod-deployment -c prod-nginx /bin/bash