'MSA' 태그의 글 목록 :: 잡다한 프로그래밍
반응형

1. 컨트롤러란?

컨트롤러는 다음과 같은 4가지 기능을 제공한다

  • Auto Healing (Node, Pod가 사용 가능한지 불가한지를 판단하여 새로운 노드에 새로운 파드를 만들어주는 역할)
  • Auto Scaling (한 파드에 과도한 요청이 있을경우 파드를 복제하여 분산시켜주는 역할)
  • Software Update (버전 업데이트를 쉽게할 수 있고 롤백또한 가능)
  • Job (일시적인 작업을 해야할경우 사용)

2. Template, Selector란?

다음 그림과 같이 Template는 컨트롤러에 pod를 설정함, 만약 파드가 죽는다면 template에 있는 파드를 재 생성함

Selector는 컨트롤러와 파드가 서비스와 파드처럼 라벨로 연결하게 해주는데 어떤 라벨을 가진 pod를 관리할건지를 의미함


3. Replicas란?

Replicas를 설정한 개수만큼 Pod를 유지하려고 한다 만약 다음과 같은 YAML파일이 작성되어 있다고 하자. replicas에 3이 적혀있으므로 컨트롤러는 파드의 개수를 3개로 유지하려 할것이고 만약 파드가 죽는다면 재생성하여 3개를 유지할 것이다 이를 활용하여 버전 업데이트가 이루어진다.

apiVersion: v1
kind: ReplicaSet
metadata:
  name: replica-1
spec:
  replicas: 3
  selector:
    type: app
  template:
    metadata:
      name: pod-1
      labels:
        type: app
    spec:
      containers:
      - name: container
        image: app:v1

4. ReplicaSet를 통해 Pod생성하기

다음과 같은 YAML파일을 작성하고 ReplicaSet을 만든다

apiVersion: v1
kind: ReplicaSet
metadata:
  name: replica-1
spec:
  replicas: 1
  selector:
    type: app
  template:
    metadata:
      name: pod-1
      labels:
        type: app
    spec:
      containers:
      - name: container
        image: app:v1
반응형
반응형

0. 사전 준비

도커 설치 및 War파일이 준비가 되어있다는 가정하에 시작한다.


1. Dockerfile작성

Dockerfile

다음과 같은 도커 파일을 작성한다. 이때 server.xml과 war파일은 도커 파일이 존재하는 디렉터리 내부에 존재해야 한다.

 

#어떤 이미지를 기반으로 빌드하는지에 대해서 지정 node 8 사용
FROM node:8

#Dockerfile을 생성/관리하는 사람 없어도 무방
LABEL MAINTAINER dilrong "본인 이메일"

#디렉토리 생성
RUN mkdir -p /usr/src/app

#WORKDIR 설정
WORKDIR /usr/src/app

#앱 의존성 설치를 위해서 package.json 복사
COPY package*.json ./

#npm install 실행 (package.json에 의한 패키지 설치)
RUN npm install

#앱 소스 추가
COPY . .

#컨테이너에서 실행할 명령어 지정 (실행하면 기존 express에서 실행하는 port로 서버가 실행)
CMD ["npm", "start"]

 

이미지 만들기

sudo docker build -t 이미지이름:버전 .

예시
sudo docker build -t test_node:0.1 .

 

2. 이미지 실행

1번을 통해 만든 이미지를 다음과 같이 실행한다

sudo docker run 이미지명:버전

#예시 기존 nodejs서버가 2222 port이므로 -p 를 2222:2222로 컨테이너를 실행
sudo docker run -p 2222:2222 test_node:0.1

아래와 같은 -p는 80 포트로 오는 요청을 1111 포트로 전달해주겠다는 의미이다.

다음과 같이 실행하였다면 war파일이 제대로 배포되어있는 것을 확인할 수 있다.

반응형
반응형

0. 사전준비

도커 설치 및 War파일이 준비가 되어있다는 가정하에 시작한다.


1. Dockerfile작성

Dockerfile

다음과 같은 도커파일을 작성한다. 이때 server.xml과 war파일은 도커파일이 존재하는 디렉토리 내부에 존재해야한다.

 

FROM tomcat:8.5-alpine #톰캣8.5 사용

