카테고리 없음

Server - 3 (Web Server & Web Application Server(WAS), Reverse Proxy)

팅탱팅탱 2024. 4. 2. 08:59

미리 정해진 (정적인) 콘텐츠를 준비해두고 요청이 오면 응답으로 주는 것이 아닌 요청이 올때마다 해당 요청에 적절한 컨텐츠를 만들기(동적인) 위해서는 WAS가 필요합니다.

클라이언트 요청에 대한 적절한 데이터를 만들어 주는 서버를 Web Application Server(WAS = nodejs , Spring Boot)라고 합니다.

 

포트번호 , IP주소를 통해 식별된 컴퓨터의 프로세스를 찾아서 데이터를 송신합니다.

aws설정시 보안그룹에서 TCP 80번 포트를 열어준 이유는 EC2의 아이피 주소를 통해 EC2를 식별 후 80번 포트로 열린 Web Server(nginx)로 요청을 보내기 위함이였습니다.

웹 브라우저에서 ip주소를 입력하면 자동으로 80번 포트가 붙어서 nginx에 요청이 간 후 응답이 온 것입니다.

(웹 브라우저는 43.201.245.2 → 43.201.245.2:80 으로 요청을 보냄)

 

그렇다면 ip주소로 연결했을때 바로 nginx화면이 나오는걸 볼 수 있는데

개발자 도구를 열어 확인해보면 html 문서라는 걸 알 수 있습니다.

nginx가 요청에 대해서 정적인 컨텐츠(미리 준비해둔 html)를 준 걸 볼 수 있습니다.

 

그럼 어떤 경우에는 a 컨텐츠를 주고 어떤 경우에는 b 컨텐츠를 주는지 알아보도록 하겠습니다.

 

NGINX에서의 정적컨텐츠 호스팅

 

nginx에는 설정 파일이 있고 웹 서버가 실행될때 이 설정 파일을 읽으면서 실행이 됩니다.

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

 

root /var/www/html; -> root는 정적인 콘텐츠를 찾는 시작 디렉토리를 의미합니다.

index index.html index.htm index.nginx-debian.html; -> index는 기본적인 요청에 대해서 index뒤에 파일들을 찾아서 웹상으로 보여 준다는 것이며 실제로 파일경로로 이동하여서 있는 파일들을 보면 index.nginx-debian.html 파일이 있는것이 확인이 가능합니다.

파일의 내부를 살펴보면

<!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>

 

아까 봤던 정적인 콘텐츠인 html파일인 것을 확인 할 수 있습니다.

(처음 80번 포트로 요청을 보냈을 때 응답으로 오는 html 문서임을 확인 가능합니다)

 

정리해서 root /var/www/html를 통해 정적 컨텐츠를 찾아낼 시작 디렉토리를 설정하고 index를 통해 기본 요청이 올 경우 어떤 파일을 줄지 설정하여 요청에 대해서 /var/www/html/index.nginx-debian.thml를 응답값으로 준 것을 알 수 있습니다.

 

nginx 설정 파일에서의 location 블록

/etc/nginx/sites-available/default에 아래와 같은 블록을 추가해봅시다.

location /temp{
                root /var/www;
                index temp.html
                try_files $uri $uri/ =404;
        }

 

인텔리제이에서 브라우저 리모트 호스트를 통하여 원래 만들어뒀던 탄력적 ip주소와 연결 후 nginx를 깔고 난후 저 경로로 이동하게된다면 위에 나와있는 코드처럼 파일이 보입니다(명령어: cat default)

만약 보인다면 그 후 default파일을 수정해주어야하는데 이때 리눅스 편집기를 사용할때의 문법을 사용하셔야합니다.

sudo vi default라는 명령어를 실행 후 i키를 눌러 파일편집을 해줍니다 그 후 :wq 명령어를 입력하여 저장 후 나와줍니다.

저장이 잘되었는지 확인을 하기 위해 cat default를 통하여 다시한번 확인해줍니다.

그 후 /var/www로 이동하여 nginx 설정이 변경되었으니 sudo systemctl restart nginx를 통하여 최신화 해줍니다.

다음으로 sudo mkdir temp 명령어를 통하여 temp 디렉토리를 생성 후 sudo vi temp.html를 통하여 html파일을 만듬과 동시에 열어줍니다.

아까와 같은 방법으로 파일편집을 통하여

<h1> hi im kimtaeyoung! <h1>

를 넣어준후 저장해줍니다.

그 후 탄력적 ip에/temp를 붙여서 경로를 이동해주면 작성된 html 파일이 나오는걸 볼 수 있습니다.

 

동작 원리

location /temp{
                root /var/www;
                index temp.html
                try_files $uri $uri/ =404;
        }

위 설정은 /temp요청에 대해서 아래 중괄호 속 내용과 같이 하라는 뜻입니다.

root /var/www라는 말은 /temp 앞에 /var/www을 붙여서 /var/www/temp 디렉토리에서 정적 파일을 찾아라라는 뜻입니다.

 

쉽게 설명하자면

location /y{
	root /x
}

/y로 오면 /x/y에서 파일을 찾으라는 것입니다.

추가로 붙혀져있는 index temp.html은 기본적으로 /temp요청이 올 경우 index뒤에 파일을 찾아서 응답을 리턴하라는 말입니다.

 

그럼 temp파일에 sudo vi test.html파일을 생성하고 아무 html 언어로 쓴후 저장하면 어떻게될까요?

ip/temp/test.html이라고 하면 그 파일이 나오게됩니다.

 

WAS(Web Server Application)

 

어떻게 was는 웹서버와 같이 동작이될까?

노드, 스프링 모두 was입니다. 

그런데 우리가 원하는 모습은 아래와 같습니다.

냅다 바로 노드 혹은 스프링을 실행시켜버리면 웹서버가 없는 모습이 됩니다.

 

Reverse Proxy

리버스 프록시는 컴퓨터 네트워크에서 사용되는 개념으로, 클라이언트와 서버간 통신을 중계하고 보안, 성능 개선등의 목적을위해 중간에 위치하는 서버를 말합니다.

프록시 서버 자체는 대리자로써 클라이언트의 요청을 받고 본 서버로 보내줍니다. 

여기서 서버는 한번 서버로써 요청을 받기만 하는건 아닙니다.

서버 프로세스가 내부적으로 connect() 시스템 콜과 같은 요청을 보내는 시스템 콜을 통하여 다른 서버 프로세스에게 다시 요청을 보낼 수 있습니다.

 

그렇다면 기존 nginx 설정파일을 아래와 같이 변경해봅시다.

location / {
                proxy_pass http://localhost:3000; <- 프록시 설정
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

이 설정은 /요청에 대해서 우선적으로 프록시로써 요청을 건내주도록 했습니다.

이때 localhost:3000, 즉 내부 컴퓨터의 3000번 포트의 프로세스로 요청을 보내도록 되어있기에 이는 리버스 프록시라고 볼 수 있습니다.

nginx의 설정을 바꿨으니 다시 업데이트 명령어를 실행시켜준후 

ip주소로 이동한다면 502 badgateway가 뜨게됩니다.

현재 3000번 포트를 가진 프로세스가 없기때문에 당연합니다.