서버 아키텍쳐 중 가장 기본적인 3-tier-architecture를 어떻게 구성하고 설치하는지의 흐름을 이해한다.
구분 | 네트워크 대역 | CPU | Memory |
---|---|---|---|
nginx-1 | 192.168.122.101/24 | 1 Core | 1024MB |
tomcat-1 | 192.168.122.11/24 | 1 Core | 1024MB |
tomcat-2 | 192.168.122.12/24 | 1 Core | 2048MB |
mariadb-1 | 192.168.122.201/24 | 1 Core | 1024MB |
selinux는 모두 disabled로 진행
> vi /etc/sysconfig/selinux
...
# SELINUX=enforcing
SELINUX=disabled
...
firewalld-cmd 방화벽 서비스 사용
> systemctl enable firewalld-cmd
> systemctl start firewalld-cmd
VM 셋팅
> vagrant init
> vagrant up
VM으로 SSH접속
> vagrant ssh nginx-1
> vagrant ssh tomcat-1
> vagrant ssh tomcat-2
> vagrant ssh mysql
# OpenSSL version mismatch. Built against 100020ef, you have 1000106f
# 오류발생 시 아래의 방법으로 SSH 접속한다.
> vagrant ssh-config > vagrant-ssh
> ssh nginx-1 -F vagrant-ssh
> ssh tomcat-1 -F vagrant-ssh
yum repo추가
> cat >> /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
nginx 설치
> yum install -y nginx
웹포트 방화벽 등록
> firewall-cmd --permanent --add-service=http
> firewall-cmd --reload
> firewall-cmd --list-all
nginx 시스템 등록 및 시작
> systemctl start nginx
> systemctl enable nginx
tomcat에 대한 로컬 도메인 설정
> vi /etc/hosts
...
192.168.122.11 tomcat-1
192.168.122.12 tomcat-2
Openjdk 15 설치
yum install -y wget
wget https://download.java.net/java/GA/jdk15/779bf45e88a44cbd9ea6621d33e33db1/36/GPL/openjdk-15_linux-x64_bin.tar.gz
tar xfz openjdk-15_linux-x64_bin.tar.gz -C /usr/local
tomcat8.5.59 다운로드
wget http://archive.apache.org/dist/tomcat/tomcat-8/v8.5.59/bin/apache-tomcat-8.5.59.tar.gz
tar xfz apache-tomcat-8.5.59.tar.gz -C /usr/local
tomcat 심볼릭링크 생성
cd /usr/local
ln -s apache-tomcat-8.5.59/ tomcat
자바 환경변수 설정
echo -e "JAVA_HOME=/usr/local/jdk-15\nJRE_HOME=/usr/local/jdk-15\nCATALINA_HOME=/usr/local/tomcat\nCLASSPATH=.:/lib/tools.jar:/lib/jsp-api.jar:/lib/servlet-api.jar\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/bin:/bin\nexport JAVA_HOME CLASSPATH PATH CATALINA_HOME JRE_HOME" >> /etc/profile
tomcat의 서비스 생성
cat > /etc/systemd/system/tomcat.service << EOF
[Unit]
Description=tomcat 9
After=network.target syslog.target
[Service]
Type=forking
Environment="JAVA_HOME=/usr/local/jdk-15"
Environment="CATALINA_HOME=/usr/local/tomcat"
User=root
Group=root
ExecStart=/usr/local/tomcat/bin/startup.sh
ExecStop=/usr/local/tomcat/bin/shutdown.sh
[Install]
WantedBy=multi-user.target
EOF
tomcat 서비스 등록 및 시작
systemctl enable tomcat.service
systemctl start tomcat.service
index.jsp 수정
> vi /usr/local/tomcat/webapps/ROOT/index.jsp
<html>
<head>
<title>tomcat-1</title>
</head>
<body>
<h1><font color="red">Session serviced by tomcat</font></h1>
<table aligh="center" border="1">
<tr>
<td>Session ID</td>
<td>5094F7DF7561C6723A4E408951823DC9</td>
</tr>
<tr>
<td>Created on</td>
<td>1611578015823</td>
</tr>
</table>
tomcat-1
</body>
<html>
db의 로컬도메인 추가
> vi /etc/hosts
...
192.168.122.201 db
...
MariaDB 패키지 설치 및 서비스 등록
> yum install -y mariadb-server
> systemctl start mariadb
> systemctl enable mariadb
간단한 보안설정
> mysql_secure_installation
1) DB의 root계정의 패스워드 입력 (설정한게 없으면 그냥 Enter)
Enter current password for root (enter for none):
2) root 계정의 패스워드를 설정
Set root password? [Y/n] y
New password : 패스워드 입력
Re-enter new password : 패스워드 입력
3) 익명의 계정 제거
Remove anoymous users? [Y/n] Y
4) root 계정의 원격 로그인 설정
Disallow root login remotely? [Y/n] Y
5) test 데이터베이스 제거
Remove test database and access to it? [Y/n] Y
6) 권한 테이블 새로고침(Reload)
Reload privilege tables now?[Y/n] Y
DB포트 방화벽에 등록
> firewall-cmd --permanent --add-port=3306/tcp
WAS에서 DB에 접근 할 테이블과 계정 생성
> mysql -u root -p
# devops 테이블 생성
> create database devops;
# shin이라는 계정을 생성하고 192.168.122.xxx 대역에서
# devops테이블에 접근가능 하게 설정함.
> grant all privileges on devops.* to tomcat@'192.168.122.%' identified by 'dkagh1.';
# (선택) localhost에서도 devops테이블에 접근 가능하게 설정
> grant all privileges on devops.* to tomcat@'localhost' identified by 'dkagh1.';
> flush privileges
/etc/nginx/nginx.conf
nginx의 로드밸런싱은 upstream이라는 옵션을 통해 설정할 수 있다.
*nginx는 유료버전을 사용하지 않는 이상 헬스체크가 불가능하다. (따로 API를 만들어야함.)
work_processes
nginx에서 실행가능한 worker 프로세스의 수를 지정한다.
worker_processes auto;
keepalive_timout
한 커넥션을 몇초동안 유지할 것인가를 설정한다.
http {
...
keepalive_timeout 5;
...
}
/etc/nginx/conf.d/tomcat.conf
upstream
블록요청을 넘겨줄 백엔드들을 지정한다.
로드밸런싱 알고리즘은 ip_hash
를 사용하여 동일 IP의 클라이언트 접속에 대해서는 동일 서버로 연결시킨다.
tomcat의 도메인과 포트를 적어준다.
keepalive
를 추가하여 세션을 유지시키는 최대 커넥션 수를 지정한다.
upstream tomcat {
ip_hash;
server tomcat-1:8080;
server tomcat-2:8080;
keepalive 100;
}
server {
listen 80;
server_name web.test.local;
access_log /var/log/nginx/test1.log;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~ \.(css|js|jpg|jpeg|gif|htm|html|swf)$ {
root /usr/share/nginx/html;
index index.html index.html;
}
location ~ \.jsp$ {
proxy_pass http://tomcat;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
nginx의 환경설정 파일의 수정이 완료되었으면 서비스를 재기동 한다.
systemctl restart nginx
[root@nginx-1 html]> curl localhost/index.jsp
<html>
<head>
<title>tomcat-1</title>
</head>
<body>
<h1><font color="red">Session serviced by tomcat</font></h1>
<table aligh="center" border="1">
<tr>
<td>Session ID</td>
<td>E534E3C07AE9343A6CDD593FDD1BD059</td>
</tr>
<tr>
<td>Created on</td>
<td>1611579076966</td>
</tr>
</table>
tomcat-1 # 메시지 확인
</body>
<html>
ip_hash
로 하여서 tomcat-1으로만 요청되는 모습을 확인할 수 있다.아래의 모든 작업은 tomcat VM에서 진행한다.
DB의 데이터를 WAS가 요청해서 사용자에게 제공해줘야 하기 때문에 접근 가능한지 테스트한다.
[root@tomcat-1 ~]> yum install -y mariadb # mysql 접속 테스트를 위해 mariadb 설치
> mysql -h db -u tomcat -pdkagh1.
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| test |
+--------------------+
2 rows in set (0.00 sec)
JSP페이지는 DB에 저장되어 있는 정보를 표현한다. JSP페이지를 이용하여 DB와의 연동을 확인한다.
Java에서 MySQL을 제어하기 위해서는 mysql-connector-java
가 필요하다.
mysql-connector-java
다운로드
> yum install -y mysql-connector-java
jar파일을 tomcat폴더의 /lib 폴더로 복사
> cp /usr/share/java/mysql-connector-java.jar /usr/local/tomcat/lib/
db_test.jsp 파일 생성
> vi /usr/local/tomcat/webapps/ROOT/**de_test.jsp**
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>tomcat-1</title> # was마다 다르게 title을 설정한다.
</head>
<body>
<%
String DB_URL = "jdbc:mysql://db:3306/test"; # DB호스트와 테이블을 정의
String DB_USER = "tomcat"; # 위에서 생성한 DB유저
String DB_PASSWORD = "dkagh1."; # 패스워드
Connection conn;
Statement stmt;
PreparedStatement ps;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
/* SQL 처리 코드 추가 부분 */
conn.close();
out.println("MySQL JDBC Driver Connection Test Success!!!");
} catch (Exception e) {
out.println(e.getMessage());
}
%>
</body>
</html>
tomcat 서비스 재시작
> systemctl restart tomcat.service
nginx로 돌아와서 curl 명령어로 테스트를 진행한다.
> curl localhost/db_test.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>tomcat-1</title>
</head>
<body>
**MySQL JDBC Driver Connection Test Success!!!**
</body>
</html>
<title>
부분에 tomcat-1과 tomcat-2이 번갈아가면서 출력되면 성공적으로 3-tier-architecture가 구성된것이다.