ENV TZ=Asia/Seoul
Run rm /usr/local/tomcat/conf/server.xml #기본으로 있는 server.xml을 지움
COPY server.xml /usr/local/tomcat/conf/ #현재 디렉토리에 있는 server.xml을 복사
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone #시간을 서울로 설정
RUN value=`cat conf/server.xml` && echo "${value//8080/1111}" >| conf/server.xml #기본포트가 8080인데 1111로 변경 필요한사람은 쓰고 8080쓸거면 지워도됌
RUN rm -Rf /usr/local/tomcat/webapps/ROOT #기본으로 있는 ROOT를 지움
COPY keti_main.war /usr/local/tomcat/webapps #현재 Dockerfile이 작성되는 디렉토리에 있는 war파일을 컨테이너 내부로 복사
ENV JAVA_OPTS="-Dserver.type=dev" #자바 옵션 설정

 

Server.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--Licensed to the Apache Software Foundation (ASF) under one or morecontributor license agreements. See the NOTICE file distributed withthis 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 withthe License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License. -->

<!-- Note: A "Server" is not itself a "Container", so you may notdefine subcomponents such as "Valves" at this level.Documentation at /docs/config/server.html -->

-<Server shutdown="SHUTDOWN" port="8005">

<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 resourcesDocumentation at /docs/jndi-resources-howto.html -->



-<GlobalNamingResources>

<!-- Editable user database that can also be used byUserDatabaseRealm to authenticate users -->


<Resource pathname="conf/tomcat-users.xml" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" description="User database that can be updated and saved" type="org.apache.catalina.UserDatabase" auth="Container" name="UserDatabase"/>

</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that sharea 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 receivedand responses are returned. Documentation at :Java HTTP Connector: /docs/config/http.htmlJava AJP Connector: /docs/config/ajp.htmlAPR (HTTP/AJP) Connector: /docs/apr.htmlDefine a non-SSL/TLS HTTP/1.1 Connector on port 1111 -->


<Connector port="8080" redirectPort="8443" connectionTimeout="20000" protocol="HTTP/1.1"/>

<!-- A "Connector" using the shared thread pool-->


<!--<Connector executor="tomcatThreadPool"port="1111" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" /> -->


<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443This connector uses the NIO implementation. The defaultSSLImplementation will depend on the presence of the APR/nativelibrary and the useOpenSSL attribute of theAprLifecycleListener.Either JSSE or OpenSSL style configuration may be used regardless ofthe SSLImplementation selected. JSSE style configuration is used below. -->


<!--<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/2This connector uses the APR/native implementation which always usesOpenSSL for TLS.Either JSSE or OpenSSL style configuration may be used. OpenSSL styleconfiguration is used below. -->


<!--<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" redirectPort="8443" protocol="AJP/1.3"/>

<!-- An Engine represents the entry point (within Catalina) that processesevery request. The Engine implementation for Tomcat stand aloneanalyzes the HTTP headers included with the request, and passes themon 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 passwordsvia a brute-force attack -->



-<Realm className="org.apache.catalina.realm.LockOutRealm">

<!-- This Realm uses the UserDatabase configured in the global JNDIresources under the key "UserDatabase". Any editsthat are performed against this UserDatabase are immediatelyavailable for use by the Realm. -->


<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>

</Realm>


-<Host name="localhost" autoDeploy="true" unpackWARs="true" appBase="webapps">

<Context reloadable="true" docBase="${catalina.home}/webapps/keti_main" path="/"/>

<!-- SingleSignOn valve, share authentication between web applicationsDocumentation at: /docs/config/valve.html -->


<!--<Valve className="org.apache.catalina.authenticator.SingleSignOn" /> -->


<!-- Access log processes all example.Documentation at: /docs/config/valve.htmlNote: The pattern used is equivalent to using pattern="common" -->


<Valve className="org.apache.catalina.valves.AccessLogValve" pattern="%h %l %u %t "%r" %s %b" suffix=".txt" prefix="localhost_access_log" directory="logs"/>

</Host>

</Engine>

</Service>

</Server>

이미지 만들기

sudo docker build -t 이미지이름:버전

예시
sudo docker build -t test:0.1

이미지 확인

빌드가 완료되면 이미지가 생성되고 다음과 같이 확인할 수 있다.

sudo docker images

2. 이미지 실행

1번을 통해 만든 이미지를 다음과 같이 실행한다

sudo docker run 이미지명:버전

sudo docker run -p 80:1111 이미지명:버전

아래와 같은 -p는 80포트로 오는 요청을 1111포트로 전달해주겠다는 의미이다.

다음과 같이 실행하였다면 war파일이 제대로 배포되어있는것을 확인할 수 있다.


3. 도커 코드

실행중인 컨테이너 상태 보기

sudo docker ps

 

실행중인 컨테이너 IP보기

sudo docker inspect -f "{{ .NetworkSettings.IPAddress }}" Container ID
반응형

+ Recent posts