본문 바로가기
Docker

[Docker] Tomcat을 Container로 구동하기 위해 Tomcat Docker Image 만들기

by 임채훈 2020. 10. 23.

Docker Custom Image는 Dockerfile을 통해 생성할 수 있음

이미지를 만드는 방법은 간단하다.

평소에 로컬에 특정 Platform을 설치하고 구동하는 일련의 과정들을 Dockerfile에 그대로 옮겨주면 된다.

예를들어 평소에 로컬에 Tomcat을 설치하고 운용하는 과정을 간추리면 다음과 같다.

 

  1. 톰캣을 tar.gz 파일로 설치 혹은 apt를 이용하여 설치

  2. 톰캣 설정 변경 (Port, Logging, Context Path 등)

이 작업들을 Dockerfile에서 처리할 수 있도록 해주면 된다.

혹은 로컬에 설치된 Tomcat Directory를 Base로 Docker Container로 구동할수도 있는데

이 과정은 추후에 다루도록 할 예정.

 

Dockerfile 작성

  • 작업 디렉토리 이동 (/usr/local/docker/tomcat)
mkdir -p /usr/local/docker/tomcat
cd /usr/local/docker/tomcat
  • Dockerfile 생성
vi Dockerfile
  • /usr/local/docker/tomcat/Dockerfile
FROM openjdk:8-jdk
MAINTAINER chaehoon

베이스 이미지는 openjdk:8-jdk로 하고 작업자는 자신의 이름 입력 (굳이 없어도 됨)

→ Tomcat은 기본적으로 OS에 JDK가 설치가 필수적이므로 흔히 많이 사용하는 Light한 ubuntu이미지를 활용할시 별도로 JDK를 설치해줘야되는 과정을 필요로 함

 

중간 빌드 및 결과

docker build --tag tomcat9 ./

Sending build context to Docker daemon  2.048kB
Step 1/2 : FROM openjdk:8-jdk
 ---> 5e934d30ed6f
Step 2/2 : MAINTAINER chaehoon
 ---> Running in 309f80248acd
Removing intermediate container 309f80248acd
 ---> c76b85d26c75

docker build 명령어를 통해 tag(이미지 이름)를 tomcat9로 설정하고 현재 디렉토리 /usr/local/docker/tomcat 에 존재하는 Dockerfile을 통해 빌드를 실행

 

명령어를 추가하면서 build를 주기적으로 해주면서 디버깅 가능
→ history는 docker 내부 빌드 로직에 따라 알아서 관리가 되며 빌드가 성공적으로 이루어졌을때 다음번 빌드과정에서는 이전 빌드과정을 Skip하게 됨.
명령어에 문제가 있거나 오타가 있거나할시 빌드가 실패되며 다음 빌드시 재시도

 

컨테이터 내부 Tomcat이 위치할 곳 및 작업할 디렉토리 설정

  • /usr/local/docker/tomcat/Dockerfile
WORKDIR /usr/local

apt-get 업데이트 및 wget 설치

  • /usr/local/docker/tomcat/Dockerfile
RUN apt-get update -y
RUN apt-get install wget

기본적으로 Light한 도커 이미지 생성용 OS 이미지는 기본적으로 필요한 유틸리티 패키지 라이브러리가 설치되어 있지 않음.
따라서 apt-get을 사용하여 특정 패키지를 설치해야 될 시 update를 해주도록 함.
현재 사용중인 openjdk:8-jdk이미지는 wget을 포함한 필수 라이브러리가 설치되어 있음

중간 빌드 및 결과

docker build --tag tomcat9 ./

Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM openjdk:8-jdk
 ---> 5e934d30ed6f
Step 2/5 : MAINTAINER chaehoon
 ---> Using cache
 ---> c76b85d26c75
Step 3/5 : WORKDIR /usr/local
 ---> Running in a7096a98a53a
Removing intermediate container a7096a98a53a
 ---> 19695ba35d2e
Step 4/5 : RUN apt-get update
 ---> Running in ee507551bad0
Get:1 http://security.debian.org/debian-security buster/updates InRelease [65.4 kB]
Get:2 http://deb.debian.org/debian buster InRelease [121 kB]
Get:3 http://deb.debian.org/debian buster-updates InRelease [51.9 kB]
Get:4 http://security.debian.org/debian-security buster/updates/main amd64 Packages [243 kB]
Get:5 http://deb.debian.org/debian buster/main amd64 Packages [7906 kB]
Get:6 http://deb.debian.org/debian buster-updates/main amd64 Packages [7868 B]
Fetched 8396 kB in 4s (2068 kB/s)
Reading package lists...
Removing intermediate container ee507551bad0
 ---> fdbfbdafc944
Step 5/5 : RUN apt-get install -y wget
 ---> Running in f5fc39cd15f3
Reading package lists...
Building dependency tree...
Reading state information...
wget is already the newest version (1.20.1-1.1).
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
Removing intermediate container f5fc39cd15f3
 ---> 689741f4c43f
