본문 바로가기
AWS Cloud School 8기/서버가상화_클라우드 이미지

3-Tier Architecture (3계층 아키텍처)/ Reverse Proxy (리버스 프록시)

by YUNZEE 2025. 2. 6.
728x90

📌 3-Tier Architecture (3 계층 아키텍처)란?

https://velog.io/@yeavov/3%EA%B3%84%EC%B8%B5-%EA%B5%AC%EC%A1%B03-Tier-Architecture

3-Tier Architecture(3 계층 아키텍처) 소프트웨어 시스템을 3개의 계층(Layer)으로 분리하여 구성하는 설계 방식임.
서버의 역할을 프레젠테이션(웹), 비즈니스 로직, 데이터베이스로 나누어 관리하는 방식

🔹 즉, 웹사이트나 애플리케이션을 만들 때 기능을 분리해서 관리하는 구조!

 

✅ 3 계층 구조의 구성 요소

🔹 1. 프레젠테이션 계층 (Presentation Layer) - 클라이언트 (사용자 인터페이스)

➡ 사용자와 직접 상호작용하는 부분
➡ 웹 브라우저, 모바일 앱, 데스크톱 애플리케이션
➡ HTML, CSS, JavaScript, React, Vue.js 등
 예제: 웹사이트 화면, 모바일 앱 UI


🔹 2. 애플리케이션(비즈니스 로직) 계층 (Application Layer) - 서버 (백엔드)

➡ 실제 데이터 처리 및 로직 수행
➡ 클라이언트 요청을 처리하고, 데이터베이스와 연결
➡ Python, Java, Node.js, PHP, Spring 등
 예제: 로그인 인증, 데이터 검증, API 서버


🔹 3. 데이터베이스 계층 (Database Layer) - 저장소 (DB)

➡ 데이터를 저장하고 관리하는 계층
➡ MySQL, PostgreSQL, MongoDB, Oracle DB 등
 예제: 회원정보 저장, 상품 정보 저장

 

✅ 3계층 아키텍처의 장점

 확장성(Scalability) 높음 → 특정 계층만 확장 가능
 보안(Security) 강화 → 직접 DB 접근 없이 서버를 통해 통신
 유지보수 용이 → 역할이 분리되어 관리가 쉬움
 다양한 기술 조합 가능 → 프론트엔드 & 백엔드 독립적으로 개발 가능

 

🚀 클라이언트가 접근 가능한 서버는 결국 web서버까지만 임 = was나 db는 내부에 접근 불가능한 장소에 존재해야 함.

실습

✅ Tomcat(탐캣)이란?

Apache Tomcat(아파치 탐캣)자바 웹 애플리케이션을 실행하는 서버임.

JSP(Java Server Pages)와 서블릿(Servlet)을 실행할 수 있는 웹 서버 역할을 함.

 

탐캣 서버 구축

vm이름 : tomcat , cent7 , 2 core 2GB 20GB , IP : 211.183.3.88

 

자바로 웹페이지(웹앱)를 만들었다면, 이런 웹애플리케이션을 배포하는 웹애플리케이션 서버.

개발환경 구성이 필요하다. JAVA(openjdk-11), tomcat(10 버전)

 

[root@tomcat ~]# yum install -y java-11-openjdk wget unzip

- openjdk11과 wget , unzip을 설치.

 

[root@tomcat ~]# yum install -y java-11-openjdk wget unzi

 

https://tomcat.apache.org/download-10.cgi

 

 

wget  https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.34/bin/apache-tomcat-10.1.34.zip

 

[root@tomcat ~]# unzip apache-tomcat-10.1.34.zip > /dev/null

[root@tomcat ~]# mv apache-tomcat-10.1.34/  tomcat

[root@tomcat ~]# cd tomcat/
[root@tomcat tomcat]# pwd
/root/tomcat

bin: 실행 파일(동작, 중지)

conf: 설정

lib: 라이브러리 모듈

logs: 로그

webapps: 웹애플리케이션 배포 디렉터리  = WAR파일을  이 폴더에 넣으면 Tomcat이 자동으로 압축을 풀고 실행할 준비를 함


[root@tomcat tomcat]# chmod 777 -R /root/tomcat

- tomcat 동작 파일을 실행시키기 위해 모든 권한 부여


[root@tomcat tomcat]# sh ./bin/startup.sh

- sh 실행

- 방화벽을 잘 껐다면 기본 페이지가 잘 보일 것임

[root@tomcat tomcat]# wget https://tomcat.apache.org/tomcat-6.0-doc/appdev/sample/sample.war

