Nginx reverse proxy tomcat 방법

# 대충 개념 잡기

Apachi, NginX프록시서버(웹서버)이며 Tomcat, Jetty, UndertowWAS다.

(WAS : Web Application Server , 자바진영 용어)

용어차이기 때문에 복잡하게 생각하지말고 Spring+Tomcat / Node.js 등으로 만든 서비스 Application

Apachi, NginX 등은 Application 앞단에서 일을 처리하는 웹서버(관리자, 스케줄러)라 생각하면 된다. 

그래서 Apachi와 NginX는 관리자의 역할에 맞게 Application 들이 각자의 서비스를 잘 수행할 수 있게 관리하는 법들을 고민한다.

TomcatSpring 프로그램(Application)의 관리자(컨테이너) 정도로 생각하면 된다. 

(Application 을 관리하기 때문에 Application과 다른 용어로 표현해야 되니, 그래서 Tomcat을 WAS라 칭하는 것이다.)

Node.js 는 톰캣과 스프링보다 뒤에 개발되었기 때문에, 이러한 Tomcat과 Spring의 구조를 보고 올인원으로 관리자가 내장되어 있는 구조라 만들었다 생각하면 된다.

(그러니까 전체적인 그림에서 수행 하는일로 보자면 Node.js = Tomcat+Spring 과 같다고 보면된다.)

즉, Apachi, NginX, Tomcat은 모두 관리자이며 Apachi와 NginX는 Tomcat보다 상위 관리자라고 생각하자.


Apachi멀티 프로세스 모듈(MPM) 방식으로 처리하고, NginX이벤트 기반(Event-Driven) 방식으로 처리한다.

(Apachi도 이벤트기반 방식을 추가하긴 했음)

따라서 잦은 IO를 처리하는 서비스는 성능과 가벼움이 강점으로 여겨지는 NginX안정성이 중요시되는 서비스에는 Apachi를 사용한다.

[IT지식] Node.js 와 Spring Boot 의 차이점

일단, Node.js와 Spring Boot는 서버 애플리케이션을 만들때 사용하는 플랫폼이다. 구인글을 보면 스타트업에선 Node.js, 정착된 기업에서는 Spring Boot 를 사용하기에, 막연하게 Node.js는 스크립트언어니

developer-ping9.tistory.com

Nginx reverse proxy tomcat 방법

# 관리자의 고민과 역할 (Apachi, NginX, Tomcat)

 이러한 고민은 웹서비스뿐만 아니라, 모든 서비스(클라우드 컴퓨팅, 엣지컴퓨팅, OS 등)에서도 똑같이 적용 된다.

 쿠버네티스, 하둡, OS 도 모두 관리자이니 근본적으로 같은 고민을 하는 셈이다.

 심지어 OSI 7 Layer 각 계층, HTTP도 어떻게 보면 하나의 서비스를 담당하는 관리자인 셈이다.

 해당 게시물에서 관리자의 역할에 대해서 모두 따져보기엔 양이 너무 방대해질 것 같아 모두 다루지 않는 점을 알려드린다.

 운영체제(OS)에 대해 공부를 하시면 아래에 소개드릴 고민 말고도 여럿 고민들을 확인 하실 수 있다.

 1. 서비스가 중지되어선 안된다.

   서비스를 수행중에 서비스가 업데이트 되어야하는 상황이라 가정하자. 하지만 서비스는 중지되어선 안된다.

   그래서 하나의 서비스를 여러개의 톰캣으로 수행시키는 것이며, 업데이트를 순차적으로 적용시킨다.

   이러한 방법으로 서비스가 죽는 상황이 오더라도 대처가능하다.

   그리고 서비스가 죽는 상황을 되도록 만들지 않기 위해 로드 밸런싱(부하분산)을 하는 것도 관리자의 몫이다.



 2. 보안을 신경써야 한다.

  외부의 사용자가 우리의 서버가 어떻게 돌아가는지 모르게 해야 한다.    

  여기서 리버스 프록시(Reverse Proxy)가 등장한다. (아래에서 설명)

 3. 서비스가 가능하면 빠르게 수행되도록 한다.  

  사용자에게 느린 서비스보다는 빠른서비스를 제공하기 위한 고민이다.

  여기서는 캐싱(Caching)과 포워드 프록시(Forward Proxy)가 등장한다. (아래에서 설명)

  적절한 로드 밸런싱 또한 서비스의 성능 향상에 기여한다.


# Proxy

 프록시서버(Proxy)는 클라이언트가 자신을 통해 다른네트워크 서비스(Node.js, Spring, WAS)에 간접적으로 접근할 수 있게 하는 컴퓨터 시스템이나 응용프로그램을 일컫는다.

 중계자(관리자)로서 로드밸런싱, Reverse Proxy, 캐싱 등의 작업을 수행한다. 

Nginx reverse proxy tomcat 방법
https://ko.wikipedia.org/wiki/%ED%94%84%EB%A1%9D%EC%8B%9C_%EC%84%9C%EB%B2%84

