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

0. 개요

https://diqmwl-programming.tistory.com/63

 

[Spring boot 강의] #2 스프링부트 HTTPS / HTTP2적용하기

1. HTTPS란 HTTP는 인터넷에서 웹 서버와 사용자 브라우저간 문서를 전송하기 위한 통신 규약이다. HTTP는 정보를 텍스트로 주고받기 때문에 누군가가 네트워크 이를 가로챈다면 정보를 확인할 수 있어서 보안에..

diqmwl-programming.tistory.com

https를 적용하기 위해 ingress에 tls를 적용하는 방법을 공부한다

https와 http의차이가 궁금하다면 다음 강의를 참고한다

1. 인증서 발급받기

letsencrypt를 통해 무료 인증서를 발급받는다. (발급받는 법 수정 예정)


2. secret 생성하기

다음과 같은 명령어를 통해 tls secret을 생성한다. 이때 secret과 ingress 컨트롤러가 같은 네임스페이스에 위치하도록 한다

Kubectl create secret tls {secretname} --key {private.pem경로} --cert {fullchain.pem경로}

ex)
Kubectl create secret tls nginx-tls --key private.pem --cert fullchain.pem -n ingress-nginx

3. ingress 생성하기

다음과 같이 Ingress를 생성한다

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: service-loadbalancing
  namespace: ingress-nginx
spec:
  rules:
  - http:
      paths:
        - path: /one
          backend:
            serviceName: service-1
            servicePort: 9000
        - path: /two
          backend:
            serviceName: service-2
            servicePort: 9001
  tls:
  - secretName: nginx-tls

4. ingress 적용하기

다음과 같이 kubernetes에 적용한다

kubectl apply -f ingress.yml
반응형
반응형

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가 이루어진다.

반응형
반응형

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