[웹서버로 콘텐츠 구분해서 서빙하기] NGINX 시작하기

Hyunjun Kim·2025년 5월 16일
0

Data_Engineering

목록 보기
73/153

2 NGINX 시작하기

2.1 NGINX 설치와 기본 명령어

2.1.1 설치

EC2 서버에 접속해서 다음 명령어로 nginx를 설치한다.

sudo apt update -y
sudo apt upgrade -y
sudo apt autoremove -y
sudo apt install nginx -y
  • upgrade 도중 kernel 업그레이드가 필요하다고 나온다면, yes 를 선택하고, restart 대상 package 를 선택해야한다는 창이 나오면 모두 선택한 뒤 OK를 누른다.
    • 방향키, 스페이스, 탭, 엔터로 이동과 선택이 가능하다.

-h 명령어로 nginx 명령어 사용법을 확인한다.

sudo nginx -h

2.1.2 실행

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

2.1.3 상태확인

Process State 확인

ps -ax | grep nginx

PID와 부모자식 관계 확인

ps -ef --forest | grep nginx

2.1.4 상태 변경

-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로그가 하나의 파일에 너무 많이 쌓였을 때, 이 명령으로 파일 분리를 할 수 있다.

2.2 NGINX 설정하기

2.2.1 설정파일의 위치

기본 설정파일(Linux): /etc/nginx/nginx.conf
설정파일들의 묶음 디렉토리: /etc/nginx/conf.d

  • XXX.d 는 XXX 파일을 여러개 묶어놓은 directory 라는 의미의 convention이다.

command의 parameter로 특정 conf 파일을 명시할 수 있다.

sudo nginx -c $your_file_location

2.2.2 설정 파일 형식

guide
설정 명령어는 명령어 이름, 파라미터, 구분자로 구성된다.
한줄로 끝나는 명령어는 ; 세미콜로을 구분자로 사용한다.
여러 줄로 구성되는 명렁어는 {} 중괄호 블록을 구분자로 사용한다.

http {
	server {
		location / {
			root /data/www;
		}

		location /images/ {
			root /data;
		}
	}
}

2.2.3 설정파일의 기본 구성

하나의 nginx.conf 파일보다 여러개의 파일을 사용하는 경우가 많다.
/etc/nginx/nginx.conf 에는 가장 기본설정만 위치시키고, /etc/nginx/conf.d 에 주제나 목적별로 파일을 분리해서 여러개 위치시키는 것이 관리하기 좋다.

2.2.4 설정 validation

-t 옵션으로 syntax 와 내용의 validation을 할 수 있다.

sudo nginx -t

2.2.5 설정파일 분리해서 모듈별로 관리하기

하나의 conf 파일로 설정을 관리하면 설정파일이 너무 커진다. 파일안의 내용이 너무 길면 읽기도 어려울 뿐만 아니라 수정할 때 버그가 발생할 확률이 높아진다. NGINX의 다양한 기능을 활용할수록 설정파일을 주제나 목적에 따라 분리해서 관리할 필요가 있다.

root 가 되는 nginx.conf 파일에 include 문을 이용해서 다른 설정파일들을 include 할 수 있다.

  • 파일을 지정할 수 있다.
  • 디렉토리를 지정할 수 있다.
  • 파일이름에 asterisk()를 넣어 여러개를 지정할 수 있다. (e.g. myconf-*.conf)

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는 사실상의 약속 같은 것이어서 어느 개발자가 서버에 접속하더라도 하나의 디렉토리 안에서 설
정파일을 추적할 수 있기 때문이다.

2.3 실습 세팅

  1. AWS에서 두 개의 EC2 서버를 발급한다.
  2. 각각의 서버에 아래 nodejs 서버 세팅을 한다.
    • node 는 java와 다르게 컴파일 안 해도 실행할 수 있는 편의성 때문에 사용.

2.3.1 nodejs 설치하기

npm 설치, node 자동설치

sudo apt install npm -y

2.3.2 실습용 directory 세팅

mkdir ~/node
cd ~/node
npm install express

2.3.3 server app

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)
})
  • 저장 후 종료(wq)

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
profile
Data Analytics Engineer 가 되

0개의 댓글