본문 바로가기
카테고리 없음

[Azure] Azure Kubernetes Cluster 배포 및 Application 배포

by moveho 2023. 7. 26.

애플리케이션 코드 가져오기

moveho@first-vm:~$ git clone https://github.com/moveho/azure-aks-application.git
moveho@first-vm:~$ cd azure-voting-app-redis
moveho@first-vm:~/azure-voting-app-redis$ ls
LICENSE  README.md  azure-vote  azure-vote-all-in-one-redis.yaml  docker-compose.yaml  jenkins-tutorial

gitclone을 사용해서 소스코드를 받습니다.

다음으로 트리구조를 확인합니다.

moveho@first-vm:~/azure-voting-app-redis$ tree
.
├── LICENSE
├── README.md
├── azure-vote
│   ├── Dockerfile
│   ├── Dockerfile-for-app-service
│   ├── app_init.supervisord.conf
│   ├── azure-vote
│   │   ├── config_file.cfg
│   │   ├── main.py
│   │   ├── static
│   │   │   └── default.css
│   │   └── templates
│   │       └── index.html
│   └── sshd_config
├── azure-vote-all-in-one-redis.yaml
├── docker-compose.yaml
└── jenkins-tutorial
    ├── config-jenkins.sh
    └── deploy-jenkins-vm.sh

5 directories, 14 files

도커설치

moveho@first-vm:~/azure-voting-app-redis$ curl https://get.docker.com/ > dockerinstall && chmod 777 dockerinstall && ./dockerinstall
중략
moveho@first-vm:~/azure-voting-app-redis$ docker --version
Docker version 24.0.5, build ced0996

VM에 도커를 설치합니다.

 

컨테이너 이미지 만들기

permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/json?all=1&filters=%7B%22label%22%3A%7B%22com.docker.compose.config-hash%22%3Atrue%2C%22com.docker.compose.project%3Dazure-voting-app-redis%22%3Atrue%7D%7D": dial unix /var/run/docker.sock: connect: permission denied
moveho@first-vm:~/azure-voting-app-redis$
moveho@first-vm:~/azure-voting-app-redis$ sudo -i
root@first-vm:~# chmod 777 /var/run/docker.sock
root@first-vm:~# exit
logout

moveho@first-vm:~/azure-voting-app-redis$ docker compose up -d
[+] Running 37/42
 ⠏ azure-vote-front 29 layers [⣿⣿⣿⣷⣦⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿] 186.1MB/263.1MB Pulling                                  15.9s
   ✔ 723254a2c089 Pull complete                                                                                         6.0s
   ✔ abe15a44e12f Pull complete                                                                                         7.8s
   ✔ 409a28e3cc3d Pull complete                                                                                         8.1s
   ⠿ 503166935590 Extracting      [===============================================>   ]  47.1...                       15.4s
   ⠼ 0f46f97746e4 Downloading     [================================>                  ]  138...                        15.4s
   ✔ fe27feb3d509 Download complete

docker compose 명령어로 이미지 빌드 및 컨테이너를 실행시킵니다.

ps 명령어 및 images 명령어로 컨테이너 상태 및 도커 이미지를 확인합니다.

moveho@first-vm:~/azure-voting-app-redis$ docker ps
CONTAINER ID   IMAGE                                             COMMAND                  CREATED       STATUS       PORTS                                            NAMES
c5c20c61af2d   mcr.microsoft.com/azuredocs/azure-vote-front:v1   "/entrypoint.sh /sta…"   2 hours ago   Up 2 hours   443/tcp, 0.0.0.0:8080->80/tcp, :::8080->80/tcp   azure-vote-front
60be54b5f483   mcr.microsoft.com/oss/bitnami/redis:6.0.8         "/opt/bitnami/script…"   2 hours ago   Up 2 hours   0.0.0.0:6379->6379/tcp, :::6379->6379/tcp        azure-vote-back

moveho@first-vm:~/azure-voting-app-redis$ docker images
REPOSITORY                                     TAG       IMAGE ID       CREATED       SIZE
mcr.microsoft.com/oss/bitnami/redis            6.0.8     3a54a920bb6c   2 years ago   103MB
mcr.microsoft.com/azuredocs/azure-vote-front   v1        4d4d08c25677   5 years ago   935MB

Azure - 인바운드 포트 규칙 추가 웹브라우저 접속

application에서 사용하는 8080 포트를 개방해줍니다.

8080 포트를 개방해줍니다.

Azure voting app

 

vm 공용IP 8080포트번호로 웹브라우져에 접속합니다.

 

ACR(Azure Container Registry) 배포 사용

Azure CLI 설치

https://learn.microsoft.com/ko-kr/cli/azure/install-azure-cli-linux?pivots=apt

해당 페이지 참조하여 설치

moveho@first-vm:~/azure-voting-app-redis$ az --version

