이번에는 NGINX 의 access.log 를 가지고 Grafana 대시보드를 만들어 보겠습니다.

 

사전준비물이 난이도가 좀 있는 편이기 때문에, 천천히 잘 따라오시면 됄듯합니다.

 

우선 mmdb 가 필요합니다.

 

curl -L https://api.manana.kr/v2/maxmind/geoip/GeoLite2-Country.mmdb -o /etc/nginx/GeoLite2-Country.mmdb

 

mmdb를 서버에 다운로드 받습니다.

 

그리고 NGINX 에서 쓸 ngx_http_geoip2_module.so 를 만듭니다.

 

git clone https://github.com/leev/ngx_http_geoip2_module.git

 

깃에서 모듈을 다운로드 받습니다.

 

nginx -v

 

그리고 NGINX 의 버전을 확인합니다.

 

nginx version: nginx/1.18.0 (Ubuntu)

 

현재 글을 쓰는 시점에서의 기본 버전은 1.18.0 입니다.

 

이 버전을 기억해주세요.

 

wget http://nginx.org/download/nginx-1.18.0.tar.gz

 

버전을 꼭 일치해주셔야 합니다.

 

아니면 컴파일후에 오류납니다.

 

tar -zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0/
./configure --with-compat --add-dynamic-module=../ngx_http_geoip2_module

 

위의 명령어를 순서대로 입력합니다.

 

컴파일이 한번에 돼면 좋겠지만, 대부분의 경우 안돼기때문에..

 

제가 발견한 에러에 대한 해결방안만 적어둡니다.

 

여기에 적지 않은건 저도 경험해보지 못한거라 검색하시기 바랍니다.

 

- ./configure: error: C compiler cc is not found

sudo apt install -y gcc build-essential

 

- ./configure: error: the geoip2 module requires the maxminddb library.

sudo apt install -y libmaxminddb-dev

 

- ./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

sudo apt install -y libpcre3 libpcre3-dev

 

- ./configure: error: the HTTP gzip module requires the zlib library.

You can either disable the module by using --without-http gzip module

option, or install the zlib library into the system, or build the zlib library

statically from the source with nginx by using --with-zlib=<path> option.

sudo apt install -y zlib1g zlib1g-dev

 

오류가 발생하면, 해당 오류에 대한 해결방법을 설치하신후에 다시 명령어를 입력해주시면 다음으로 넘어갑니다.

 

성공적으로 종료돼었다면, 아래의 명령어를 순서대로 입력해주세요.

 

make modules

cp objs/ngx_http_geoip2_module.so /usr/lib/nginx/modules/

 

만약에 make 시 아래와 같은 에러가 발생한다면 해결해줍니다.

 

- Command 'make' not found

sudo apt install -y make

 

이제 NGINX 기본 설정에 모듈을 로드합니다.

 

vi /etc/nginx/nginx.conf

 

파일을 열고.

 

load_module modules/ngx_http_geoip2_module.so;

 

모듈 로드 구문을 추가해줍니다.

 

저는 events, http 전에 추가했습니다.

(맨위에 한줄짜리 명령어들이 있는 부분 아래..)

 

