>  기사  >  Java  >  Azure 컨테이너 앱에 Java Azure 함수 배포

Azure 컨테이너 앱에 Java Azure 함수 배포

WBOY
WBOY원래의
2024-09-09 22:30:47373검색

Deploying a Java Azure Function on Azure Container Apps

Azure Functions는 Azure Container Apps에서 컨테이너화된 함수 앱을 개발, 배포 및 관리하기 위한 통합 지원을 제공합니다. 이를 통해 AKS(Azure Kubernetes Service)와 같은 컨테이너 환경에서 Azure Functions를 독립적으로 실행하는 것에 비해 통합 Azure 관리 포털을 사용하여 Azure Functions를 더 쉽게 실행하고 관리할 수 있습니다. 또한 Azure Container Apps에서 제공하는 기능을 활용하면 Azure Functions에 대한 KEDA, Dapr, Envoy, 크기 조정, 모니터링, 보안 및 액세스 제어와 같은 기능을 쉽게 활용할 수 있습니다.

[참고]

Azure Functions의 Azure Container Apps 호스팅

Azure Container Apps에서 첫 번째 컨테이너화된 함수 만들기

환경 변수 설정

다음은 Azure Container Apps 리소스 생성과 관련된 환경 변수입니다. 여기에서는 생성할 리소스의 다양한 이름과 설치 위치는 물론 컨테이너 이미지 이름과 태그를 지정합니다.

# Azure Container Apps resource names
export LOCATION=eastus
export RESOURCE_GROUP_NAME=yoshio-rg
export CONTAINER_REGISTRY_NAME=cajava2411
export CONTAINER_ENVIRONMENT=YoshioContainerEnvironment
export STORAGE_NAME=yoshiojavastorage
export AZURE_FUNCTION_NAME=yoshiojavafunc

# Container image name and tag
export C_IMAGE_NAME=tyoshio2002/java-function-on-aca
export C_IMAGE_TAG=1.0

Java Azure 함수 프로젝트 생성 및 테스트

1. Java Maven 프로젝트용 Azure Functions 생성

먼저 Azure Functions for Java용 Maven 프로젝트를 만듭니다. 이 Maven 프로젝트는 Java 21을 사용하여 Azure Functions를 생성하도록 설계되었습니다. mvn archetype:generate 명령을 사용하여 프로젝트를 생성하고 필요에 따라 매개 변수를 수정합니다.

mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=com.microsoft.azure \
-DarchetypeArtifactId=azure-functions-archetype \
-DgroupId=com.yoshio3 \
-Dpackage=com.yoshio3 \
-DartifactId=yoshiojavafunc \
-DappName=Java-Azure-Functions \
-DappRegion=$LOCATION \
-DjavaVersion=21 \
-Dversion=1.0-SNAPSHOT \
-Ddocker

위 명령을 실행하면 디렉터리 구조가 자동으로 생성되고 Function.java에는 HTTP 트리거가 있는 Azure 함수에 대한 샘플 코드가 포함됩니다. Docker 컨테이너 환경에서 Azure Functions를 실행하기 위한 구성이 포함된 Dockerfile도 생성됩니다.

├── Dockerfile
├── host.json
├── local.settings.json
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── yoshio3
    │               └── Function.java
    └── test
        └── java
            └── com
                └── yoshio3
                    ├── FunctionTest.java
                    └── HttpResponseMessageMock.java

2. 로컬에서 Azure 함수 실행

Maven 프로젝트를 빌드하고 Azure Functions를 로컬에서 실행합니다. 다음 명령을 실행하여 HTTP 트리거로 Azure Functions를 시작합니다.

mvn clean package
mvn azure-functions:run

Azure Functions가 실행되면 다른 터미널을 열고 다음 명령을 실행하여 HTTP 트리거에 요청을 보냅니다. "Hello, World"라는 응답을 받아야 합니다.

curl "http://localhost:7071/api/HttpExample?name=World"
# Output: 
Hello, World

Azure Functions 컨테이너 이미지 생성 및 테스트

1. Docker 이미지 빌드 및 테스트

자동으로 생성된 Dockerfile을 사용하여 Azure Functions 컨테이너 이미지를 빌드합니다. 다음 명령을 실행하여 이미지를 빌드합니다.

docker build -t $C_IMAGE_NAME:$C_IMAGE_TAG -f ./Dockerfile .

빌드가 완료되면 다음 명령어를 실행하여 이미지가 생성되었는지 확인하세요.

docker images | grep $C_IMAGE_NAME
# Output: 
tyoshio2002/java-function-on-aca    1.0    bcf471e6f774   9 hours ago     1.46GB

이미지가 생성되면 다음 명령을 실행하여 Azure Functions 컨테이너 이미지를 로컬에서 테스트합니다. Azure Functions 컨테이너는 내부적으로 HTTP 포트 80을 사용하므로 로컬 액세스를 위해 포트 8080에 매핑합니다. 컨테이너가 시작된 후 컬 명령을 실행하여 Azure Functions HTTP 트리거에 요청을 보냅니다. 모든 것이 올바르게 작동하면 "Hello, World" 메시지가 표시됩니다.

docker run -p 8080:80 -it $C_IMAGE_NAME:$C_IMAGE_TAG
curl "http://localhost:8080/api/HttpExample?name=World"
# Output: 
Hello, World

컨테이너 이미지를 Azure Container Registry로 푸시

1. 애저 CLI에 로그인

먼저 Azure CLI를 사용하여 Azure에 로그인합니다. 다음 명령어를 실행하여 로그인하세요.

az login

2. 리소스 그룹 생성