Command 'az' not found, but can be installed with:

sudo apt install azure-cli

버전 확인을 해보면 미리 설치 되어있지 않은 상태입니다.

1.	설치 프로세스에 필요한 패키지를 가져옵니다.
sudo apt-get update
sudo apt-get install ca-certificates curl apt-transport-https lsb-release gnupg
2.	Microsoft 서명 키를 다운로드하고 설치합니다.
sudo mkdir -p /etc/apt/keyrings
curl -sLS https://packages.microsoft.com/keys/microsoft.asc |
    gpg --dearmor |
    sudo tee /etc/apt/keyrings/microsoft.gpg > /dev/null
sudo chmod go+r /etc/apt/keyrings/microsoft.gpg
3.	Azure CLI 소프트웨어 리포지토리를 추가합니다.
AZ_REPO=$(lsb_release -cs)
echo "deb [arch=`dpkg --print-architecture` signed-by=/etc/apt/keyrings/microsoft.gpg] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" |
    sudo tee /etc/apt/sources.list.d/azure-cli.list
4.	리포지토리 정보를 업데이트하고 azure-cli 패키지를 설치합니다.
sudo apt-get update
sudo apt-get install azure-cli

다음의 명령어로 az cli를 설치합니다.

moveho@first-vm:~/azure-voting-app-redis$ az --version
azure-cli                         2.50.0   # 2.0.53 이상 충족해야합니다.

core                              2.50.0
telemetry                          1.0.8

Dependencies:
msal                              1.22.0
azure-mgmt-resource             23.1.0b2

Python location '/opt/az/bin/python3'
Extensions directory '/home/moveho/.azure/cliextensions'

azure-cli 버전이 2.0.53 이상인지 확인합니다.

Azure Container Registry 만들기

1. az group create 명령을 사용하여 리소스 그룹을 만듭니다.

moveho@first-vm:~/azure-voting-app-redis$ az group create --name myResourceGroup --location koreasouth
Please run 'az login' to setup account.
moveho@first-vm:~/azure-voting-app-redis$ az login
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ********to authenticate. # 해당 웹페이지를 열고 code *****를 입력합니다.

[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "769b7a4e-c45a-49a3-8446-a0967bb53c43",
    "id": "fd8e0c3f-bc15-453d-9b2a-b7f54c9056e3",
    "isDefault": true,
    "managedByTenants": [],
    "name": "Azure subscription 1",
    "state": "Enabled",
    "tenantId": "769b7a4e-c45a-49a3-8446-a0967bb53c43",
    "user": {
      "name": "dlehdgh2919@gmail.com",
      "type": "user"
    }
  }
]

az group create 명령어 실행후 나오는 web browser에 접속 해 해당 code를 입력해서 인증을 합니다.

moveho@first-vm:~/azure-voting-app-redis$ az group create --name myResourceGroup --location koreasouth
{
  "id": "/subscriptions/fd8e0c3f-bc15-453d-9b2a-b7f54c9056e3/resourceGroups/myResourceGroup",
  "location": "koreasouth",
  "managedBy": null,
  "name": "myResourceGroup",
  "properties": {
    "provisioningState": "Succeeded"
  },
  "tags": null,
  "type": "Microsoft.Resources/resourceGroups"
}

acr을 생성합니다

moveho@first-vm:~/azure-voting-app-redis$ az acr create --resource-group myResourceGroup --name moveho-acr --sku Basic
Resource provider 'Microsoft.ContainerRegistry' used by this operation is not registered. We are registering for you.
Registration succeeded.
(ResourceNameInvalid) Invalid resource name: 'moveho-acr'. Resource names may contain alpha numeric characters only and must be between 5 and 50 characters.. For more information, please refer resource name requirements at: https://docs.microsoft.com/en-us/rest/api/containerregistry/
Code: ResourceNameInvalid
Message: Invalid resource name: 'moveho-acr'. Resource names may contain alpha numeric characters only and must be between 5 and 50 characters.. For more information, please refer resource name requirements at: https://docs.microsoft.com/en-us/rest/api/containerregistry/
ACR 이름에 특수문자가 있으면 안됩니다.

moveho-acr 이름으로 acr을 생성하려 했는데 특수문자가 허용되지 않습니다.

- 대시를 빼고 다시 생성 시도를 합니다.