- sample.war 파일이 저장됨

 

[root@tomcat tomcat]# mv sample.war /root/tomcat/webapps

- mv 파일을 이동하거나 이름을 변경할 때 사용하는 리눅스 명령

- 여기서는 sample.war 파일을 /root/tomcat/webapps 폴더로 이동하는 역할을 함.


[root@tomcat tomcat]# ls /root/tomcat/webapps/

 

간단한 sample 웹앱을 배포.

 

이번에는 간단한 jsp파일을 배포해 보자.

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
    	<head><title>hello world</title></head>
    	<body>
    	<h2>
            	TOMCAT TEST<br><br>
            	time : <%= new java.util.Date()%>
            	<%@ page import="java.net.InetAddress" %><br>
            	<%InetAddress inet= InetAddress.getLocalHost();%>
            	WAS ip : <%=inet.getHostAddress()%>
    	</h2>
 
 
    	</body>
</html>

- test.jsp로 만들어보자

 

[root@tomcat tomcat]# vi /root/tomcat/webapps/ROOT/test.jsp

- restart 필요 없음

- tomcat 중지

- tomcat 실행

- 이 catalina.sh 파일임. 하지만 이 파일을 직접 실행시키지 않는 이유는 foreground로 동작하기 때문임

- 나중에 컨테이너 환경에서는 반드시 foreground로 동작시켜야 하는 경우가 발생함 

 

DB 구축

vm이름 : dbdb , cent7 , 2 core 2GB 20GB , IP : 211.183.3.6

 

[root@dbdb ~]# yum install -y mariadb-server

 

[root@dbdb ~]# systemctl restart mariadb

[root@dbdb ~]# systemctl enable mariadb

[root@dbdb ~]# mysql_secure_installation

[root@dbdb ~]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] 123^H^H^H
Set root password? [Y/n] y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] n
 ... skipping.

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

 

 

MariaDB [(none)]> create database tomcatdb ;

 

MariaDB [(none)]> grant all privileges on tomcatdb.* to tomcatuser@'%' identified by '1234';

 

톰캣서버로 돌아가서 mysql 명령어 설치 후 db접속이 되는지 확인

 

[root@tomcat tomcat]# yum install -y mysql

- mysql 명령어 설치

 

[root@tomcat tomcat]# mysql -u tomcatuser -p1234 -h 211.183.3.6

- db 접속 확인

cat <<EOF > dbtest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<h1>DB</h2>
<%
        Connection conn=null;
        try{
                String Url="jdbc:mysql://<DB주소>/<DB이름>";
                String Id="<DB유저>";
                String Pass="<유저암호>";

                Class.forName("com.mysql.jdbc.Driver");
                conn=DriverManager.getConnection(Url,Id,Pass);
                out.println("was-db Connection Success!");
        }catch(Exception e) {
                e.printStackTrace(); 
}
%>

EOF

내용 수정 전

cat <<EOF > dbtest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<h1>DB</h2>
<%
        Connection conn=null;
        try{
                String Url="jdbc:mysql://211.183.3.6/tomcatdb";
                String Id="tomcatuser";
                String Pass="1234";

                Class.forName("com.mysql.jdbc.Driver");
                conn=DriverManager.getConnection(Url,Id,Pass);
                out.println("was-db Connection Success!");
        }catch(Exception e) {
                e.printStackTrace(); 
}
%>

EOF

내용 수정 후

 

- 자바로 DB에 연동하기 위해선 jdbc라이브러리가 필요함

 

[root@tomcat tomcat]# mv dbtest.jsp /root/tomcat/webapps/ROOT/dbtest.jsp

- 수정을 잘했다면 /root/tomcat/webapps/ROOT 경로로 파일을 옮긴다.

 

https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.23

- jdbc 페이지 경로

wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar

 

 

[root@tomcat tomcat]# mv mysql-connector-java-8.0.23.jar /root/tomcat/lib

- 라이브러리 폴더(lib)에 jdbc 이동

 

[root@tomcat tomcat]# ./bin/shutdown.sh

[root@tomcat tomcat]# ./bin/startup.sh

- 톰캣 재시작.

 

📌Reverse Proxy (리버스 프록시)란?

https://chatgpt.com/c/676fe673-aca0-800a-b6ab-fffccd27821a

📌 클라이언트(사용자)가 직접 원본 서버(백엔드 서버)와 통신하지 않고,
📌 중간에 프록시 서버(리버스 프록시)가 요청을 받아 대신 전달해 주는 방식임

 

