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

1. 디플로이먼트의 업데이트 방법 4가지

  • ReCreate
  • Rolling Update
  • Blue/Green
  • Canary

#1) ReCreate

Pod1이 작동 중이라면 Pod1을 죽이고 Pod2를 실행시켜 업데이트하는 방식. Pod1이 죽고 Pod2가 실행되는 시간(Downtime)만큼의 빈 공간이 생긴다

 

#2) Rolling Update

Pod1이 1개 실행중이라면 Pod1이 실행된 상태로 Pod2를 실행한다 총 2개를 사용하는 셈 (이때 누군가는 Pod1에, Pod2에 접근할 수 있는 상태) 이후 Pod1을 삭제(이제부터 Pod2에만 접근함) 추가적인 자원을 요구하지만 Downtime이 없음

 

#3) Blue/Green

서비스와 연결된 pod1(컨트롤러1)이 실행 중일 때 pod2(컨트롤러 2)를 만듦 이후 서비스에 연결된 pod1을 pod2로 바꿔주면 pod2로 바꿀 수 있음(추가적인 자원을 요구하고, 서비스의 downtime 없음) 만약 pod2에 문제가 생기면 서비스에 연결된 pod만 pod1으로 바꿔주면 됨 문제가 없으면 pod1과 컨트롤러 1을 삭제해주면 됨

 

#4) Canary

업데이트 예정


2. Rolling Update 실습

다음과 같은 구조로 이루어져있을때 Deployment의 pod v1을 v2로 수정하면 자동으로 Rolling Update가 된다(Rolling Update가 Default)

 

Deployment.YAML

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      type: app
  template:
    metadata:
      labels:
        type: app
    spec:
      containers:
      - name: pod-test
        image: diqmwl/pod:v1
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: test-service
spec:
  selector:
    type: app
  ports:
    - port: 9000
      targetPort: 8080

다음과 같은 YAML에서 image: diqmwl/pod:v1 부분을 pod:v2로 수정하면 Rolling Update가 이루어진다.

반응형
반응형

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파일이 제대로 배포되어있는 것을 확인할 수 있다.

반응형
반응형

1. Service란?

  • 파드에서 실행 중인 프로세스를 위한 신원을 제공한다(공식 홈페이지)
  • 파드에는 수명이 있기 때문에(휘발성 이므로 IP가 변한다) 이에 고정된 주소로 접근하기 위해 Serive가 존재
  • 서비스에는 ClusterIP, NodePort, Load Balancer로 3가지 종류가 존재한다.

2. 서비스 종류

#1) ClusterIP

  • 클러스터 IP로 만들어진 서비스는 외부에서는 접근할 수 없으나 같은 클러스터(같은 쿠버네티스로 연결된) 내에서는 접근이 가능하다.
  • 서비스 내에 파드는 한 개일 수도 여러 개일 수도 있다.
  • 여러 개의 파드가 연결되어있을 경우 트래픽을 분산하여 파드로 전달함
  • 외부에서 접근할 수 없고, 클러스터 내부에서만 사용하기 때문에 허가된 사용자만 사용하는 용도 ex) 쿠버네티스 내부 대시보드

Service Yaml

apiVersion: v1
kind: Service
metadata:
  name: svc-1
spec:
  selector:
    app: pod
  ports:
    - port: 9000
      targetPort: 2000
  type: ClusterIP //생략가능함 기본 옵션임

Pod Yaml

apiVersion: v1
kind: Pod
metadata:
  name: pod-1
  labels:
  app: pod
spec:
  containers:
  - name: container
    image: 이미지명
    ports:
    - containerPort: 2000

svc-1 서비스가 라벨이 app: pod인 pod-1와 연결된 모습이다.

 

#2) NodePort

  • NodePort로 만들어도 ClusterIP는 할당되어 ClusterIP기능을 기본으로 포함하고 있다
  • 모든 노드에 설정한 Port가 할당되고 외부에서 설정한 port로 요청이 올 경우 서비스로 서비스는 파드로 요청이 전달됨
  • 내부망이나, 일시적인 외부 연결용(개발하다가 외부에 임시로 보여줄 때)

그림과 같이 외부로부터 접근이 있을 때 파드가 없는 노드 1(컴퓨터라 생각하면 편함)로 30000 포트로 접근하면 연결된 9000 포트 서비스로 연결함 파드가 있는 노드 2로 접근해도 같은 결과를 나타냄.

 

Service Yaml

apiVersion: v1
kind: Service
metadata:
  name: svc-2
spec:
  selector:
    app: pod
  ports:
    - port: 9000
      targetPort: 2000
      nodePort: 30000 //30000~32767사이로 가능
  type: NodePort

 

#3) Load Balancer

  • 기본적인 노트 포트의 특징을 그대로 가지고 있음
  • 추가적인 로드벨런서가 생겨서 각 노드에 트래픽을 분산시켜주는 역할을 함
  • 기본적인 쿠버네티스만을 설치해서 사용하는 경우 로드밸런서가 생기지 않음 별도로 플러그인을 설치해야 함(GCP, AWS에서 제공하는 쿠버네티스를 사용할 경우에는 제공해줌)
  • 실질적으로 외부로 시스템을 노출할 때 사용함

 

Service.yaml

apiVersion: v1
kind: Service
metadata:
  name: svc-3
spec:
  selector:
    app: pod
  ports:
    - port: 9000
      targetPort: 2000
    type: LoadBalancer
반응형
반응형

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