# Reverse Proxy

 클라이언트에게서 서버의 정보를 감추는 작업

 (서버 내부적으로 파일들이 어느 폴더에 있는지, 어느 서비스가 어느 포트에서 작업중인지 등)

 클라이언트와 WAS 사이의 중계자로서 둘 사이의 통신을 담당한다.

 리버스 프록시서버를 통해 응답을 내려주기 때문에, 실제 서버의 정보를 알 수 없게 된다.

 또한 WAS는 서버확장에 있어 자유로워지는 이점이 생긴다.

 클라이언트가 요청하는 End Point 는 프록시서버의 도메인이다.

[Reverse Proxy의 캐싱] - 서버의 성능향상에 초점

클라이언트들이 자주 요청할 리소스들을 리버스 프록시에 캐싱하여 요청이 들어오면 바로 건네 줌

# Forward Proxy

 서버에게서 클라이언트를 감추는 작업

 요청받는 서버는 포워드 프록시 서버를 통해서 요청을 받기에 클라이언트의 정보를 알 수 없게 된다.

 [Forward Proxy의 캐싱] - 클라이언트의 성능향상에 초점

 빈번히 사용될 리소스들을 포워드 프록시에 캐싱하여 서버까지 요청할 필요 없이 프록시에서 받아오게 함

- 끝 -


# 짤막지식

[war]

스프링으로 작성한 웹앱을 war 파일로 빌드하면, 그 안에 class, jsp, img, css, js 파일들이 압축되어 있음

톰캣의 특정폴더에 war파일을 넣고 명령어를 실행하면 스프링서비스가 톰캣을 사용해서 돌게 됨 

[jar]

스프링과 톰캣이 같이 묶여서 압축된 파일 


# Reference

>> 얄코님의 유튜브

Nginx reverse proxy tomcat 방법

Apache Tomcat is an open-source implementation of the Java Servlet and JSP technologies that can be used to deploy Java-based applications. It was created under the Apache-Jakarta subproject, but due to its popularity, it is now hosted as a separate Apache project. Tomcat also provides additional functionality that makes it easier to develop a complete web application solution. Tomcat is simple, easy-to-use, and one of the most widely used web servers in the world.

If you are looking to run Java-based applications that operate seamlessly and fast, then Apache Tomcat is the best choice for you.

In this tutorial, we will learn how to install and configure Apache Tomcat with Nginx as a reverse proxy on Ubuntu 18.04 VPS.

Prerequisites

  • A fresh Ubuntu 18.04 VPS on the Atlantic.Net Cloud Platform.
  • A valid domain name pointed at your VPS IP address. In this tutorial, we will use example.com.

Note: You can refer to the Atlantic DNS Guide to manage the DNS records.

Step 1 – Create Atlantic.Net Cloud Server

First, log in to your Atlantic.Net Cloud Server.  Create a new server, choosing Ubuntu 18.04 as the operating system with at least 2GB RAM. Connect to your Cloud Server via SSH and log in using the credentials highlighted at the top of the page.

Once you are logged in to your Ubuntu 18.04 server, run the following command to update your base system with the latest available packages.

apt-get update -y

Step 2 – Install Java

Apache Tomcat is a Java-based application, so Java must be installed on your system. You can install the latest version of Java with the following command:

apt-get install default-jdk -y

After installing Java, verify the Java version with the following command:

java --version

You should get the following output:

Nginx reverse proxy tomcat 방법

Step 4 – Create Tomcat User

Next, you will need to create a Tomcat user and group to run the Tomcat service.

First, create a group with the name tomcat using the following command:

groupadd tomcat

Next, create a new tomcat user and make this user member of the tomcat group with a /home/tomcat home directory.

useradd -s /bin/false -g tomcat -d /home/tomcat tomcat

At this point, the Tomcat user is created.

Step 5 – Download Tomcat

First, visit the Apache Tomcat download page. You should see the following screen:

Nginx reverse proxy tomcat 방법

Next, download the latest version of Apache Tomcat with the following command:

wget http://www.mirrorservice.org/sites/ftp.apache.org/tomcat/tomcat-9/v9.0.31/bin/apache-tomcat-9.0.31-fulldocs.tar.gz

After downloading Apache Tomcat, extract the downloaded file with the following command:

tar -xvzf apache-tomcat-9.0.31-fulldocs.tar.gz

Next, move the extracted directory to /home/tomcat as shown below:

mv tomcat-9.0-doc /home/tomcat

Next, change the ownership of the /home/tomcat directory to tomcat and give proper permissions with the following command:

chown -R tomcat:tomcat /home/tomcat
chmod -R 755 /home/tomcat/

Step 6 – Create a System Unit File for Tomcat

Next, you will need to create a systemd service file to run Tomcat as a service. You can create it with the following command:

nano /etc/systemd/system/tomcat.service

Add the following lines:

[Unit]
Description=Tomcat servlet container
After=network.target

[Service]
Type=forking

User=tomcat
Group=tomcat

