본문 바로가기
프로그램 활용/웹서버

웹서버] Apache + 다중 톰캣 설치(서비스 여러개 No)

by 3604 2023. 11. 28.
728x90

출처: https://blog.naver.com/hahav000/221924900991

 

  •  
  • ?
    안녕하세요 하하입니다.
    오랜만에 포스팅 하나 올립니다.
     
    최근 서버구성에서 하나의 서버컴퓨터에서 Web 서비스를 2개이상 해야하는 상황이 생겼습니다.
    ?
    현재 서버 구성은
    - 리눅스(ubuntu 18.04),
    - apache2 + tomcat8
    - java-1.8.0-openjdk
    이렇게 구성 했었고 apache2와 tomcat8을 apt-get install 로 자동 설치하였습니다.
    ?
    구글링을 해보니 Web서비스를 여러개 구성하는 방법이 여러가지 존재했었습니다.
    ?
    1. 톰캣/conf/server.xml 에서 service를 추가로 등록하는 방법(port변경 필요)
    2. 톰캣(수동설치)을 여러개 놓고 각각 service.xml을 구성을 하는 방법(port변경 필요)
    ?
    처음에 1번으로 service를 2개를 만들어서 Web 서비스를 구성하려고 했으나 tomcat 하나를 죽이면 2개의 서비스 모두 죽는 단점이 있어서 중간에 포기했습니다.
    특히나 apt-get install tomcat8 이런식으로 톰캣을 설치하는 경우 2번을 하기가 굉장히 까다롭습니다. 폴더별 경로가 한곳에 있지 않고 여러군데로 흩어져 있기때문에 다중톰켓을 원하신다면 웬만하면 자동설치는 지우시고 수동설치하시는게 좋을 듯 합니다.
    ?
    @ 프로그램 설치
    1. apache2
    # apt-get install apache2 # apache2 ?v # version 확인 # systemctl restart apache2
    apache2가 설치되었습니다.
    2. tomcat8.5 수동 설치 (2개 복사함)
    #root@: cd ~ #root@: ?wget http://archive.apache.org/dist/tomcat/tomcat-8/v8.5.27/bin/apache-tomcat-8.5.27.tar.gz? #root@: ?tar zxvf apache-tomcat-8.5.27.tar.gz
    ?
    다운로드가 완료되면 압축을 풀고
    #root@: mv apache-tomcat-8.5.27 /usr/local/tomcat8_1 다시 톰캣 gz파일 압축을 풀고 #root@: mv apache-tomcat-8.5.27 /usr/local/tomcat8_2
    이제 tomcat8 폴더가 두개 생성되었습니다.
    ?
    이제 아파치와 톰캣 내부 포트와 맞춰줘야 하는 작업을 진행해봅니다.
    ?
    @ mod_Jk 연동
    1. workers.properties 파일 생성 및 내용 추가
    vi /etc/apache2/workers.properties
    workers.java_home=/usr/lib/jvm/java-8-openjdk-amd64

    # Define 1 real worker ajp13
    worker.list=tomcat1, tomcat2

    # Set properties for tomcat1 (ajp13)
    worker.tomcat1.port=8009
    worker.tomcat1.host=localhost
    worker.tomcat1.type=ajp13
    worker.tomcat1.lbfactor=1

    # Set properties for tomcat2 (ajp13)
    worker.tomcat2.port=8109
    worker.tomcat2.host=localhost
    worker.tomcat2.type=ajp13
    worker.tomcat2.lbfactor=1

    java_home의 경우 java가 설치된 경로입니다.
    기본적으로 apache에서 tomcat으로의 연결포트는 8009로 default 셋팅되어 있습니다.
    저는 다중 톰캣을 위해 tomcat을 하나 더 생성하여 port는 8109로 셋팅하였습니다.
    ?
    ajp13은 apache와 톰캣간에 연결되는 타입이라고 생각하시면 됩니다.
    lbfactor는 로드밸런싱 인자인데 들어오는 패킷에 대한 비율로 알고있습니다.
    각각 1로 셋팅했습니다.
    ?
    2. jk.conf 파일 수정
    vi /etc/apache2/mods-available/jk.conf
    #JkWorkersFile /etc/libapache2-mod-jk/workers.properties <- 주석 처리
    JkWorkersFile /etc/apache2/workers.properties <- 추가

    위의 workers.properties경로를 추가합니다.
    ?
    3. 000-default.conf 파일 수정
    vi /etc/apache2/sites-available/000-default.conf
    <VirtualHost *:6003>
      # The ServerName directive sets the request scheme, hostname and port that
      # the server uses to identify itself. This is used when creating
      # redirection URLs. In the context of virtual hosts, the ServerName
      # specifies what hostname must appear in the request's Host: header to
      # match this virtual host. For the default virtual host (this file) this
      # value is not decisive as it is used as a last resort host regardless.
      # However, you must set it for any further virtual host explicitly.
      #ServerName www.example.com
      ServerAdmin webmaster@localhost
      #DocumentRoot /var/www/html
      DocumentRoot /usr/local/tomcat8_1/webapps
      JKMount /* tomcat1

      # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
      # error, crit, alert, emerg.
      # It is also possible to configure the loglevel for particular
      # modules, e.g.
      #LogLevel info ssl:warn
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined
      # For most configuration files from conf-available/, which are
      # enabled or disabled at a global level, it is possible to
      # include a line for only one particular virtual host. For example the
      # following line enables the CGI configuration for this host only
      # after it has been globally disabled with "a2disconf".
      #Include conf-available/serve-cgi-bin.conf
    </VirtualHost>
    <VirtualHost *:6004>
      ServerAdmin webmaster@localhost
      DocumentRoot /usr/local/tomcat8_2/webapps
      JKMount /* tomcat2
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>

    중요 포인트
    기본 VirtualHost *:80 이 아니라
    실제 외부에서 들어오는 포트번호를 입력해야합니다.
    저의 경우 6003과 6004를 포트포워딩하여서 사용하였습니다.
    VirtualHost 포트 추가하는 부분과 JKMount부분과 DocumentRoot 부분을 수정하였습니다.
    ?
    @ apache2 port listen을 해준다.
    vi /etc/apache2/ports.conf에서
    Listen 포트명 작성후 저장
    예) Listen 6003
    Listen 6004
    ?
    지금까지 잘 따라오셨다면 이제 tomcat의 server.xml 에서 포트만 확인해주시면됩니다.
    ?
    @ 톰캣 server.xml 수정(포트 정리)
    현재 /usr/local/tomcat8_1 과 /usr/local/tomcat8_2가 두개 존재합니다.
    /usr/local/tomcat8_1/conf/server.xml과
    /usr/local/tomcat8_2/conf/server.xml 의 내용이 달라야
    두개를 동시에 실행가능합니다.
    vi /usr/local/tomcat8_1/conf/server.xml 에서 수정되어야하는 부분
    1. <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1"
    => jvmRoute tomcat1 추가 (worker에서 사용했던 이름)
    <?xml version="1.0" encoding="UTF-8"?>
    <Server port="8005" shutdown="SHUTDOWN">
        <Listener className="org.apache.catalina.startup.VersionLoggerListener" /> <!-- Security listener. Documentation at /docs/config/listeners.html <Listener className="org.apache.catalina.security.SecurityListener" /> -->
        <!--APR library loader. Documentation at /docs/apr.html -->
        <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> <!-- Prevent memory leaks due to use of particular java/javax APIs-->
        <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
        <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> <!-- Global JNDI resources Documentation at /docs/jndi-resources-howto.html -->
        <GlobalNamingResources>
            <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users -->
            <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" />
        </GlobalNamingResources>
        <Service name="Catalina">
            <!--The connectors can use a shared executor, you can define one or more named thread pools-->
            <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> -->
            <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <!-- A "Connector" using the shared thread pool-->
            <!-- <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> -->
            <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="150" SSLEnabled="true"> <SSLHostConfig> <Certificate certificateKeystoreFile="conf/localhost-rsa.jks" type="RSA" /> </SSLHostConfig> </Connector> -->
            <!-- Define an AJP 1.3 Connector on port 8009 -->
            <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
            <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
                <!--For clustering, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) -->
                <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> -->
                <!-- Use the LockOutRealm to prevent attempts to guess user passwords via a brute-force attack -->
                <Realm className="org.apache.catalina.realm.LockOutRealm">
                    <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. -->
                    <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" />
                </Realm>
                <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
                    <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html -->
                    <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> -->
                    <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" -->
                    <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" />
                </Host>
            </Engine>
        </Service>
    </Server>​


    vi /usr/local/tomcat8_2/conf/server.xml 에서 수정되어야하는 부분
    1. <Server port="18005" shutdown="SHUTDOWN">
    => 기본 8005로 되어있던것 18005로 변경함
    2. <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">
    => jvmRoute tomcat2추가 (worker에서 사용했던 이름)
    3. <Connector port="18080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
    => http/1.1 프로토콜의 connector port를 18080으로 변경
    4. <Connector port="8109" protocol="AJP/1.3" redirectPort="8443" />
    => AJP/1.3 프로토콜의 connector port를 8009->8109로 변경
    ?
    다 되셨으면 저장합니다.
    ?
    아파치를 다시 재기동하고 tomcat을 실행해봅니다.
    systemctl restart apache2
    ?
    /usr/local/tomcat8_1/bin의 startup.sh 를 실행시킵니다.
    /usr/local/tomcat8_2/bin의 startup.sh를 실행시킵니다.
    ?
    tomcat을 최초설치하는경우 /usr/local/tomcat8_1/webapps에 이미
    웹을 연결했을 때 톰캣 화면이 나오도록 되어있습니다.
    ?
    인터넷 창을 켜고 http:// IP주소:포트 를 입력했을 때
    tomcat 고양이 화면이 나오면 끝.^^
    ?
    톰켓을 리눅스 서비스로 등록하시려면 아래 사이트 확인해주세요
    https://suwoni-codelab.com/linux/2018/05/21/tomcat-installation/
    https://suwoni-codelab.com/linux/2018/05/21/tomcat-installation/

 

 

728x90