Reverse Proxy를 사용하는 이유
보안 강화: 백엔드 서버의 IP를 숨겨 보호
로드 밸런싱: 여러 서버에 요청을 분산
캐싱: 자주 요청되는 콘텐츠를 캐싱하여 성능 향상
SSL 처리: SSL/TLS 암호화를 프록시 서버에서 처리

📌 예시

사용자가 http://example.com에 요청을 보낼 때,
리버스 프록시가 이를 받아 백엔드 서버(http://backend.local:8080)로 전달해 줌.
사용자는 백엔드 서버의 존재를 모름.

사용자 → 리버스 프록시 → 백엔드 서버 (진짜 웹 서버)
 

📌Forward Proxy vs Reverse Proxy 비교

 

그럼 정방향 프록시는 벡엔드 서버를 보안하지 못할까?

- 벡엔드 서버를 직접 보호하지는 못함

-> 정방향 프록시는 클라이언트 보안을 강화하는 역할을 하지만, 벡엔드 서버의 보안 강화에는 적합하지 않음

그리고 리버시 프록시는 백엔드 서버 앞단에서 동작하면서 백엔드 서버를 보호하는 기능을 함

 

WEB 구축

VM이름 : web , cent7 2 core 2GB 20GB , IP : 211.183.3.80 /24

- tomcat 서버에서 db가 잘 연동되는지만 확인

 

[root@web ~]# yum install -y httpd

- apache 설치

 

[root@web ~]# systemctl restart httpd

[root@web ~]# systemctl enable httpd

- 동작

 

[root@web ~]# echo 'static file' > /var/www/html/index.html

- 인덱스 파일 생성

 

[root@web ~]# vi /etc/httpd/conf/httpd.conf

- 리버스 프록시 설정을 위해 httpd.conf 파일을 수정.

LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

<VirtualHost *:80> # 80번 포트로 들어오는 모든 ip에 대한 설정
    ProxyRequests Off
    ProxyPreserveHost On
    <Proxy *> 
        Order deny,allow
        Allow from all #모든 클라이언트 대상
    </Proxy>

    ProxyPass /jsp http://211.183.3.88:8080/ # /jsp: web서버의 경로/ 211.183.3.88:8080: was의 경로
    ProxyPassReverse /jsp http://211.183.3.88:8080/
</VirtualHost>

- 누군가 웹서버의 /jsp 경로로 들어오면, 그 요청을 211.183.3.88:8080 로 전달

57~ 59 안에 있는 내용 (= 필요한 모듈) 위에 56번 안으로 넣어줌

56: 라이브러리폴더

ProxyPass (프록시 패스)란?

📌 요청을 특정 백엔드 서버로 전달하는 역할을 함.
📌 주로 Apache에서 mod_proxy 모듈을 사용할 때 적용됨.

ProxyPassReverse (프록시 패스 리버스)란?

📌 백엔드 서버에서 클라이언트로 보내는 응답의 헤더를 수정하는 역할.
📌 백엔드 서버가 Location 또는 Redirect 헤더에 원래 주소를 포함할 때,
📌 이를 클라이언트가 인식할 수 있도록 프록시 서버의 주소로 바꿔줌.

 

[root@web-re ~]# systemctl restart httpd
[root@web-re ~]# systemctl enable httpd

- 정적인 요청

- 동적인 요청 

📌정적인 요청과 동적인 요청

 

 

ProxyPassReverse: 응답하는 주체를 tomcat에서 web서버로 변경. (클라이언트가 헷갈리지 않게 하기 위해서)

웹 서버(Web Server)와 애플리케이션 서버(WAS, Web Application Server)의 역할을 구분하면 정적 요청은 웹 서버(Web Server)에서 처리하고, 동적 요청은 WAS(Tomcat)에서 처리함

- 만약 위에 정적인 요청과 동적인 요청을 했는데 웹페이지가 안 보인다면 그것은 tomcat에 문제가 있는 것임 문제를 잘 찾고 해결할 수 있는 사람이 되길 바람 (저도 그러고 싶어요...)

 

오케이! 파이팅! 할 수 이따!

728x90

'AWS Cloud School 8기 > 서버가상화_클라우드 이미지' 카테고리의 다른 글

web + db + tomcat 실습(코드만)  (3) 2025.02.06
Proxy[정방향 프록시 (Forward Proxy)], SSH  (0) 2025.02.05
VM 8 + DNS + DB + WP 실습(코드만)  (0) 2025.02.03
WordPress  (2) 2025.01.31
LVM  (0) 2025.01.31