log_format json_analytics escape=json '{'
'"msec": "$msec", ' # request unixtime in seconds with a milliseconds resolution
'"connection": "$connection", ' # connection serial number
'"connection_requests": "$connection_requests", ' # number of requests made in connection
'"pid": "$pid", ' # process pid
'"request_id": "$request_id", ' # the unique request id
'"request_length": "$request_length", ' # request length (including headers and body)
'"remote_addr": "$remote_addr", ' # client IP
'"remote_user": "$remote_user", ' # client HTTP username
'"remote_port": "$remote_port", ' # client port
'"time_local": "$time_local", '
'"time_iso8601": "$time_iso8601", ' # local time in the ISO 8601 standard format
'"request": "$request", ' # full path no arguments if the request
'"request_uri": "$request_uri", ' # full path and arguments if the request
'"args": "$args", ' # args
'"status": "$status", ' # response status code
'"body_bytes_sent": "$body_bytes_sent", ' # the number of body bytes exclude headers sent to a client
'"bytes_sent": "$bytes_sent", ' # the number of bytes sent to a client
'"http_referer": "$http_referer", ' # HTTP referer
'"http_user_agent": "$http_user_agent", ' # user agent
'"http_x_forwarded_for": "$http_x_forwarded_for", ' # http_x_forwarded_for
'"http_host": "$http_host", ' # the request Host: header
'"server_name": "$server_name", ' # the name of the vhost serving the request
'"request_time": "$request_time", ' # request processing time in seconds with msec resolution
'"upstream": "$upstream_addr", ' # upstream backend server for proxied requests
'"upstream_connect_time": "$upstream_connect_time", ' # upstream handshake time incl. TLS
'"upstream_header_time": "$upstream_header_time", ' # time spent receiving upstream headers
'"upstream_response_time": "$upstream_response_time", ' # time spent receiving upstream body
'"upstream_response_length": "$upstream_response_length", ' # upstream response length
'"upstream_cache_status": "$upstream_cache_status", ' # cache HIT/MISS where applicable
'"ssl_protocol": "$ssl_protocol", ' # TLS protocol
'"ssl_cipher": "$ssl_cipher", ' # TLS cipher
'"scheme": "$scheme", ' # http or https
'"request_method": "$request_method", ' # request method
'"server_protocol": "$server_protocol", ' # request protocol, like HTTP/1.1 or HTTP/2.0
'"pipe": "$pipe", ' # "p" if request was pipelined, "." otherwise
'"gzip_ratio": "$gzip_ratio", '
'"geoip_country_code": "$geoip_country_code"'
'}';

geoip2 /etc/nginx/GeoLite2-Country.mmdb {
  $geoip_country_code default=US source=$remote_addr country iso_code;
}

access_log /var/log/nginx/json_access.log json_analytics;

 

그리고 http 안쪽에 위의 코드를 넣어줍니다.

 

NGINX 를 재시작합니다.

 

sudo service nginx restart

 

그리고 브라우저에서 IP 로 접속해서 로그가 정상적으로 쌓이는지를 확인합니다.

 

/var/log/nginx/json_access.log 가 정상적으로 json 방식으로 쌓이면 성공입니다.

 

그러면 이제 json_access.log 를 Grafana 로 보내주기 위한 프로그램 Grafana Promtail 을 설치합니다.

(Grafana Loki 와 짝을 이루는 프로그램입니다.)

 

아래의 명령어를 순서대로 입력합니다.

 

mkdir /etc/loki
cd /etc/loki

wget https://github.com/grafana/loki/releases/download/v2.4.2/promtail-linux-amd64.zip
unzip promtail-linux-amd64.zip
chmod a+x promtail-linux-amd64

rm -rf promtail-linux-amd64.zip
mv promtail-linux-amd64 promtail

wget https://raw.githubusercontent.com/grafana/loki/main/clients/cmd/promtail/promtail-local-config.yaml

 

GitHub - grafana/loki: Like Prometheus, but for logs.

 

GitHub - grafana/loki: Like Prometheus, but for logs.

Like Prometheus, but for logs. Contribute to grafana/loki development by creating an account on GitHub.

github.com

 

릴리스 페이지에 보시면 버전이 있습니다.

 

그 버전으로 다운로드해주세요.

 

작성 시점에는 'v2.4.2' 버전입니다.

 

그리고 서버의 CPU 도 체크하셔야합니다.

 

이제 promtail 을 서비스로 만들어봅니다.

 

sudo vi /etc/systemd/system/grafana-loki-promtail.service

 

파일 내용으로는 아래의 내용을 복사해서 붇여넣습니다.

 

[Unit]
Description=Grafana Loki Promtail
Documentation=https://github.com/grafana/loki
After=network-online.target

[Service]
User=root
Restart=always
ExecStart=/etc/loki/promtail --config.file=/etc/loki/promtail-local-config.yaml

[Install]
WantedBy=multi-user.target

 

아래의 명령어를 순서대로 입력합니다.

 

sudo systemctl daemon-reload
sudo service grafana-loki-promtail restart
sudo service grafana-loki-promtail status
sudo systemctl enable grafana-loki-promtail

 

promtail 설치가 끝나면, 이제 Loki 와 연결해주는 설정을 넣어줍니다.

 

sudo vi /etc/loki/promtail-local-config.yaml

 

위의 파일을 엽니다.

 

