8 분 소요

  • 안녕하세요. ‘Nerd-Lee’ 입니다.
    스프링부트 리눅스 서버에 배포하는 법과 MySQL 설치하는 방법에 대해서 정리해봤습니다.
    완벽하진 않지만, 배운 내용이나 터득한 방법에 대해서 한 번 정리해봤으니 도움이 되시기를 바랍니다.

1. FileZlila & Putty 설치


2. MySQL 설치하기

  • putty로 MySQL을 명령어를 입력해서, 설치 및 설정을 하면 된다.
  • sudo apt update 라는 명령어를 입력해서 ubuntu 패키지 정보들을 업데이트한다.
  • sudo apt install mysql-server 명령어를 입력하면, mysql이 설치가 된다.
  • MySQL이 잘 설치되었는 지 확인하기 위해서, dpkg -l | grep mysql-server 를 입력하자.
ii  mysql-server  5.7.37-0ubuntu0.18.04.1  all  MySQL database server (metapackage depending on the latest version)

이런식으로 뜬다면, 설치가 성공한 것이다.

  • MySQL가 실행이 되고 있는 지 확인하기 위해서는, netstat 이라는 것을 이용해서 확인해야 하는데
    sudo netstat -tap | grep mysql 명령어를 입력하자.
    만약 netstat: command not found 에러가 발생하면 아래의 명령어를 입력하자.
  • sudo apt install net-tools 명령어를 입력해서, netstat을 설치하면 된다.
  • 그리고 다시 시도하면, 실행중인 지 확인이 된다.
  • cd /etc/mysql/mysql.conf.d 폴더로 이동
  • sudo vi mysqld.cnf 를 입력해서 bind-address 부분에, 127.0.0.1 ip를 0.0.0.0으로 변경하자
  • sudo mysql 을 입력해서, MySQL을 실행하자.
create user '계정이름'@'%' identified by '패스워드';                  // 외부 접속 계정이름과 비밀번호를 설정하자.
grant all privileges on *.* to '계정이름'@'%' with grant option;     // 해당 계정이름에 권한을 부여하자.
  • 이 다음은 내가 한 부분이 아닌 상사가 한 부분이기 때문에, 만약 aws를 사용하는 개발자라면 이 링크를 참고하는 것이 좋다.

3. JAVA 설치하기

  • 오늘 출근하고 그냥 파일질라를 이용해서, JAVA를 지워서 처음 환경 그대로 다시 시도를 해보려고 했으나..
    큰 오류를 발생할 줄은 몰랐다. putty에서, 삭제에 대한 명령어를 사용해서 삭제를 했어야했는데.. 에효..
    java -version 을 입력해도, 'java' command not found 와 같은 로그만 뜨고..
    그래서, 어쩔 수 없이 일단 sudo 명령어를 이용해서 삭제를 먼저 실행했다.
$ sudo apt-get remove openjdk-8-jre
$ sudo apt-get remove openjdk-8-jdk
  • 그리고, 다시 java 8 버전을 설치를 해봤으나.. 소용이 없었다.. echo $JAVA_HOME 을 입력하면 경로는 뜨지만
    java -version을 입력했을 때 'java' command not found 가 뜨면 의미가 없어보인다.
    그럼 11버전으로 사용해야지ㅎㅎ 만약 8버전을 사용할 예정이라면, 11을 8로 바꾸면 된다.
$ sudo apt-get install openjdk-11-jdk
$ sudo apt-get install openjdk-11-jre
  • 이후, java -version 이나, javac -version 명령어를 입력하면 자바의 버전이 뜰 것이다.
    만약 안뜬다면 sudo reboot now를 입력해서, 서버를 한 번 꺼주고
    다시 파일질라와 putty로 서버에 접속을 해보자.
  • java 환경변수 설정을 해줘야한다. 환경변수 설정은 다음과 같다.
    보통 자바가 설치된 경로는 /usr/lib/jvm 폴더에 설치가 되어있다.
$ sudo nano /etc/profile
  • 위의 명령어를 입력하면, 다음과 같은 텍스트들이 출력된다.
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi
TMOUT=324000
HISTFILESIZE=0
  • 그럼 제일 마지막에 다음과 같은 문장을 추가해주자.
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 // 만약 8 버전이면, 11대신 8입력
export PATH=$JAVA_HOME/bin/:$PATH
export CLASS_PATH=$JAVA_HOME/lib:$CLASS_PATH
  • 이렇게 문장을 추가해줬다면, Ctrl + O 를 입력해주고, Enter 키 입력해서 저장해주고
    Ctrl + X 키를 눌러서 밖으로 빠져나오자.
  • 그리고, source /etc/profile 을 입력해서, 추가된 문장을 적용시키고
    sudo reboot now 명령어를 입력해서 서버를 끄고, 다시 프로그램으로 접속을 한다.
  • echo $JAVA_HOME$JAVA_HOME/bin/javac -version을 입력해서
    환경변수가 제대로 설정이 잘 되었는 지 확인하자.