Azure에서 리소스 그룹을 만듭니다. 이 리소스 그룹은 Azure Container Registry 및 Azure Container Apps와 관련된 리소스를 그룹화하는 데 사용됩니다.

az group create --name $RESOURCE_GROUP_NAME --location $LOCATION

3. Azure Container Registry 생성 및 로그인

Azure Container Registry를 만들고 로그인하세요. Azure Container Registry는 컨테이너 이미지 푸시를 위한 프라이빗 컨테이너 레지스트리입니다.

az acr create --resource-group $RESOURCE_GROUP_NAME --name $CONTAINER_REGISTRY_NAME --sku Basic
az acr login --name $CONTAINER_REGISTRY_NAME

4. Azure Container Registry 서버 이름 검색

생성된 Azure Container Registry의 서버 이름을 검색합니다. 서버 이름은 $CONTAINER_REGISTRY_NAME.azurecr.io 형식입니다.

CONTAINER_REGISTRY_SERVER=$(az acr show --name $CONTAINER_REGISTRY_NAME --query loginServer --output tsv)

5. 이미지를 Azure Container Registry에 푸시

로컬에서 생성된 컨테이너 이미지를 Azure Container Registry에 푸시하려면 tag 명령을 사용하여 이미지에 태그를 지정하세요. 태그를 붙인 후 push 명령을 사용하여 이미지를 푸시합니다.

docker tag $C_IMAGE_NAME:$C_IMAGE_TAG $CONTAINER_REGISTRY_SERVER/$C_IMAGE_NAME:$C_IMAGE_TAG
docker push $CONTAINER_REGISTRY_SERVER/$C_IMAGE_NAME:$C_IMAGE_TAG

Azure 컨테이너 앱 생성 및 Java Azure 함수 배포

1. Azure CLI에 확장 및 리소스 공급자 등록

Azure CLI에서 Azure Container Apps를 생성하고 관리하려면 필요한 확장 프로그램과 리소스 공급자를 등록하세요.

az upgrade
az extension add --name containerapp --upgrade -y
az provider register --namespace Microsoft.Web
az provider register --namespace Microsoft.App
az provider register --namespace Microsoft.OperationalInsights

2. Azure 컨테이너 앱 환경 생성

Azure Container Apps용 환경을 만듭니다. 이 명령은 Azure Container Apps를 호스팅하는 데 필요한 구성을 설정합니다.

az containerapp env create --name $CONTAINER_ENVIRONMENT --enable-workload-profiles --resource-group $RESOURCE_GROUP_NAME --location $LOCATION

3. Create Storage Account for Azure Functions

Azure Functions requires a storage account when creating a Function App instance. Therefore, create a general-purpose storage account for Azure Functions.

az storage account create --name $STORAGE_NAME --location $LOCATION --resource-group $RESOURCE_GROUP_NAME --sku Standard_LRS

4. Create an Instance of Java Azure Function in Azure Container Apps

Create an instance of the Java Azure Function in Azure Container Apps. Execute the following command to create the instance. Since the Azure Function is created using Java 21, specify --runtime java.

az functionapp create --name $AZURE_FUNCTION_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--environment $CONTAINER_ENVIRONMENT \
--storage-account $STORAGE_NAME \
--workload-profile-name "Consumption" \
--max-replicas 15 \
--min-replicas 1 \
--functions-version 4 \
--runtime java \
--image $CONTAINER_REGISTRY_SERVER/$C_IMAGE_NAME:$C_IMAGE_TAG \
--assign-identity

5. Assign Role for Azure Function to Access Azure Container Registry

Finally, configure secure access for Azure Functions to Azure Container Registry. Enable the system-managed identity for Azure Functions and assign the ACRPull role for access.

FUNCTION_APP_ID=$(az functionapp identity assign --name $AZURE_FUNCTION_NAME --resource-group $RESOURCE_GROUP_NAME --query principalId --output tsv)
ACR_ID=$(az acr show --name $CONTAINER_REGISTRY_NAME --query id --output tsv)
az role assignment create --assignee $FUNCTION_APP_ID --role AcrPull --scope $ACR_ID

6. Retrieve the URL of the Azure Function

Finally, retrieve the HTTP trigger function URL of the deployed Azure Function. Use the az functionapp function show command to get the details of the Azure Functions function.

az functionapp function show --resource-group $RESOURCE_GROUP_NAME --name $AZURE_FUNCTION_NAME --function-name HttpExample --query invokeUrlTemplate
# Output: "https://yoshiojavafunc.niceocean-********.eastus.azurecontainerapps.io/api/httpexample"

You can then send a request to the retrieved URL using curl command to confirm that the Azure Functions is working correctly.

curl "https://yoshiojavafunc.niceocean-********.eastus.azurecontainerapps.io/api/httpexample?name=World"
# Expected Output: 
Hello, World

If everything is set up correctly, you should receive a response saying "Hello, World", confirming that your Azure Function is functioning as expected.

Summary

In this guide, you learned how to:

  1. Set up environment variables for your Azure resources.
  2. Create a Java Azure Function project using Maven.
  3. Run the Azure Function locally for testing.
  4. Build a Docker image for the Azure Function.
  5. Push the Docker image to Azure Container Registry.
  6. Create an Azure Container Apps environment and deploy the Java Azure Function.
  7. Assign necessary roles for secure access to Azure Container Registry.
  8. Retrieve and test the URL of the deployed Azure Function.

By following these steps, you can successfully deploy a Java Azure Function on Azure Container Apps, leveraging the benefits of containerization and Azure's integrated management capabilities. If you have any further questions or need assistance with specific steps, feel free to ask!

위 내용은 Azure 컨테이너 앱에 Java Azure 함수 배포의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.