1. tomcat/conf/server.xml 에 access log 생성 관련 추가

<Server port="8015" shutdown="SHUTDOWN">
  <Service name="Catalina">
  ...
      <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
        ...
          
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b %D" />
            
            
       </Host>
   </Service>
</Server>

- 위 내용처럼 <Host> 태그 및 에 <Value> 태그를 생성

- prefix , suffix 설정하면  /logs 폴더 및에 파일 생성

- pattern은 아래 내용 확인 ( 자세히 : https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/valves/AccessLogValve.html )

%a - Remote IP address
%A - Local IP address
%b - Bytes sent, excluding HTTP headers, or '-' if no bytes were sent
%B - Bytes sent, excluding HTTP headers
%h - Remote host name (or IP address if enableLookups for the connector is false)
%H - Request protocol
%l - Remote logical username from identd (always returns '-')
%m - Request method
%p - Local port
%q - Query string (prepended with a '?' if it exists, otherwise an empty string
%r - First line of the request
%s - HTTP status code of the response
%S - User session ID
%t - Date and time, in Common Log Format format
%u - Remote user that was authenticated
%U - Requested URL path
%v - Local server name
%D - Time taken to process the request, in millis
%T - Time taken to process the request, in seconds
%I - current Request thread name (can compare later with stacktraces)

결과: 

// pattern="%h %l %u %t &quot;%r&quot; %s %b %D"

127.0.0.1   -    -    [04/Sep/2023:00:00:13 +0900] "GET /sse HTTP/1.1"  200   43   11  
   (%h)    (%l) (%u)              (%t)                   (%r)           (%s) (%b) (%D)

- 중요부분만 보면 /sse 라는 GET 방식 API 요청 결과 , 성공(200) 했고 ,헤더 포함 43byte 전송.

- 요청 소요 시간은 11 (millesec) .

'server > tomcat' 카테고리의 다른 글

Tomcat SSL 인증서 적용  (0) 2023.02.20

tomcat 버전 : 9.0

java 버전 :  8 (1.8.065)

 

OpenSSL 설치 (https://takudaddy.tistory.com/507)

 

.crt  -> .pfx  -> .jks  순서로 변경
편의상 인증서 파일이 있는 경로에서 cmd 창으로 작업하는 것을 추천
아래는 인증서 파일이 D:/ 루트에 있을 경우

1. 인증서 파일(.crt)을 .jks로 변환

 

D:\>openssl pkcs12 -export -name (도메인이름) -in (인증서파일_이름).crt -inkey 
(개인키 파일 이름).key -out (생성할 pfx 파일 이름).pfx

Loading 'screen' into random state - done
Enter Export Password: (패스워드 입력)
Verifying - Enter Export Password: (패스워드 확인)
unable to write 'random state'

ex) openssl pkcs12 -export  -name goom.tistory.com -in goom_tistory_com.crt -inkey 
goom_tistory_com.key -out goom_tistory_com.pfx

 

 

2..pfx 파일을 .jks 파일로 변환

D:\>keytool -importkeystore -srckeystore (위에서 생성한 pfx 파일 이름).pfx -srcstoretype pkcs12 
-destkeystore (생성할 jks파일 이름).jks -deststoretype jks
대상 키 저장소 비밀번호 입력: (jks에 적용할 패스워드 입력)
새 비밀번호 다시 입력: (패스워드 확인)
소스 키 저장소 비밀번호 입력: (pfx 생성시 설정한 패스워드)
portal.sangsin.com 별칭에 대한 항목이 성공적으로 임포트되었습니다.
임포트 명령 완료: 성공적으로 임포트된 항목은 1개, 실패하거나 취소된 항목은 0개입니다.

ex) keytool -importkeystore -srckeystore goom_tistory_com.pfx  -srcstoretype pkcs12 
-destkeystore goom_tistory_com.jks -deststoretype jks

 

더보기

[참고] 확장자별 사용 가능한 서버
Apache 서버 : .crt, .pem 확장자 적용 가능
Nginx 서버 : .crt, .pem 확장자 적용 가능
Webtob 서버 : .crt, .pem 확장자 적용 가능
IIS 서버 : .pfx 확장자 적용 가능
Exchange 서버 : .pfx 확장자 적용 가능
Tomcat 서버 : .jks 확장자 적용 가능
Resin 서버 : .jks 확장자 적용 가능
Jboss 서버 : .jks 확장자 적용 가능

* 위의 내용은 일반적인 사항이며,
인증서 갱신 시에는 서버에 설치 되어 있는 확장자를 확인 후 서버에 설치되어 있는 확장자와
동일한 인증서 파일로 설치 진행하면 됨.

3.Tomcat / server.xml에 적용

 