moveho@first-vm:~/azure-voting-app-redis$ az acr create --resource-group myResourceGroup --name movehoacr --sku Basic
{
  "adminUserEnabled": false,
  "anonymousPullEnabled": false,
  "creationDate": "2023-07-26T05:42:19.347151+00:00",
  "dataEndpointEnabled": false,
  "dataEndpointHostNames": [],
  "encryption": {
    "keyVaultProperties": null,
    "status": "disabled"
  },
  "id": "/subscriptions/fd8e0c3f-bc15-453d-9b2a-b7f54c9056e3/resourceGroups/myResourceGroup/providers/Microsoft.ContainerRegistry/registries/movehoacr",
  "identity": null,
  "location": "koreasouth",
  "loginServer": "movehoacr.azurecr.io",
  "name": "movehoacr",
  "networkRuleBypassOptions": "AzureServices",
"networkRuleSet": null,
                                       중략 …

정상적으로 완료가 된 상태입니다.

컨테이너 레지스트리에 로그인

moveho@first-vm:~/azure-voting-app-redis$ az acr login --name movehoacr
Login Succeeded

컨테이너 이미지 태그 지정

moveho@first-vm:~/azure-voting-app-redis$ docker images
REPOSITORY                                     TAG       IMAGE ID       CREATED       SIZE
mcr.microsoft.com/oss/bitnami/redis            6.0.8     3a54a920bb6c   2 years ago   103MB
mcr.microsoft.com/azuredocs/azure-vote-front   v1        4d4d08c25677   5 years ago   935MB
도커 이미지 목록을 확인합니다.


moveho@first-vm:~/azure-voting-app-redis$ az acr list --resource-group myResourceGroup --query "[].{acrLoginServer:loginServer}" --output table
AcrLoginServer
--------------------
movehoacr.azurecr.io
로그인서버를 쿼리합니다.

moveho@first-vm:~/azure-voting-app-redis$ docker tag mcr.microsoft.com/azuredocs/azure-vote-front:v1 movehoacr.azurecr.io/azure-vote-front:v1
moveho@first-vm:~/azure-voting-app-redis$ docker images
REPOSITORY                                     TAG       IMAGE ID       CREATED       SIZE
mcr.microsoft.com/oss/bitnami/redis            6.0.8     3a54a920bb6c   2 years ago   103MB
mcr.microsoft.com/azuredocs/azure-vote-front   v1        4d4d08c25677   5 years ago   935MB
movehoacr.azurecr.io/azure-vote-front          v1        4d4d08c25677   5 years ago   935MB

올바르게 docker image 에 tag가 되었는지 확인합니다.

레지스트리에 이미지 푸시

moveho@first-vm:~/azure-voting-app-redis$ docker push movehoacr.azurecr.io/azure-vote-front:v1
The push refers to repository [movehoacr.azurecr.io/azure-vote-front]
ab48c9fa73df: Pushed
5e85a99d34e4: Pushed
d9aeb057eef2: Pushed
9d93163e41ff: Pushed
2131d41261d2: Pushed
a9f64da75364: Pushed
efa870440d9c: Pushed
cde1a4e95d8b: Pushed
57fe04427c69: Pushed
f8af872e5018: Pushed
a7364327f282: Pushing [==================================================>]   2.56kB
c30da5f5d23c: Pushing [==================================================>]  3.584kB
ddeb470c2099: Pushing [==================================================>]  5.186MB
7b3929993879: Pushing [==================================================>]  3.072kB
1a350e9420b7: Pushing [==================================================>]  3.584kB

                                      중략…

레지스트리에서 이미지 나열

moveho@first-vm:~/azure-voting-app-redis$ az acr repository list --name movehoacr.azurecr.io --output table
The login server endpoint suffix '.azurecr.io' is automatically omitted.
Result
----------------
azure-vote-front

 

az acr repository list 명령어로 이미지 목록을 확인합니다.

Azure 콘솔에서도 push 이미지를 확인할 있습니다.

 

AKS(Azure Kubernetes Service) 클러스터 배포

Kubernetes 클러스터 만들기

moveho@first-vm:~/azure-voting-app-redis$ az aks create \
>     --resource-group myResourceGroup \
>     --name myAKSCluster \
>     --node-count 2 \
>     --generate-ssh-keys \
>     --attach-acr movehoacr
SSH key files '/home/moveho/.ssh/id_rsa' and '/home/moveho/.ssh/id_rsa.pub' have been generated under ~/.ssh to allow SSH access to the VM. If using machines without permanent storage like Azure Cloud Shell without an attached file share, back up your keys to a safe location
Resource provider 'Microsoft.ContainerService' used by this operation is not registered. We are registering for you.

에러 발생 ---- koreasouth 에서 사용가능한 vm 크기가 오류메시지가 나옵니다. koreasouth에서 사용가능한 vm 크기 변경해야합니다.

 

명령어에 --node-vm-size 옵션을 추가 하여 다시 명령어를 실행합니다.

moveho@first-vm:~/azure-voting-app-redis$
moveho@first-vm:~/azure-voting-app-redis$ az aks create \
>     --resource-group myResourceGroup \
>     --name myAKSCluster \
>     --node-count 2 \
>     --generate-ssh-keys \
>     --attach-acr movehoacr \
>     --node-vm-size standard_b2s_v2
- Running ..

Running이 출력되면 잠시 클러스터가 생성되기를 기다려 줍니다.

 

콘솔에서도 kubernetes cluster 생성중인것을 확인가능 합니다.

AAD role propagation done[############################################]  100.0000%{
  "aadProfile": null,
  "addonProfiles": null,
  "agentPoolProfiles": [
    {
      "availabilityZones": null,
      "count": 2,
      "creationData": null,
      "currentOrchestratorVersion": "1.25.6",
                                       중략………….

클러스터 생성이 완료되면 다음과 같이 출력됩니다.

 

Kubernetes CLI 설치

moveho@first-vm:~/azure-voting-app-redis$ sudo az aks install-cli
The detected architecture of current device is "x86_64", and the binary for "amd64" will be downloaded. If the detectiton is wrong, please download and install the binary corresponding to the appropriate architecture.
No version specified, will get the latest version of kubectl from "https://storage.googleapis.com/kubernetes-release/release/stable.txt"
Downloading client to "/usr/local/bin/kubectl" from "https://storage.googleapis.com/kubernetes-release/release/v1.27.4/bin/linux/amd64/kubectl"
Please ensure that /usr/local/bin is in your search PATH, so the `kubectl` command can be found.
No version specified, will get the latest version of kubelogin from "https://api.github.com/repos/Azure/kubelogin/releases/latest"
Downloading client to "/tmp/tmpesyf48j7/kubelogin.zip" from "https://github.com/Azure/kubelogin/releases/download/v0.0.31/kubelogin.zip"
Moving binary to "/usr/local/bin/kubelogin" from "/tmp/tmpesyf48j7/bin/linux_amd64/kubelogin"
Please ensure that /usr/local/bin is in your search PATH, so the `kubelogin` command can be found.

az aks install-cli 명령어로 kubectl을 설치합니다.

kubectl version을 확인합니다.

moveho@first-vm:~/azure-voting-app-redis$ kubectl version
WARNING: This version information is deprecated and will be replaced with the output from kubectl version --short.  Use --output=yaml|json to get the full version.
Client Version: version.Info{Major:"1", Minor:"27", GitVersion:"v1.27.4", GitCommit:"fa3d7990104d7c1f16943a67f11b154b71f6a132", GitTreeState:"clean", BuildDate:"2023-07-19T12:20:54Z", GoVersion:"go1.20.6", Compiler:"gc", Platform:"linux/amd64"}
Kustomize Version: v5.0.1
The connection to the server localhost:8080 was refused - did you specify the right host or port?

kubectl 사용하여 클러스터에 연결 <중요>

moveho@first-vm:~/azure-voting-app-redis$ az aks get-credentials --resource-group myResourceGroup --name myAKSCluster
Merged "myAKSCluster" as current context in /home/moveho/.kube/config

moveho@first-vm:~/azure-voting-app-redis$ kubectl get no
NAME                                STATUS   ROLES   AGE     VERSION
aks-nodepool1-39083606-vmss000000   Ready    agent   6m43s   v1.25.6
aks-nodepool1-39083606-vmss000001   Ready    agent   6m44s   v1.25.6

az aks get-credentials 명령어로 현재 context를 kube config 파일에 merge 시켜줍니다.

그 후 kubectl 명령어를 사용하여 생성된 node들을 확인할 수 있습니다.

 AKS(Azure Kubernetes Service)에서 애플리케이션 실행

yaml 파일 업데이트

moveho@first-vm:~/azure-voting-app-redis$ az acr list --resource-group myResourceGroup --query "[].{acrLoginServer:loginServer}" --output table
AcrLoginServer
--------------------
movehoacr.azurecr.io

az acr list 명령어를 사용해서 acr 로그인 서버 이름을 가져옵니다.

moveho@first-vm:~/azure-voting-app-redis$ vi azure-vote-all-in-one-redis.yaml

본인의 acr 태그로 변경합니다.

 

애플리케이션 배포

moveho@first-vm:~/azure-voting-app-redis$ kubectl apply -f azure-vote-all-in-one-redis.yaml
deployment.apps/azure-vote-back created
service/azure-vote-back created
deployment.apps/azure-vote-front created
service/azure-vote-front created

kubectl 명령어를 사용해 해당 yaml파일을 배포합니다.

 

애플리케이션 테스트

moveho@first-vm:~/azure-voting-app-redis$ kubectl get service azure-vote-front --watch
NAME               TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)        AGE
azure-vote-front   LoadBalancer   10.0.95.178   20.200.168.73   80:32272/TCP   20s

로드밸런서 타입의 서비스로 동작하는 서비스를 웹브라우져에서 확인할 있습니다.

EXTERNAL-IP 웹브라우져에 접속해서 확인합니다.

다음과 같이 AKS 를 이용하여 성공적으로 Application을 배포해보았습니다.

댓글