Environment="JAVA_HOME=/usr/lib/jvm/default-java"
Environment="JAVA_OPTS=-Djava.security.egd=file:///dev/urandom"

Environment="CATALINA_BASE=/home/tomcat"
Environment="CATALINA_HOME=/home/tomcat"
Environment="CATALINA_PID=/home/tomcat/temp/tomcat.pid"
Environment="CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC"

ExecStart=/home/tomcat/bin/startup.sh
ExecStop=/home/tomcat/bin/shutdown.sh

[Install]
WantedBy=multi-user.target

Save and close the file. Then, reload the systemd daemon with the following command:

systemctl daemon-reload

Next, start the Tomcat service and enable it to start after system reboot:

systemctl start tomcat
systemctl enable tomcat

You can also check the status of the Tomcat service with the following command:

systemctl status tomcat

You should see the following output:

● tomcat.service - Tomcat servlet container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-11-28 05:15:32 UTC; 7s ago
  Process: 6044 ExecStart=/home/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 6053 (java)
    Tasks: 43 (limit: 1150)
   CGroup: /system.slice/tomcat.service
           └─6053 /usr/lib/jvm/default-java/bin/java -Djava.util.logging.config.file=/home/tomcat/conf/logging.properties -Djava.util.logging.m

Nov 28 05:15:32 ubuntu1804 systemd[1]: Starting Tomcat servlet container...
Nov 28 05:15:32 ubuntu1804 startup.sh[6044]: Tomcat started.
Nov 28 05:15:32 ubuntu1804 systemd[1]: Started Tomcat servlet container.

Step 7 – Access Tomcat Web Interface

Tomcat is now installed and running on port 8080. You can verify the Tomcat port with the following command:

netstat -ant

You should see the following output:

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State     
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN    
tcp6       0      0 :::8009                 :::*                    LISTEN    
tcp6       0      0 :::8080                 :::*                    LISTEN    
tcp6       0      0 :::22                   :::*                    LISTEN    
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN

Now, open your web browser and visit the URL http://your-server-ip:8080. You should see the Tomcat default web page:

Nginx reverse proxy tomcat 방법

Step 8 – Configure Tomcat Web Management Interface

Next, you will need to add a login to access the manager web application.

You can add a user to access manager-gui and admin-gui by editing the file tomcat-users.xml:

nano /home/tomcat/conf/tomcat-users.xml

Add the following lines above the line </tomcat-users>:

<role rolename="manager-gui"/>
<user username="tomcat1" password="s3cret" roles="manager-gui"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="s3cret" roles="admin-gui"/>

Save and close the file when you are finished.

By default, Tomcat is configured to restrict access to the Manager and Host Manager apps only from the localhost, so you will need to remove this restriction.

To remove the restriction for Manager app, edit the context.xml file as shown below:

nano /home/tomcat/webapps/manager/META-INF/context.xml

Comment out the Valve section as shown below:

<Context antiResourceLocking="false" privileged="true" >
<!--
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|223.184.194.44" />
-->
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreven$
</Context>

Save and close the file.

To remove the restriction for Host Manager app, edit the context.xml file as shown below:

nano /home/tomcat/webapps/host-manager/META-INF/context.xml

Comment out the Valve section as shown below:

<Context antiResourceLocking="false" privileged="true" >
<!--

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|223.184.194.44|172.20.10.3" />
-->

  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreven$
</Context>

Save and close the file when you are finished. Then, restart the Tomcat service to apply the changes:

systemctl restart tomcat

Now, open your web browser and type the URL http://your-server-ip:8080. You should see the following page:

Nginx reverse proxy tomcat 방법

Now, click on the Manager App/Host Manage button. You will be prompted for the admin username and password. Provide your admin username and password and click on the Login button. You should see the Manager App/Host Manager on the following page:

Nginx reverse proxy tomcat 방법

Nginx reverse proxy tomcat 방법

Step 9 – Configure Nginx Proxy for Tomcat

By default, Tomcat is configured to run on port 8080, so you will need to configure Nginx as a reverse proxy to forward the request coming on port 8080 to the Nginx port 80.

First, install the Nginx web server with the following command:

apt-get install nginx -y

Once installed, create a new virtual host configuration file for Tomcat.

nano /etc/nginx/sites-available/tomcat.conf

Add the following lines:

server {
  listen 80;

  server_name    example.com;
  access_log /var/log/nginx/tomcat-access.log;
  error_log /var/log/nginx/tomcat-error.log;

  location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://127.0.0.1:8080/;
  }
}

Save and close the file, then enable the Nginx virtual host file and restart the Nginx web server to apply the configuration:

ln -s /etc/nginx/sites-available/tomcat.conf /etc/nginx/sites-enabled/
systemctl restart nginx

Now, you can access your Tomcat web interface using the URL http://example.com.

Conclusion

Congratulations! Your Tomcat installation is now completed. I hope you have now enough knowledge to deploy your Java-based application on the Tomcat server. For more information, visit the Tomcat official documentation at Tomcat Doc. Try out Tomcat today with VPS Hosting from Atlantic.Net!