4. Tomcat 설치

  • 나 같은 경우는, putty를 이용해서 tomcat을 설치하지 않고
    설치된 tomcat 8.5.5 버전을 Filezilla를 이용해서, 복사했다.
  • 설치를 해도 방법은 비슷하다. 경로만 알고 있도록 하자.
  • 설치는 sudo apt-get install tomcat 이란 명령어이다.
  • 톰캣 버전을 확인하는 방법은, cd ${톰캣 경로}/bin
    톰캣 설치된 경로에 있는 bin 폴더를 참고하고 있도록 하고 ./version.sh 를 입력해서 실행하면 되는데..
  • Permission Error가 뜨는 경우가 있다. 그럴 땐, chmod +x version.sh 를 입력해서
    해당 파일을 실행할 수 있는 접근 권한을 허용시키고 다시 실행하자.
  • 실행이 잘 되었다면, 톰캣 서버 버전과 OS 이름, 버전 등등 여러가지가 출력되는 것을 확인할 수 있다.

5. 톰캣서버 포트번호 설정

  • 톰캣서버가 깔려있는 경로로 이동하면, conf 폴더가 있는데, conf 폴더로 이동한다.
  • 그 안에 server.xml 파일을 열어본다.
$ apache-tomcat-8.5.5/conf $ vi server.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8105" 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.core.JreMemoryLeakPreventionListener" />
  <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>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <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"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->

    ★★★ 이 부분 중요
    <Connector port="포트번호" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="리디렉트 포트번호" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->

    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation with the JSSE engine. When
         using the JSSE engine, the JSSE configuration attributes must be used.
    -->
    <!--
    <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 a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation. When using the
         APR/native implementation or the OpenSSL engine with NIO or NIO2 then
         the OpenSSL configuration attributes must be used.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--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>
  • ★★★ 이 부분 중요!! 라고 되어 있는 부분에, 해당 서버에 접근할 수 있도록 설정한 포트번호를 입력하면 된다.

6. 톰캣서버 실행하기

  • tomcat server를 실행하기 위해선, 윗 부분에서, version.sh를 실행하던 폴더로 이동하면
    startup.sh가 있고, shutdown.sh 파일이 있는데 두 파일은, 실행과 종료 파일이다.
    실행하는 방법은 다음과 같다.
$ tomcat/bin $ ./startup.sh
$ tomcat/bin $ ./shutdown.sh
  • 이렇게 입력하면, 톰캣서버가 실행이 된다.
    만약에 또 Permission 관련 에러가 발생하면 위에 적어놓은 방법처럼, chmod 명령어로 접근 권한을 허용해주면 된다.
  • startup.sh 파일을 실행하고 브라우저에, ip번호와 server.xml에 설정해놓은 포트번호를 입력하면 실행이 된다.
  • 만약 안된다면, tomcat 경로에 있는 logs라는 폴더로 이동해서, catalina.out 파일을 열어보자.
$ ...apache-tomcat-8.5.5/logs/vi catalina.out
$ ...apache-tomcat-8.5.5/logs/tail -f catalina.out
  • 첫 번째 명령어는 모든 로그를 다 볼 수 있고, Shift + G 키를 누르면, 제일 아래로 내려갈 수 있다.
  • 두 번째 명령어는 실시간으로 로그를 확인할 수 있다.
  • 로그를 확인해서, 어떤 부분이 잘못됐는 지 확인하고, 다시 ./startup.sh를 입력하면 된다.

7. application.yml 파일 수정하기

  • 만약 database 에러가 났다면, application.yml을 수정해야 하는데
    이 부분은 다시 STS에서 수정하고 빌드를 해도 되지만 만약 ROOT 폴더에 있는 파일을 수정하고 싶은 거라면?
$ apache-tomcat-8.5.5 > cd webapps/ROOT/WEB-INF/classes
  • 명령어를 입력하고, ls 라고 입력을 해보면, application.yml 또는 application.properties 파일이 있을 것이다.
  • 그 부분에서, DB 주소를 입력하고 ./shutdown.sh 를 입력해서 톰캣서버를 종료하고 다시 ./startup.sh 명령어로 톰캣서버를 실행하면 된다.

  • 해당 작업을 하면서 알게 된 부분들과, Database Dump 부분은 내일 다시 적어보도록 할 것이다. 나처럼 헤맸던 사람들이라면 도움이 되었길 바랄 뿐이다. 이 내용으로 도움이 될 지는 의문이지만ㅠㅠ


이 글이 도움이 되셨다면 댓글 부탁드립니다^^
다음 글로 찾아오겠습니다!