Successfully built 689741f4c43f
Successfully tagged tomcat9:latest

Tomcat 압축파일 다운로드 및 압축해제

  • /usr/local/docker/tomcat/Dockerfile
RUN wget https://downloads.apache.org/tomcat/tomcat-9/v9.0.39/bin/apache-tomcat-9.0.39.tar.gz
RUN tar -xvzf apache-tomcat-9.0.39.tar.gz
RUN mv apache-tomcat-9.0.39 tomcat9

 

 

Apache Tomcat® - Apache Tomcat 9 Software Downloads

Welcome to the Apache Tomcat® 9.x software download page. This page provides download links for obtaining the latest version of Tomcat 9.0.x software, as well as links to the archives of older releases. Unsure which version you need? Specification version

tomcat.apache.org

다운로드 링크는 위 이미지 참고.

현재 시점 버전의 경우 apache-tomcat-9.0.39 압축을 푼 후 폴더명인 apache-tomcat-9.0.39 를 tomcat9 로 변경해줌

 

중간 빌드 및 결과

docker build --tag tomcat9 ./

Step 6/8 : RUN wget https://downloads.apache.org/tomcat/tomcat-9/v9.0.39/bin/apache-tomcat-9.0.39.tar.gz
 ---> Running in a9298a8da77e
--2020-10-22 03:55:36--  https://downloads.apache.org/tomcat/tomcat-9/v9.0.39/bin/apache-tomcat-9.0.39.tar.gz
Resolving downloads.apache.org (downloads.apache.org)... 88.99.95.219, 2a01:4f8:10a:201a::2
Connecting to downloads.apache.org (downloads.apache.org)|88.99.95.219|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11282879 (11M) [application/x-gzip]
Saving to: 'tomcat9.tar.gz'

     0K .......... .......... .......... .......... ..........  0% 93.9K 1m57s
    50K .......... .......... .......... .......... ..........  0%  190K 87s
   100K .......... .......... .......... .......... ..........  1% 3.68M 59s
		... (다운로드 진행률 생략)
 10900K .......... .......... .......... .......... .......... 99% 6.12M 0s
 10950K .......... .......... .......... .......... .......... 99% 6.26M 0s
 11000K .......... ........                                   100% 22.1M=7.2s

2020-10-22 03:55:44 (1.49 MB/s) - 'tomcat9.tar.gz' saved [11282879/11282879]

Removing intermediate container a9298a8da77e
 ---> 12ed34abd878
Step 7/8 : RUN tar -xvzf apache-tomcat-9.0.39.tar.gz
 ---> Running in 8a50f93175f5
apache-tomcat-9.0.39/conf/
apache-tomcat-9.0.39/conf/catalina.policy
apache-tomcat-9.0.39/conf/catalina.properties
apache-tomcat-9.0.39/conf/context.xml
		... (압축 해제 진행상태 생략)
apache-tomcat-9.0.39/bin/shutdown.sh
apache-tomcat-9.0.39/bin/startup.sh
apache-tomcat-9.0.39/bin/tool-wrapper.sh
apache-tomcat-9.0.39/bin/version.sh

Removing intermediate container 8a50f93175f5
 ---> c4a8037918a8
Step 8/8 : RUN mv apache-tomcat-9.0.39 tomcat9
 ---> Running in db15a4926cae
Removing intermediate container db15a4926cae
 ---> 361fe474f771
Successfully built 361fe474f771
Successfully tagged tomcat9:latest

톰캣 실행

WORKDIR /usr/local/tomcat9

EXPOSE 8080

ENTRYPOINT ["./bin/catalina.sh", "run"]

작업 디렉토리 /usr/local/tomcat9 로 이동 후 컨테이너가 사용할 8080을 지정해주고 ENTRYPOINT 설정(Application 실행 명령어)

최종 빌드 및 결과

docker build --tag tomcat9 ./

Step 9/11 : WORKDIR     /usr/local/tomcat9
 ---> Running in 211f2402f3b3
Removing intermediate container 211f2402f3b3
 ---> 8c0bb3117a5c
Step 10/11 : EXPOSE 8080
 ---> Running in 65d1d4a3776b
Removing intermediate container 65d1d4a3776b
 ---> baa66e109bff
Step 11/11 : ENTRYPOINT ["./bin/catalina.sh", "run"]
 ---> Running in 57f6b74645fa
Removing intermediate container 57f6b74645fa
 ---> 74476006e59f
Successfully built 74476006e59f
Successfully tagged tomcat9:latest

최종 점검

1. 로컬 도커 이미지 목록 확인

docker images

REPOSITORY                        TAG                 IMAGE ID            CREATED             SIZE
tomcat9                           latest              74476006e59f        42 seconds ago      571MB
openjdk                           8-jdk               5e934d30ed6f        8 days ago          511MB   133MB

2. 컨테이너 생성 및 실행

docker run -d -p 8080:8080 --name tomcat9 tomcat9

