EC2 서버에 접속해서 다음 명령어로 nginx를 설치한다.
sudo apt update -y
sudo apt upgrade -y
sudo apt autoremove -y
sudo apt install nginx -y
-h 명령어로 nginx 명령어 사용법을 확인한다.
sudo nginx -h
sudo nginx
실행한 뒤에, $host:$port
로 웹브라우저로 접속하면 다음과 같은 화면이 나와야한다.
다음과 같은 에러 메세지가 나온다면, 해당 포트(default 80)을 사용중이다.
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error)
nginx: [emerg] bind() to [::]:80 failed (98: Unknown error)
이경우 다음 명령어로 포트를 어떤 프로세스가 사용하고 있는지 확인한다.(이미 nginx가 실행되고 있는 경우도 있다.)
sudo ss -tulpn | grep LISTEN
Process State 확인
ps -ax | grep nginx
PID와 부모자식 관계 확인
ps -ef --forest | grep nginx
-s옵션에 signal을 전달하는 방식으로 컨트롤한다.
sudo nginx -s $signal
다음 signal을 사용할 수 있다.
stop
— fast shutdown. 즉시 종료.quit
— graceful shutdown. 현재 맺어진 connection에 대한 요청은 모두 완료 후에 종료reload
— reloading the configuration file. 변경된 설정 파일을 적용한다.reopen
— reopening the log files. 로그 로테이션 설정을 하지 않아서, nginx로그가 하나의 파일에 너무 많이 쌓였을 때, 이 명령으로 파일 분리를 할 수 있다.기본 설정파일(Linux): /etc/nginx/nginx.conf
설정파일들의 묶음 디렉토리: /etc/nginx/conf.d
XXX.d
는 XXX 파일을 여러개 묶어놓은 directory 라는 의미의 convention이다.command의 parameter로 특정 conf 파일을 명시할 수 있다.
sudo nginx -c $your_file_location
guide
설정 명령어는 명령어 이름, 파라미터, 구분자로 구성된다.
한줄로 끝나는 명령어는 ;
세미콜로을 구분자로 사용한다.
여러 줄로 구성되는 명렁어는 {}
중괄호 블록을 구분자로 사용한다.
예
http {
server {
location / {
root /data/www;
}
location /images/ {
root /data;
}
}
}
하나의 nginx.conf 파일보다 여러개의 파일을 사용하는 경우가 많다.
/etc/nginx/nginx.conf
에는 가장 기본설정만 위치시키고, /etc/nginx/conf.d
에 주제나 목적별로 파일을 분리해서 여러개 위치시키는 것이 관리하기 좋다.
-t
옵션으로 syntax 와 내용의 validation을 할 수 있다.
sudo nginx -t
하나의 conf 파일로 설정을 관리하면 설정파일이 너무 커진다. 파일안의 내용이 너무 길면 읽기도 어려울 뿐만 아니라 수정할 때 버그가 발생할 확률이 높아진다. NGINX의 다양한 기능을 활용할수록 설정파일을 주제나 목적에 따라 분리해서 관리할 필요가 있다.
root 가 되는 nginx.conf 파일에 include 문을 이용해서 다른 설정파일들을 include 할 수 있다.
include의 순서대로 뒤에 이어붙는다고 생각하면 된다.
다음은 conf.d 내부에서 모듈별로 conf 파일과 디렉토리를 구성한 예시이다.
conf.d/
├── private-service.conf # include /etc/nginx/conf.d/private-service.conf.d/*.conf
├── private-service.conf.d
│ ├── internal-api.conf
│ └── internal-gateway.conf
├── public-service.conf # include /etc/nginx/conf.d/public-service.conf.d/*.conf
├── public-service.conf.d
│ ├── public-api.conf
│ └── public-gateway.conf
└── static.conf
conf.d 외에도 sites-enabled, sites-available 등의 디렉토리에 conf 파일들을 모아놓기도 하지만, 특별한 이유가 없다면 conf.d 하나에 통일해서 모아놓는 것을 추천한다. conf.d는 사실상의 약속 같은 것이어서 어느 개발자가 서버에 접속하더라도 하나의 디렉토리 안에서 설
정파일을 추적할 수 있기 때문이다.
npm 설치, node 자동설치
sudo apt install npm -y
mkdir ~/node
cd ~/node
npm install express
server.js 에 서버별로 다른 응답을 하도록 nodejs app을 작성한다.
vi server.js
1번 서버
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/user', function (req, res) {
var time = new Date().toLocaleTimeString().substring(0,8)
console.log("API call /user at " + time)
res.end(JSON.stringify({ "user": "user1", "time": time }))
})
app.get('/customer', function (req, res) {
var time = new Date().toLocaleTimeString().substring(0,8)
console.log("API call /customer at " + time)
res.end(JSON.stringify({ "customer": "customer1", "time": time }))
})
var server = app.listen(9000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
2번 서버
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/user', function (req, res) {
var time = new Date().toLocaleTimeString().substring(0,8)
console.log("API call /user at " + time)
res.end(JSON.stringify({ "user": "user2", "time": time }))
})
app.get('/customer', function (req, res) {
var time = new Date().toLocaleTimeString().substring(0,8)
console.log("API call /customer at " + time)
res.end(JSON.stringify({ "customer": "customer2", "time": time }))
})
var server = app.listen(9000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
application background로 실행시키기
nohup node server.js > server.log 2>&1 & echo $! > run.pid
application 종료
kill -9 $(cat run.pid) && rm run.pid
log tracking
tail -f server.log