clients:
#  - url: http://localhost:3100/loki/api/v1/push
  - url: http://{Grafana Loki IP}:3100/loki/api/v1/push

#scrape_configs:
#- job_name: system
#  static_configs:
#  - targets:
#      - localhost
#    labels:
#      job: varlogs
#      __path__: /var/log/*log

scrape_configs:
- job_name: node
  static_configs:
  - targets:
      - localhost
    labels:
      job: nginx
      host: Test
      agent: promtail
      __path__: /var/log/nginx/json_access.log

 

그리고 위의 주석됀 내용을 찾아서 바꿉니다.

(host 의 경우 현재 Test 로 통일하고 있으니, 설정도 Test 입니다. 이건 사용하실걸로 바꿔주세요.)

 

설정을 바꾸었으니, 서비스를 재시작합니다.

 

sudo service grafana-loki-promtail restart

 

성공적으로 재시작을 하였다면, 끝났습니다.

 

이제 Grafana 에서 대시보드를 추가해도록 하겠습니다.

 

 

이번에는 12559 를 입력합니다.

 

Grafana Loki Dashboard for NGINX Service Mesh dashboard for Grafana | Grafana Labs

 

Grafana Loki Dashboard for NGINX Service Mesh dashboard for Grafana

Loki v2+ showcase using JSON NGINX access logs.

grafana.com

 

이번에 사용하는 대시보드는 이것입니다.

 

 

대시보드에 접속하면 위의 이미지처럼 엄청난 오류가 뜨는데..

 

정상입니다.

 

Label Name 이 선택돼지 않아서 그렇습니다.

 

 

host 로 선택해주시면 데이터가 정상적으로 불러와지게 됍니다.

(이건 Grafana Cloud 도 동일합니다.)

 

벌서부터 엄청난 해킹시도가 보이는군요. (웃음..)

 

이걸로 NGINX 를 가지고 모니터링을 하는것은 끝났습니다.

 

이제 MySQL 과 Redis 가 남았네요.

 

참고로 NGINX 는 여러가지가 있고, 그것에 맞는 대시보드가 있기 때문에 서로 맞는것을 사용하셔야합니다.

 

개인적으로는 아래의 것을 사용해보려고 하다가 실패했습니다.

 

GitHub - kubernetes/ingress-nginx: NGINX Ingress Controller for Kubernetes

 

GitHub - kubernetes/ingress-nginx: NGINX Ingress Controller for Kubernetes

NGINX Ingress Controller for Kubernetes. Contribute to kubernetes/ingress-nginx development by creating an account on GitHub.

github.com

 

NGINX Ingress controller dashboard for Grafana | Grafana Labs

 

NGINX Ingress controller dashboard for Grafana

Ingress-nginx supports a rich collection of prometheus metrics. If you have prometheus and grafana installed on your cluster then prometheus will already be scraping this data due to the scrape annotation on the deployment.

grafana.com

 

근데 나중에 찾은 access.log 로 쓰는게 더 좋아보여서..

 

결과적으로는 만족.

Posted by Pure Ani

RE:D Cherish! -Eternity Blood- CRYSTALiA

放課後シンデレラ2 HOOKSOFT

花鐘カナデ*グラム NanaWind

フタマタ恋愛 ASa Project

スタディ§ステディ2 ま~まれぇど

リンパにATATA! ~メス牡蠣ミルクどぴゅらっしゅ~ Hending

創作彼女の恋愛公式 Aino+Links

流星ワールドアクター Heliodor

Secret Agent~騎士学園の忍びなるもの~ ensemble

天冥のコンキスタ エウシュリー

HaremKingdom -ハーレムキングダム- SMEE

ラズベリーキューブ まどそふと

ノラと皇女と野良猫ハート2 -Nora, Princess, and Crying Cat.- HARUKAZE

『ノラと皇女と野良猫ハート2』応援中♪

ピュアソングガーデン PULLTOP

はにデビ! Honey&Devil eufonie

姫繰三六五 HIMEKURI365

姫繰三六五 公式ウェブサイト

はるるみなもに! クロシェット

死に逝く君、館に芽吹く憎悪 バグシステム

Sanguinea-サングイネア- すにぃる

麗華の館 しすたーそふと

カスタムメイドオンライン KISS