본문 바로가기

프로그래밍/Docker

Docker로 AWS ECR 배포

728x90
반응형

docker push 명령을 사용하여 컨테이너 이미지를 Amazon ECR 리포지토리 푸시할 일이 생겨서 해당 작업을 정리해 보았습니다.

 

1. 젠킨스에서 빌드된 이미지를 ECR 리포지토리로 push 하는 python 스크립트 생성

- 젠킨스에서 최신 빌드 가져오기

- AWS 로그인

- ECR 리포지토리로 push

import os
import sys
import time
import urllib2
import commands
from datetime import datetime
from urllib2 import URLError

buildServerIP = ""
buildJobName = ""
buildImageName = "xxx-manager"

def loginAws():
    loginCommand = commands.getstatusoutput("aws ecr get-login --no-include-email --region ap-northeast-2")[1]
    dockerCommand = "sudo %s" % (loginCommand)
    os.system(dockerCommand)

def deployToAws():
    buildCommand = "sudo docker build -t %s:latest ." % (buildImageName)
    os.system(buildCommand)

    tagCommand = "sudo docker tag %s:latest xxxx.dkr.ecr.ap-northeast-2.amazonaws.com/%s:latest" % (buildImageName, buildImageName)
    os.system(tagCommand)

    pushCommand = "sudo docker push xxx.dkr.ecr.ap-northeast-2.amazonaws.com/%s:latest" % (buildImageName)
    os.system(pushCommand)

def convertTimestamp(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

def checkoutBuild():
    if not os.path.exists("jobs"):
        os.system("mkdir jobs")

    checkCommand = "sudo cp /xxx/program/jenkins/jobs/%s/builds/permalinks jobs/permalinks" % (buildJobName)
    os.system(checkCommand)

    lastSuccessfulBuild = commands.getstatusoutput("cat /home/svcapp_su/deploy/jobs/permalinks | grep lastSuccessfulBuild | awk '{ print $2 }'")[1]
    checkCommand = "sudo cp /xxx/program/jenkins/jobs/%s/builds/%s/build.xml jobs/build.xml" % (buildJobName, lastSuccessfulBuild)
    #print("[JENKINS] Enter login password of user 'svcapp_su' to check jenkins build result.")
    os.system(checkCommand)

    if not os.path.exists("jobs/build.xml"):
        return

    isNewBuild = True
    isMasterBranchFound = False
    with open("jobs/build.xml", "r") as f:
        for line in f.read().split('\n'):
            line = line.strip()
            if line == "<string>refs/remotes/origin/stage</string>":
               isMasterBranchFound = True
            if isMasterBranchFound == False:
               continue

            if line.startswith("<hudsonBuildNumber>"):
                buildNum = line[len("<hudsonBuildNumber>"):]
                buildNum = buildNum[0:buildNum.find("</hudsonBuildNumber>")]
                if not os.path.exists("jobs/%s" % buildNum):
                    os.system("mkdir jobs/%s" % buildNum)

                jobDir = "jobs/%s/%s" % (buildNum, moduleName)
                if os.path.exists(jobDir):
                    print("[JENKINS] Jenkins build #%s already deployed [%s]" % (buildNum, convertTimestamp(os.path.getmtime(jobDir))))
                    isNewBuild = False
                else:
                    print("[JENKINS] Lastest successful jenkins build #%s will be downloaded." % buildNum)
                    print("[JENKINS] target : %s.jar" % moduleName)
                break

    if isNewBuild:
        lastModifiedOld = None
        if os.path.exists("deploy_lib/%s.jar" % moduleName):
            lastModifiedOld = os.path.getmtime("deploy_lib/%s.jar" % moduleName)

        getCommand = "cp /data/jenkins/workspace/%s/build/libs/%s.jar deploy_lib/%s.jar" % (buildJobName, moduleName, moduleName)
        print("[JENKINS] Enter login password of user 'svcapp_su' to downlaod jar file from jenkins")
        os.system(getCommand)

        lastModified = os.path.getmtime("deploy_lib/%s.jar" % moduleName)
        if lastModified != lastModifiedOld:
            os.system("mkdir %s" % jobDir)
            os.system("mv jobs/build.xml %s/build.xml" % jobDir)
        else:
            os.system("rm jobs/build.xml")
    else:
        os.system("rm jobs/build.xml")


moduleName = "xxx-deploy"
servicePort = ""
profile = sys.argv[1]
buildServerIP = sys.argv[2]
buildJobName = sys.argv[3]

num = None
isMultiModule = False
if len(sys.argv) > 4:
    num = sys.argv[4]
else:
    isMultiModule = True

checkoutBuild()
loginAws()
deployToAws()

 

2. Dockerfile 을 만들기

- nginx 와 Spring boot 같이 띄우기가 잘 안되서 좀 많이 고생함.

FROM openjdk:8-jdk-alpine
RUN apk add nginx openrc

VOLUME ["/sys/fs/cgroup"]
VOLUME /logs
RUN mkdir /run/nginx/
RUN chown -R nginx:nginx /run/nginx/
RUN chmod 775 /run/nginx/

COPY ./conf/default.conf /etc/nginx/conf.d/default.conf

COPY ./run.sh /run.sh
RUN chmod 775 /run.sh
ADD /deploy_lib/xxx-deploy.jar xxx-deploy.jar

EXPOSE 80
ENTRYPOINT sh run.sh && nginx -g 'daemon off;'

 

3. run.sh

#!/bin/bash
java -Dspring.profiles.active=stage -Dserver.port=8082 -Duser.timezone=Asia/Seoul -jar /xxx-deploy.jar &
728x90
반응형

'프로그래밍 > Docker' 카테고리의 다른 글

NginX 와 php 환경의 Docker 컨네이트 배포  (2) 2020.08.06