<Server port="8005" shutdown="SHUTDOWN">
	<Service name="Catalina">
    	<Connector port="80" protocol="HTTP/1.1"
        		redirectPort="443"
                ...
                />
         <Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
                port="443"
                scheme="https"
                secure="true"
                SSLEnabled="true"
                keystoreFile="(.jsk 경로 및 파일 이름)"
                keystorePass="(생성시 설정한 패스워드)"
                sslProtocol="SSL" 
           />
           ...
       </Service>
 </Server>

 

4. http -> https 자동 리다이렉트

 

- 브라우저 창에 http:// 로 입력해도 자동으로 https:// 변환 필요

 

- tomcat/conf/web.xml 에 아래 코드 삽입

	...
    
	<!-- SSL Forward(HTTP->HTTPS) config start -->
	<security-constraint>
	<web-resource-collection>
	<web-resource-name>SSL Forward</web-resource-name>
	<url-pattern>/*</url-pattern>
	</web-resource-collection>
	<user-data-constraint>
	<transport-guarantee>CONFIDENTIAL</transport-guarantee>
	</user-data-constraint>
	</security-constraint>
	<security-constraint>
	<web-resource-collection>
	<web-resource-name>HTTPS or HTTP</web-resource-name>
	<url-pattern>/js/*</url-pattern>
	<url-pattern>/images/*</url-pattern>
	<url-pattern>/css/*</url-pattern>
	<url-pattern>/plugins/*</url-pattern>
	</web-resource-collection>
	<user-data-constraint>
	<transport-guarantee>NONE</transport-guarantee>
	</user-data-constraint>
	</security-constraint>
	<!-- SSL Forward(HTTP->HTTPS) config end -->
    
</web-app>

 

[참고]

tomcat 로그에 별 특이 사항 없고 정상적으로 올라온 것 같을 때 확인해 볼 사항

 

1. tomcat/log의 catalina.log 

 - 톰캣 실행되면서 특이한 로그 없는지 확인

 

2.server.xml 에 ssl 인증서 경로 확인

 

3.방화벽 확인

 - AP 서버에서 톰캣 구동 후 telnet 등으로 443 포트 연결되는지 확인

 - AP 서버는 되는데 외부에서 연결이 안되면 방화벽 문제

 - 직접 방화벽 허용이 가능하면 ufw allow 443 등으로 방화벽 허용

'server > tomcat' 카테고리의 다른 글

톰캣 access log 응답 시간 조회  (0) 2023.09.04
요구사항:

AP1은 상시 Active 상태 이고, AP1이 문제 생기거나 패치시 AP2가 백업으로 활성화 되도록 조치

nginx.conf 에서 upstream의 특정 server에  backup 만 추가해줌

http {
    ...(생략)...
    upstream tomcatGroup{
		server 127.0.0.1:8090 max_fails=3 fail_timeout=3s;
		server 127.0.0.1:8094 backup; //backup 추가
	}
    
    server {
        listen 80; 
		listen [::]:80;
        ...(생략)...
        location / {
        	proxy_pass http://tomcatGroup;
            ...(생략)...
         }
    } //end - server     
} //end - http

테스트 결과, AP1(Main) 이 다운되면 , AP2(Backup)으로 세션 전달됨

 

AP1이 재구동 시작되면, AP2의 연결이 끊기고 AP1이 완전히 구동될 때까지 대기 상태로 됨.

 

[참고] tomcat 클러스터링

 

AP1에서 AP2로 세션이 유지하기 위해서는 각 tomcat server.xml 및 web.xml에서 아래 설정 추가해야 함

 

https://tomcat.apache.org/tomcat-8.0-doc/cluster-howto.html

 

Apache Tomcat 8 (8.0.53) - Clustering/Session Replication HOW-TO

Simply add to your or your element to enable clustering. Using the above configuration will enable all-to-all session replication using the DeltaManager to replicate session deltas. By all-to-all we mean that the session gets replicated to all the other no

tomcat.apache.org

 

<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
   ...(생략)...
  <Service name="Catalina">
  	...(생략)...  			   
	<Connector port="8090" protocol="HTTP/1.1"
		connectionTimeout="60000"
		URIEncoding="UTF-8"
		enableLookups="false"		
		redirectPort="443"
		disableUploadTimeout="true"
		maxThreads="500"
		minSpareThreads="100"
		maxSpareThreads="300"
		maxConnection="8192"
		maxParameterCount="1000000"
		compression="on"
		compressionMinSize="204800"
		noCompressionUserAgents="gozilla, traviata"
		compressableMimeType="text/html,text/plain,text/xml,text/css,text/javascript,application/javascript,application/json,application/octet-stream"
		useSendfile="false" />
       
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8090">
        
        //방법 1.
        //아래 <Cluster> 태그만 주석 해제해도 동작함
        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
        
        //방법 2.
        //아래 <Cluster> 태그는 관련 옵션 customize 할 때 사용
      	<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
				 channelSendOptions="6"> 

		  <!-- <Manager className="org.apache.catalina.ha.session.BackupManager"
				   expireSessionsOnShutdown="false"
				   notifyListenersOnReplication="true"
				   mapSendOptions="6"/> -->
		  
		  <Manager className="org.apache.catalina.ha.session.DeltaManager"
				   expireSessionsOnShutdown="false"
				   notifyListenersOnReplication="true"/>
		  
		  <Channel className="org.apache.catalina.tribes.group.GroupChannel">
			<Membership className="org.apache.catalina.tribes.membership.McastService"
						address="228.0.0.4"
                        port="45564"
						frequency="500"
						dropTime="3000"/>
			<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
					  address="auto"
                      //[중요] TCP port 4000~ 4100 설정가능
                      //같은 서버에서 tomcat이 여러개일 경우 해당 포트 각각 다르게 설정
					  port="4001"   
					  selectorTimeout="100"
					  maxThreads="6"/>

			<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
			  <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
			</Sender>
			<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
			<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
			<Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
		  </Channel>

		  <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
				 filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt"/>

		  <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
					tempDir="/tmp/war-temp/"
					deployDir="/tmp/war-deploy/"
					watchDir="/tmp/war-listen/"
					watchEnabled="false"/>

		  <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
		</Cluster> -->	
        
		...(생략)... 
     </Engine>
  </Service>
</Server>

F12 - Application - Storage(Cookies)에서 JSESSIONID 확인

AP1 강제 종료하면 tomcat 로그에 

 

정보 [Membership-MemberDisappered.] 멤버 사라짐 메시지를 수신했습니다. 로그 확인

 

AP2(backup)의 tomcat 로그

 

F12 - Application - Storage(Cookies)에서 JSESSIONID 다시 확인해보면 AP2 의 jvmRoute 값(tomcat8094)으로 변경된 것을 확인할 수 있음.

'server > nginx' 카테고리의 다른 글

[nginx- tomcat] 세션 클러스터링  (0) 2021.08.19
nginx : ver.1.20.1
tomcat: ver. 8.0

 

nginx를 이용 무중단 배포 시도 중 아래와 같이 .. 세션이 끊기는 현상 발생

 

"Unauthorized...?!"
console 로그에 401...

 

nginx 설정(nginx.conf)은 

 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
	client_max_body_size 0;

    #gzip  on;

	upstream tomcatGroup{
		ip_hash;
		server 0.0.0.0:8088;
		server 0.0.0.0:8092;
	}

    server {
        #listen       8080; //8087
		listen 80; 
		listen [::]:80;
        server_name  (domain name);

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
            #index  index.html index.htm;
			proxy_pass http://tomcatGroup;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			#proxy_set_header X-Forwarded-Proto $scheme;
			#proxy_set_header X-NginX-Proxy true;
			#proxy_redirect off;
			charset utf-8;
			proxy_set_header Host $http_host;
			proxy_cookie_path ~*^/.* /;
			#add_header 'Access-Control-Allow-Origin' '*';
        }
    }
	...
}

 

upstream load balancing 할 IP 주소, port 입력 후 location에 proxy_pass에 upstream 지정해둠

 

//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xml:xsi= ...

   <distributable/> //세션 공유를 위해 추가
 </web-app>

 

검색 결과 한가지 더 해줘야함. tomcat/conf/server.xml 에서

 

//server.xml
<?xml version='1.0' encoding='utf-8'?>
<Server port= ...
	...
	<Service name="Catalina">
	   <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8092">
	
         //주석 해제
         <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
           ...
       </Engine>
    </Service>
</Server>

 

 <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

이 태그 주석을 해제함.

 

아래 톰캣 공식 문서에 자세한 내용이 나와있음.

 

F12> Application> Storage -Cookies의 해당 도메인 주소 sessionID 값 확인 

 tomcat:8092 startUp  -> Tomcat:8088 shutDown 후 다시 확인

JSESSIONID 의 값은 같은데 끝에 jvmRoute 값으로 설정한 8092로 변경됨

 

 

참고:

https://tomcat.apache.org/tomcat-8.0-doc/cluster-howto.html

https://fliedcat.tistory.com/126

https://www.lesstif.com/java/tomcat-46366798.html

'server > nginx' 카테고리의 다른 글

nginx backup 설정 (feat. tomcat clustering)  (0) 2023.01.27

+ Recent posts