1. Web Server와 WAS(web application server) 차이
쉽게 말해서 web server는 어떤 요청에 대해 정적 콘텐츠를 제공하는 서버이며 was는 어떤 요청을 통해 다양한 로직 처리를 요구하는 (db에 접근함) 동적 컨텐츠를 제공하는 서버입니다.
사실 WAS가 웹서버의 기능을 모두 수행할 수 있습니다. 동적 컨텐츠를 제공하는 것은 정적 컨텐츠도 처리한다는 말이기 때문입니다.
하지만 웹서버와 was를 분리하는 것이 좋은데 그 이유는 서버 부화를 방지할 수 있고, 보안이 강화되며 여러 대의 was들의 연결이 가능하는 등의 장점이 있습니다.
그래서 웹서버는 was 전에 두어 http 요청을 웹서버가 받고 web server는 요청을 was에 보내어 처리하는 형태로 아키텍처를 설계해보았습니다.
2. 스프링 프로젝트 생성
docker-project 라는 이름의 프로젝트를 생성하여 resources -> static 안에 index.html 파일을 생성했습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>spring</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
localhost:8080 에 접속하면 hello world가 보이게 됩니다.
3. Dockerfile 생성
프로젝트 바로 밑에 Dockerfile을 생성했습니다.
Dockerfile에는 아래와 같은 내용이 들어갑니다.
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=build/libs/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
간단하게 설명하면 FROM 뒤에는 어떤 이미지를 사용하겠다는 뜻입니다. 저는 자바 8버전이므로 openjdk:8-jdk-alpine docker 공식 이미지를 사용하겠습니다.
ARG 는 변수를 지정하는 것, COPY는 호스트의 파일을 docker 이미지의 파일시스템으로 복사하기 위해 사용되는 명령어로 ARG에서 설정해놓은 JAR_FILE이라는 변수명을 활용하여 COPY에서 jar파일을 app.jar로 복사합니다.
ENTRYPOINT는 이미지를 컨테이너로 띄울 때 항상 실행되어야 하는 커맨트를 지정하는 명령어입니다.
4. bootJar로 .jar 파일 생성
우측의 Gradle을 클릭하고 bootJar를 클릭하여 jar 파일을 생성합니다.
bootJar를 실행하게 되면 build -> libs에 .jar 파일이 생성됩니다.
5. docker image build 하기
cd 명령어를 통해 프로젝트로 이동한 뒤 아래의 명령어를 통해 도커 이미지를 생성합니다. -t (--tag) 이 명령어를 통해 image 이름을 지정할 수 있습니다.
docker build -t docker-spring .
아래의 명령어를 통해 이미지가 생성된 것을 확인할 수 있습니다.
docker images
6. docker image run 하기
아래의 명령어를 통해 docker 이미지를 실행시킬 것입니다. --rm 은 이 프로세스가 종료될 시에 삭제시키고, -d는 입출력 프롬프트 없이 실행시키는 옵션입니다. -p는 포트번호를 연결하는 옵션으로 호스트 시스템에서 사용되는 포트번호:컨테이너에서 사용되는 포트번호/프로토콜 유형 로 구성됩니다.
이 말은 -p 8080:8080이면 호스트 시스템의 8080 포트로 유입되면 도커 컨테이너의 8080 포트로 전달된다는 뜻입니다.
docker run --rm -d --name spring -p 8080:8080 docker-spring
docker ps 명령어를 통해 실행되고 있는 프로세스를 확인할 수 있습니다.
docker ps
7. nginx 실행하기
프로젝트 밑에 default.conf 파일을 생성했습니다.
default.conf
server {
listen 80;
listen [::]:80;
location / {
proxy_pass http://docker-spring:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
}
listen 80은 서버가 80포트로 들어오는 요청을 받는다는 뜻입니다.
proxy_pass 는 프록시 설정으로 spring 이름과 8080 포트를 가진 서버로 요청을 전달하게 됩니다.
다른 이름을 사용하셨다면 spring 자리에 다른 이름을 넣으시면 됩니다.
이제 nginx 이미지를 실행하게 될텐데 -v 호스트 위치:컨테이너 위치 로 파일을 mount 해주는 일을 합니다. -link는 spring 컨테이너와 nginx 컨테이너를 연결합니다. (ip가 아닌 컨테이너 이름을 기반으로 통신 가능)
docker run -d --rm --name nginx -p 80:80 --link spring:spring -v default.config:/etc/nginx/conf.d/default.config nginx
8. ip서버에 접근하기
ipconfig
ipv4 주소에 접속하게 되면 잘 출력되는 것을 확인할 수 있습니다.
'🌎infra > docker' 카테고리의 다른 글
[Docker] centOS 7 docker mysql 과 spring 연동하기 (한글 깨짐 해결) (1) | 2023.12.21 |
---|---|
[Docker] docker nginx에 html 매핑하기 (3) | 2023.09.18 |