sudo getenforce # enforce 상태 확인.
sudo setenforce 0 # enforce 상태 변경. (끄기)
📌 selinux 영구적으로 끄는 법
# 파일 수정.
sudo vi /etc/selinux/config
# 이 항목을 찾는다.
SELINUX=enforcing
# 다음과 같이 변경.
SELINUX=disabled
# 시스템 재부팅.
sudo reboot
# 적용되었는지 확인.
sestatus
커널 sysctl 수정 (소켓 maxconn 셋팅값 수정.) -> maxconn 값은 상황에 따라 수정 가능
# maxconn 상태 조회.
sudo sysctl -a | grep net.core.somaxconn
# maxconn 상태 수정.
sudo /sbin/sysctl -w net.core.somaxconn=4096
---
net.core.somaxconn = 65535
port 체크
sudo netstat -nltup
시스템 업데이트 및 필수 패키지 설치
sudo dnf update -y
sudo dnf install -y curl wget tar gcc-c++ make
Nginx 셋팅 (version : 1.26.2)
# 필요한 패키지 설치
sudo dnf install -y gcc pcre-devel zlib-devel make openssl-devel
# Nginx 소스 다운로드
wget https://nginx.org/download/nginx-1.26.2.tar.gz
# 압축 해제 및 설치
tar -zxvf nginx-1.26.2.tar.gz
cd nginx-1.26.2
# Nginx 컴파일 및 설치
./configure
make
sudo make install
# Nginx 실행 확인
/usr/local/nginx/sbin/nginx -v
Nginx 환경변수 설정
vi ~/.bashrc # 해당 파일에 아래와 같은 내용 추가.
export PATH=$PATH:/usr/local/nginx/sbin
source ~/.bashrc # 적용.
nginx -v # 확인.
# nvm 설치
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
source ~/.bashrc
# nvm으로 Node.js 16.20.2 설치
nvm install 16.20.2
nvm use 16.20.2
# 설치된 Node.js 버전 확인
node -v
npm -v
NPM 8.19.4 설치
#### 위에서 버전이 나오면 따로 설치 안해도 됨.
npm install -g npm@8.19.4
# 설치된 NPM 버전 확인
npm -v
PM2 5.4.2 설치
npm install -g pm2@5.4.2
# PM2 버전 확인
pm2 -v
PM2 사용법
# 애플리케이션 시작
pm2 start app.js
# 모든 애플리케이션 목록 확인
pm2 list
# 애플리케이션 로그 확인
pm2 logs
# 애플리케이션 재시작
pm2 restart app
# PM2 상태 저장 (서버 재부팅 시 자동 시작)
pm2 save
pm2 startup
## 여러개의 IP 등록 할때..
if ($remote_addr = "1.1.1.1") {
set $cors_origin $http_origin;
}
if ($remote_addr = "2.2.2.2") {
set $cors_origin $http_origin;
}
if ($http_origin = "허락할도메인") {
set $cors_origin $http_origin;
}
location / {
uwsgi_pass ;
# 서버가 uwsgi를 쓴다면 필요할 수도..
uwsgi_hide_header Access-Control-Allow-Origin;
uwsgi_hide_header Access-Control-Allow-Methods;
uwsgi_hide_header Access-Control-Allow-Headers;
uwsgi_hide_header Access-Control-Allow-Credentials;
set $cors_origin "";
if ($remote_addr = "허락할 특정IP") { # 필요없으면 이 블럭 빼면 됨.
set $cors_origin $http_origin;
}
if ($http_origin = "허락할 domain") { # 필요없으면 이 블럭 빼면 됨.
set $cors_origin $http_origin;
}
add_header 'Access-Control-Allow-Origin' "$cors_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Allow-Origin' "$cors_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Max-Age' 3600;
add_header 'Content-Length' 0;
add_header 'Content-Type' text/plain;
return 204;
}
}
location /route {
allow ip; # 특정 IP
deny all; # deny 정책
}
⛺️ 옵션 설명
🚀 Access-Control-Allow-Origin
어떤 웹사이트에서 API를 요청할 수 있는지 지정, 이게 없으면 브라우저 차단 당한다.
🚀 Access-Control-Allow-Methods
어떤 HTTP 요청 종류를 허용할지 지정
🚀 Access-Control-Allow-Headers
브라우저가 보낼 수 있는 요청 헤더를 허용한다. 예를 들어, 클라이언트가 JWT 토큰을 담기 위해 Auth 헤더를 쓸 때, 서버가 이걸 허용해주지 않으면 요청 자체가 막힌다.
Content-Type도 없으면 Application/json 같은 것도 막힌다.
🚀 Access-Control-Allow-Credentials
“쿠키, 인증정보도 같이 보내도 돼”를 허용
브라우저에서 withCredentials: true를 사용하는 요청이 있으면 이 설정이 필수다.
예: 로그인 상태 유지용 쿠키, 토큰 등을 브라우저가 같이 보내려면 이게 있어야 한다.
🚀 Access-Control-Max-Age
브라우저가 CORS 체크 결과를 얼마나 오래 기억할지 설정(초 단위)
브라우저는 1시간 동안은 또 다시 OPTIONS 요청을 보내지 않고, 캐시된 정보를 쓴다.
# 버전 확인 (예: 2.9.4)
VERSION="2.9.4"
# 바이너리 다운로드 및 압축 해제
wget https://github.com/grafana/loki/releases/download/v${VERSION}/promtail-linux-amd64.zip
unzip promtail-linux-amd64.zip
chmod +x promtail-linux-amd64
sudo mv promtail-linux-amd64 /usr/local/bin/promtail
✅ Config 파일 작성
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /var/log/positions.yaml
clients:
- url: http://localhost:3100/loki/api/v1/push # Loki 주소로 입력해야 함.
scrape_configs:
- job_name: system
static_configs:
- targets:
- localhost
labels:
job: varlogs # QL 에서 잡을 job 이름.
__path__: /var/log/*.log # 수집할 로그 파일
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets: ["localhost:9093"]
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files: ["alert.rules.yml"]
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "node"
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ["ip:9100"]
node exporter 설치 및 압축풀기
# node_exporter 설치.
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
# 파일 압출 풀기.
tar xzvf node_exporter-1.7.0.linux-amd64.tar.gz
node_exporter 실행
./node_exporter
# 백그라운드 실행
./node_exporter &
🧱 Grafana를 이용해서 서버 리소스 알림
이렇게 Grafana에 접속한 후,
alerting에 들어간다.
alerting에 3가지가 나오는데, 먼저 alert rules를 작성해야 한다.
나는 CPU, Disk, RAM 이렇게 3가지를 모니터링을 할 것이다.
CPU 설정법
CPU
DISK 설정법
RAM 설정법
나머지는 CPU 설정법과 동일하다. 이미지 보고 참고 바란다.
contact Points 에서 Telegram 사용
이렇게 텔레그램으로 알림을 줄 수 있게 만들어 주면 된다.
Notification Templates 설정
template 제목
monitoring-templete
template 코드
{{ define "monitoring-template" }}
*********** {{ .Status }} ***********
{{ range $key, $value := .CommonLabels }}
{{$key}}: {{$value}}
{{ end }}
{{ range .Alerts.Firing }}
{{ if gt (len .Annotations) 0 }}
{{ index .Annotations.Values 0 }}
{{ end }}
{{ end }}
{{ end }}
# 자신의 쓸 알람 스타일에 맞게 변형해서 쓰면 된다.
쿠버네티스 버전 1.24.0 이전이면, 도커와 쿠버네티스가 연동되는 dockershim이 있었지만, 1.24.0 버전 이후에는 따로 설정을 해줘야 함.
docker를 설치한 후,
도커 데몬 설정
#/etc/docker 디렉토리 없을 경우 생성
sudo mkdir /etc/docker
#daemon.json 파일 추가
sudo cat <<EOF | sudo tee /etc/docker/daemon.json
{
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
},
"storage-driver": "overlay2"
}
EOF
cgroup(runc) 옵션 설정
#containerd 구성 파일 생성
sudo mkdir -p /etc/containerd
#containerd 기본 설정값으로 config.toml 생성
sudo containerd config default | sudo tee /etc/containerd/config.toml
#config.toml 파일 수정
vi /etc/containerd/config.toml
# cgroup driver(runc) 사용하기 설정
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
SystemdCgroup = true
#수정사항 적용 및 재실행
sudo systemctl restart containerd
docker 재시작
#도커 재시작
sudo service docker restart
#도커 상태 조회
sudo service docker status