31034627620dc2607db4d80740b9da6daba4199144b8339346056e242a3b2a90

컨테이너에서 사용하는 8080포트를 로컬포트로 매핑 (Port Forwarding)

컨테이너 이름은 tomcat9로 지정

3. 실행 결과 확인

docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES
31034627620d        tomcat9             "./bin/catalina.sh r…"   6 seconds ago       Up 5 seconds        0.0.0.0:8080->8080/tcp                     tomcat9

4. 컨테이너에 접속하여 빌드 작업 내역 확인

docker exec -it tomcat9 /bin/bash

방금전 실행한 컨테이너(tomcat9)의 bash shell을 통해 터미널 형태로 접속한다.

터미널 접속이 아닌 명령어를 날려 실행하는것도 가능함

ls -alh

total 160K
drwxr-xr-x 1 root root 4.0K Oct 22 04:47 .
drwxr-xr-x 1 root root 4.0K Oct 22 04:47 ..
-rw-r----- 1 root root  19K Oct  6 14:17 BUILDING.txt
-rw-r----- 1 root root 5.3K Oct  6 14:17 CONTRIBUTING.md
-rw-r----- 1 root root  56K Oct  6 14:17 LICENSE
-rw-r----- 1 root root 2.3K Oct  6 14:17 NOTICE
-rw-r----- 1 root root 3.2K Oct  6 14:17 README.md
-rw-r----- 1 root root 6.8K Oct  6 14:17 RELEASE-NOTES
-rw-r----- 1 root root  16K Oct  6 14:17 RUNNING.txt
drwxr-x--- 2 root root 4.0K Oct 22 04:47 bin
drwx------ 1 root root 4.0K Oct 22 04:51 conf
drwxr-x--- 2 root root 4.0K Oct 22 04:47 lib
drwxr-x--- 1 root root 4.0K Oct 22 04:51 logs
drwxr-x--- 2 root root 4.0K Oct 22 04:47 temp
drwxr-x--- 7 root root 4.0K Oct  6 14:14 webapps
drwxr-x--- 1 root root 4.0K Oct 22 04:51 work
ps -ef |grep tomcat

root         1     0  9 04:51 ?        00:00:09 /usr/local/openjdk-8/bin/java -Djava.util.logging.config.file=/usr/local/tomcat9/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/local/tomcat9/bin/bootstrap.jar:/usr/local/tomcat9/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat9 -Dcatalina.home=/usr/local/tomcat9 -Djava.io.tmpdir=/usr/local/tomcat9/temp org.apache.catalina.startup.Bootstrap start

간단하게 Tomcat이 잘 설치되어있는지, Tomcat 프로세스가 잘 떠있는지 확인하는 과정

 

로컬 디렉토리 컨테이너에 마운트

Tomcat을 통해 Web Service를 운영하다보면 가끔 변경해야될 설정정보나 소스 배포 및 로그 파일들이 존재하는데 그럴때마다 매번 컨테이너에 접속하는것은 번거로우므로 Tomcat의 핵심 디렉토리 요소인

  • logs
  • webapps
  • conf

위 디렉토리들을 로컬에서 사용할 수 있도록 디렉토리를 마운트 해주면 좋음

→ 컨테이너 내 특정 디렉토리를 로컬에 마운트

 

1. 디렉토리 이동

cd /usr/local/docker/tomcat

2. 컨테이너 구동 목록 확인

docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES
31034627620d        tomcat9             "./bin/catalina.sh r…"   26 minutes ago      Up 26 minutes       0.0.0.0:8080->8080/tcp                     tomcat9

3. 컨테이너 내 디렉토리 로컬로 복사

docker cp tomcat9:/usr/local/tomcat9/webapps .
docker cp tomcat9:/usr/local/tomcat9/conf.
docker cp tomcat9:/usr/local/tomcat9/logs .

4. 컨테이너 실행 중지 및 삭제

docker stop tomcat9
docker rm tomcat9

5. 컨테이너 생성 및 디렉토리 마운트

docker run -d -p 8080:8080 --name tomcat9 tomcat9 \ 
		-v /usr/local/docker/tomcat/conf:/usr/local/tomcat9/conf \
		-v /usr/local/docker/tomcat/logs:/usr/local/tomcat9/logs \
		-v /usr/local/docker/tomcat/webapps:/usr/local/tomcat9/webapps

6. 테스트

mkdir -p /usr/local/docker/tomcat/webapps/test

vi /usr/local/docker/tomcat/webapps/test/index.html

<html>
<body>
	Hello World
</body>
</html>
curl localhost:8080/test/index.html

<html>
<body>
        Hello World
</body>
</html>

테스트는 현재 로컬 webapps 디렉토리에서 WEB Context를 test 라고 임의로 생성하여 index.html 파일을 작성하여 로컬에서localhost:8080/test/index.html 호출을 했을때 성공적으로 요청이 이루어지는가에 대한 테스트

댓글