본문 바로가기

인프라,데이터/Docker, Kubernetes

Kubernetes 특정 경로로 로그 파일 수집하기(nginx access 로그 만들기)

nginx같은 경우는 /var/log/nginx/ 경로 하위에 access.log, error.log가 만들어진다.

이렇게 쌓이는 로그를 쿠버네티스에 띄운 Logstash로 수집할 수 있다.

nginx.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  namespace: test
spec:
  replicas: 3
  selector:
    matchLabels:
      run: my-nginx
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: beta.kubernetes.io/arch
                operator: In
                values:
                - amd64
                - arm64
      containers:
      - name: nginx
        image: public.ecr.aws/z9d2n7e1/nginx:1.19.5
        volumeMounts:
        - name: varlog
          mountPath: /var/log/nginx
          subPath: nginx
        imagePullPolicy: Always
        ports:
        - containerPort: 80
      terminationGracePeriodSeconds: 30
      volumes:
        - name: varlog
          hostPath:
            path: /var/log/containers

 

nginx-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-nginx
  namespace: test
  labels:
    run: my-nginx
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    run: my-nginx

$ kubectl apply -f nginx.yaml
$ kubectl apply -f nginx-service.yaml 로 배포해준다.

여기서 포인트는 volumeMounts 설정으로 nginx 파드의 /var/log/nginx 폴더를 워커노드의 /var/log/containers와 마운트하되,
var/log/nginx 폴더 하위에는 nginx에서 생긴 access.log와 error.log만 있다는 것이다.

보통 마운트하면 워커노드의 모든 파일들이 다 딸려오거나, 워커노드의 파일들로 덮어씌워지는데 그러지 않는다!

$ kubectl get pods -n test 로 배포된 파드를 확인해주고,

$ kubectl exec -ti $podsname -n test /bin/bash 로 파드 안에 접속해준다.

$ curl my-nginx(서비스 이름) 을 하면 

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

다음과 같이 로그가 뜬다. 하지만 이렇게 서비스로 접속해도 3개의 파드 중에 랜덤으로 떨어지기 떄문에, 6-10번 정도 명령어를 반복해준 후,  

/var/log/nginx/access.log를 확인해보면 (apt-get update , apt-get install vim으로 vim을 깔아야 한다)

다음과 같은 로그가 쌓이는 것을 볼 수 있다.

Kubernetes에서 Logstash(sqs output)를 사용해 elasticsearch, kibana로 로그 확인

이 로그를 로그스태시로 받아와 엘라스틱서치로 보내면, 키바나에서 다음과 같이 확인할 수 있다.