阿里云「飞天发布时刻」2024来啦!新产品、新特性、新能力、新方案,等你来探~ 了解详情
写点什么

Deploying Java EE apps to Azure: Part 3

  • 2020-03-30
  • 本文字数:7519 字

    阅读完需:约 25 分钟

Deploying Java EE apps to Azure: Part 3

This is the final blog in a series of posts that explore different options for running Java EE workloads on Azure. In this part, we will run the Java EE app on a Kubernetes cluster in Azure.



The previous parts covered how to deploy a Java EE application to an application server which is set up in a Virtual Machine on Microsoft Azureas well as a Docker container in Azure Container Instances.



The example used in the blog post is a simple three-tier application that uses Java EE 8 specifications such as JAX-RS, EJB, CDI, JPA, JSF, Bean Validation. We will use the Payara Server to deploy the application and use PostgreSQL as the relational database.


During the course of the tutorial, we will cover:


  • Postgres setup on Azure

  • Setup and configure Azure Kubernetes Service cluster and Azure Container Registry

  • Dockerize the Java EE app

  • Deploy the application to Kubernetes

  • Explore its functionality


Except for minor changes, the application used in this tutorial has been adapted from this project by Reza Rahman

Pre-requisites

You will need a Microsoft Azure account and the Azure CLI to work through the tutorial.


If you don’t have a Microsoft Azure account, go ahead and sign up for a free one!. The Azure CLI is a cross-platform command-line experience for managing Azure resources — please install it using these instructions.

First things first…

Set your Azure Subscription ID using the Azure CLI which will be used for this tutorial.


To set your Azure subscription ID


export AZURE_SUBSCRIPTION_ID=[to be filled]az account set --subscription $AZURE_SUBSCRIPTION_ID
复制代码


Create a resource group that will contain all the services (resources) which you will create as a part of this tutorial. A resource group is like a logical container that holds related resources for an Azure solution. The resource group includes those resources that you want to manage as a group.


To create a resource group


export AZURE_RESOURCE_GROUP_NAME=[to be filled]export AZURE_LOCATION=[to be filled]az group create --name $AZURE_RESOURCE_GROUP_NAME --location $AZURE_LOCATION
复制代码

Install Postgres on Azure

Azure Database for PostgreSQL is a relational database service based on the open-source Postgres database engine. It’s a fully managed database-as-a-service offering which is available in two deployment options, as a single server and as a Hyperscale (Citus) cluster


We will be using the single server option for the purposes of this tutorial


We will use the az postgres server createcommand to create a Postgres server instance on Azure. First, set up some of the server properties such as the name, admin user, etc.


export AZURE_POSTGRES_SERVER_NAME=[to be filled]export AZURE_POSTGRES_ADMIN_USER=[to be filled]export AZURE_POSTGRES_ADMIN_PASSWORD=[to be filled]export SKU=B_Gen5_1export STORAGE=5120
复制代码


For storage and SKU options, please refer to the documentation


And, then invoke the command to initiate the database instance creation:


az postgres server create --resource-group $AZURE_RESOURCE_GROUP_NAME --name $AZURE_POSTGRES_SERVER_NAME  --location $AZURE_LOCATION --admin-user $AZURE_POSTGRES_ADMIN_USER --admin-password $AZURE_POSTGRES_ADMIN_PASSWORD --storage-size $STORAGE --sku-name $SKU
复制代码


The provisioning process will take a few minutes.


To check the details of the Postgres database instance you just provisioned, invoke az postgres server show command


az postgres server show --resource-group $AZURE_RESOURCE_GROUP_NAME --name $AZURE_POSTGRES_SERVER_NAME
复制代码


You should get a JSON response. Please note down the value for the fullyQualifiedDomainName attribute as you will be using this to connect to the Postgres instance later.


It should be of the format: *[AZURE_POSTGRES_DB_NAME].postgres.database.azure.com*

Azure Kubernetes Service (AKS) setup

You need the az aks create command to stand up a Kubernetes cluster on Azure


To keep things simple, the below command creates a single node cluster. Feel free to change the specification as per your requirements


export AKS_CLUSTER_NAME=[to be filled]az aks create --resource-group $AZURE_RESOURCE_GROUP --name $AKS_CLUSTER_NAME --node-count 1 --node-vm-size Standard_B2s --node-osdisk-size 30 --generate-ssh-keys
复制代码


Get the AKS cluster credentials using az aks get-credentials - as a result, kubectl will now point to your new cluster. You can confirm the same


az aks get-credentials --resource-group $AZURE_RESOURCE_GROUP --name $AKS_CLUSTER_NAMEkubectl get nodes
复制代码


If you are interested in learning Kubernetes and Containers using Azure, simply create a *free*account and get going! A good starting point is to use the quickstarts, tutorials and code samples in the documentation to familiarize yourself with the service. I also highly recommend checking out the 50 days Kubernetes Learning Path. Advanced users might want to refer to Kubernetes best practices or the watch some of the videos for demos, top features and technical sessions.

Allow AKS to access the Postgres database

The Postgres database is not accessible to external services by default. We can use the az postgres server firewall-rule create command to create a firewall rule to explicitly allow Azure services to access the Postgres instance. This will allow the JavaEE application deployed in AKS to communicate with Postgres.


export FIREWALL_RULE_NAME=AllowJavaEECafeAppOnAKSaz postgres server firewall-rule create --resource-group $AZURE_RESOURCE_GROUP_NAME --server-name $AZURE_POSTGRES_SERVER_NAME --start-ip-address=0.0.0.0 --end-ip-address=0.0.0.0 --name $FIREWALL_RULE_NAME
复制代码


Note: This setting allows network connections from all IPs within the Azure network. For production use, try to configure the most restrictive firewall rules possible

Setup Azure Container Registry

Azure Container Registry is a managed, private Docker registry service to store and manage your private Docker container images (it based on the open-source Docker Registry 2.0). You can use Azure container registries with your existing container development and deployment pipelines, or use Azure Container Registry Tasks to build container images in Azure. You can either build on-demand, or fully automate builds with triggers such as source code commits and base image updates.


Let’s create a registry to store the Docker image for the JavaEE application. We will use the az acr createcommand


export ACR_NAME=[to-be-filled]az acr create --resource-group $AZURE_RESOURCE_GROUP_NAME --name $ACR_NAME --sku Basic --admin-enabled true
复制代码


We are using the *Basic* SKU. Valid value are: *Basic*, *Classic*, *Premium*, *Standard*


You can log in to the registry once it’s created and check the login server


az acr login --name $ACR_NAMEaz acr show --name $ACR_NAME --query loginServer --output table
复制代码


You will use the ACR login server name soon. Its value follows the format: *[ACR_NAME].azurecr.io*

Configure Azure Container Registry to work with Azure Kubernetes Service

To access images stored in Azure Container Registry, you must grant the Azure Kubernetes Service service principal the correct rights to pull images from ACR.


Get the appId of the service principal which is associated with your AKS cluster


AKS_SERVICE_PRINCIPAL_APPID=$(az aks show --name $AKS_CLUSTER_NAME --resource-group $AZURE_RESOURCE_GROUP --query servicePrincipalProfile.clientId -o tsv)
复制代码


Find the resource ID for Azure Container Registry


ACR_RESOURCE_ID=$(az acr show --resource-group $AZURE_RESOURCE_GROUP --name $ACR_NAME --query "id" --output tsv)
复制代码


Grant acrpull permissions to AKS service principal


az role assignment create --assignee $AKS_SERVICE_PRINCIPAL_APPID --scope $ACR_RESOURCE_ID --role acrpull
复制代码


Our AKS cluster along with ACR is ready to use!

Setup and prepare application image

Clone the git repository


git clone https://github.com/abhirockzz/javaee-on-azure-kubernetescd javaee-on-azure-kubernetes
复制代码


You need to enter the Postgres connectivity information to the ``attribute of the section inweb.xml`.


You can find the *web.xml* file under *javaee-on-azure-iaas/src/main/webapp/WEB-INF*


The format is as follows:


jdbc:postgresql://[POSTGRES_FQDN]:5432/postgres?user=[AZURE_POSTGRES_ADMIN_USER]@[AZURE_POSTGRES_SERVER_NAME]&password=[AZURE_POSTGRES_ADMIN_PASSWORD]&sslmode=require
复制代码


Here are the list placeholders which form a part of the JDBC URL:


  • POSTGRES_FQDN with value of fullyQualifiedDomainName

  • AZURE_POSTGRES_ADMIN_USER with admin user name used to provision PG

  • AZURE_POSTGRES_SERVER_NAME with server name used to provision PG

  • AZURE_POSTGRES_ADMIN_PASSWORD with admin password used to provision PG


Set the required values


export POSTGRES_FQDN=[to be filled]export AZURE_POSTGRES_ADMIN_USER=[to be filled]export AZURE_POSTGRES_SERVER_NAME=[to be filled]export AZURE_POSTGRES_ADMIN_PASSWORD=[to be filled]
复制代码


Simply use these commands to replace


export FILE_NAME=javaee-on-azure-iaas/src/main/webapp/WEB-INF/web.xmlsed -i 's/POSTGRES_FQDN/'"$POSTGRES_FQDN"'/g' $FILE_NAMEsed -i 's/AZURE_POSTGRES_SERVER_NAME/'"$AZURE_POSTGRES_SERVER_NAME"'/g' $FILE_NAMEsed -i 's/AZURE_POSTGRES_ADMIN_USER/'"$AZURE_POSTGRES_ADMIN_USER"'/g' $FILE_NAMEsed -i 's/AZURE_POSTGRES_ADMIN_PASSWORD/'"$AZURE_POSTGRES_ADMIN_PASSWORD"'/g' $FILE_NAME
复制代码


Here is an e.g. of what the `` section will look like:


<data-source>        <name>java:global/JavaEECafeDB</name>        <class-name>org.postgresql.ds.PGPoolingDataSource</class-name>        <url>jdbc:postgresql://foobar-pg.postgres.database.azure.com:5432/postgres?user=foobar@foobar-pg&amp;password=foobarbaz&amp;sslmode=require</url>    </data-source>
复制代码


The application is now configured. Let’s build it!


mvn clean install
复制代码


You should have the WAR file available. To confirm


ls -lrt target | grep javaee-cafe.war
复制代码

Build and push the image to Azure Container Registry

Our application artifact (WAR file) is ready. We can now build the Docker image and push it out to Azure Container Registry. Here is a quick look at the Dockerfile used for this


FROM payara/server-fullCOPY target/javaee-cafe.war $DEPLOY_DIRRUN wget https://jdbc.postgresql.org/download/postgresql-42.2.8.jarRUN cp /opt/payara/postgresql-42.2.8.jar ${PAYARA_DIR}/glassfish/domains/${DOMAIN_NAME}/lib && rm /opt/payara/postgresql-42.2.8.jarEXPOSE 8080
复制代码


It builds on top of the base image for payara/server-full, copies the WARfile to a folder from where it can be automatically detected and deployed, downloads the Postgres JDBC driver and places it in the appropriate location for the Payara application server. That’s it!


export DOCKER_IMAGE=javaee-cafedocker build -t $DOCKER_IMAGE .docker tag $DOCKER_IMAGE $ACR_NAME.azurecr.io/$DOCKER_IMAGE
复制代码


To push the image


docker push $ACR_NAME.azurecr.io/$DOCKER_IMAGE
复制代码


For e.g., if the ACR_NAME (name of the Azure Container Registry) is javaeecafe-acr, the resulting Docker image will be javaeecafe-acr.azurecr.io/javaee-cafe


Use az acr repository list command to check the image.


az acr repository list --name $ACR_NAME --output table
复制代码

Deploy the application to Azure Kubernetes Service

Before deploying the application, please update the Kubernetes manifest file javaee-cafe.yaml with the name of the Docker image. To be specific, update the spec.containers.image with the name of the Azure Container Registry which you specified above


It is assumed that the name of the Docker image is *javaee-azure*, if not please update that as well


spec:  containers:    - name: javaee-cafe      image: <replace_me>.azurecr.io/javaee-azure
复制代码


For e.g.


spec:  containers:    - name: javaee-cafe      image: javaeecafe-acr.azurecr.io/javaee-azure
复制代码


To deploy the application


kubectl apply -f javaee-cafe.yml
复制代码


This should spin up a Pod. Wait for it to transition to Running state.


kubectl get pods -l=app=javaee-cafe -w
复制代码


Once the Pod is Running, confirm that the application has been deployed successfully


kubectl logs -f <replace_with_pod_name>
复制代码


The application deployment should be in progress and finally, you should see the logs similar to the one below (with the Successfully autodeployedmessage)


[AutoDeploy] Successfully autodeployed : /foo/bar/payara5/glassfish/domains/domain1/autodeploy/javaee-cafe.war.]]
复制代码

Explore the application

We use a LoadBalancer Service type to ensure that our Java EE app is accessible outside of the cluster. The creation of a Kubernetes LoadBalancer``Service in Azure does exactly what it’s supposed to i.e. provision an Azure Load Balancer behind the scenes.


apiVersion: v1kind: Servicemetadata:  name: javaee-cafespec:  type: LoadBalancer  ports:    - port: 80      targetPort: 8080  selector:    app: javaee-cafe
复制代码


We can get the load balancer IP by using


kubectl get svc javaee-cafe

复制代码


where *javaee-cafe* is the name of the *Service*


The value of the EXTERNAL-IP is the load balancer IP and will be used to access the application

Access the JSF front end

Use your browser to access http://[LOAD_BALANCER_IP]/javaee-cafe. You can use the UI to create, delete and see coffees.


Use the REST API

The application also exposes a REST API for creating, deleting and listing coffees.


export JAVAEE_AKS_REST=http://[LOAD_BALANCER_IP]/javaee-cafe/rest/coffees
复制代码


e.g.


export JAVAEE_AKS_REST=http://23.101.24.139/javaee-cafe/rest/coffees
复制代码


Create coffees


curl -X POST $JAVAEE_AKS_REST -d '{"name":"cappuccino","price":"10"}' -H "Content-Type: application/json"curl -X POST $JAVAEE_AKS_REST -d '{"name":"caffe-latte","price":"15"}' -H "Content-Type: application/json"
复制代码


Get all coffees


curl -H "Accept: application/json" $JAVAEE_AKS_REST
复制代码


You should see a JSON response listing both the coffee options you just added


Get a coffee by ID


curl -H "Accept: application/json" $JAVAEE_AKS_REST/1
复制代码


Delete a coffee by ID


curl -X DELETE $JAVAEE_AKS_REST/1curl -H "Accept: application/json" $JAVAEE_AKS_REST
复制代码


Notice that cappuccino is now deleted

Scale

Right now, we have one instance of our application since we had set spec.replicas to 1 in the Kubernetes manifest. We can scale our application horizontally and Kubernetes will ensure that it spins up and maintains the required number of Pods. To add another instance


kubectl scale deployment javaee-cafe --replicas=2
复制代码


To confirm that another Pod has been spun up:


kubectl get pods -l=app=javaee-cafe -w
复制代码


You can continue accessing the application in the same manner and now the requests will be transparently load balanced amongst your app instances by the Load Balancer.

Clean up resources

Once you are done exploring the application, you can delete the resources. Since we used a resource group, it’s as easy as executing a single command.


Please be aware that this will delete all the resources in the group which includes the ones you created as part of the tutorial as well as any other service instances you might have if you used an already existing resource group


az group delete --name $AZURE_RESOURCE_GROUP_NAME
复制代码

Summary

You learned how to leverage Docker containers to package your Java EE application and deploy it to a Kubernetes cluster in Azure along with a managed database offering for long term persistence.


That brings us to the end of this series exploring some of the common ways of deploying Java EE workloads to Azure. I hope you found it useful!


原文链接https://medium.com/microsoftazure/deploying-java-ee-apps-to-azure-part-3-772e717bc4d1


2020-03-30 19:14424

评论

发布
暂无评论
发现更多内容

选择MobPush的三大理由

MobTech袤博科技

智能推送

推送翻车名场面——Mobpush的推送修改/撤回帮你避免翻车

MobTech袤博科技

卡奥斯第二届1024程序员节正式启动!

Openlab_cosmoplat

1024 1024程序员节 程序员节

语音识别技术的进步与挑战

来自四九城儿

基于云服务器 EC2 的云上堡垒机的设计和自动化实现

亚马逊云科技 (Amazon Web Services)

自动化 Amazon EC2

APP开发者的得力助手:Mobpush六大功能助力实现精准推动服务

MobTech袤博科技

智能推送

语音识别技术:现状、前景与挑战

来自四九城儿

鸿蒙生态助力,嵩山少林首个数字剧本游元服务打造沉浸式体验

最新动态

文心一言 VS 讯飞星火 VS chatgpt (98)-- 算法导论9.3 4题

福大大架构师每日一题

福大大架构师每日一题

元服务助力肉牛产业供应链创新发展,解决“最后一公里”难题

最新动态

iOS应用程序数据保护:如何保护iOS应用程序中的图片、资源和敏感数据

开源协同创新,加速云计算应用

华为云开源

开源 云原生 前端 华为云 低代码前端

传统私有云系统存在哪些问题

青椒云云电脑

私有云 云厂商

学生PC怎么选?云电脑 不买高价硬件也能畅享高配

青椒云云电脑

云电脑

中国私有云未来演进方向

青椒云云电脑

私有云

Serverless 数仓技术与挑战(内含 PPT 下载)

Databend

再也不担心没有测试币了,PandaBridge跨链桥随时兑换无压力

加密先生

跨链桥

私有云有哪些特点,与公有云有什么关系

青椒云云电脑

私有云

低代码助力企业数字化转型

高端章鱼哥

低代码 数字化转型

智能时代的“发动机升级”:数据中心十年之变

脑极体

数据中心

Waves 14 Complete for Mac(后期混音效果全套插件)v2023.08.09激活版

mac

苹果mac Windows软件 Waves 14 Complete 后期混音效果全套插件

虹口有数丨上海市虹口区“一网统管”新解法

浪潮云

云计算

2023年前端流行什么技术和框架了?

互联网工科生

vue.js 前端框架 vue3.0

英特尔为先进科技注入AI动力,帮助客户赢在AI时代

E科讯

DaaS到底是什么 为什么越来越多人在用云桌面办公

青椒云云电脑

云桌面

有一个新工具,能让程序员变成高手,优雅撸它!

树上有只程序猿

低代码 应用开发 JNPF

技术分享| anyRTC音视频混流技术解析

anyRTC开发者

音视频 视频会议 音视频混流 图像合成 音频合成

10分钟设置免费海外远程桌面

亚马逊云科技 (Amazon Web Services)

语音识别技术:进展、挑战和未来

来自四九城儿

私有云架构设计原理

青椒云云电脑

云厂商

数据库OpenTenBase和操作系统OpenCloudOS获信通院Oscar开源尖峰奖

Geek_2d6073

Deploying Java EE apps to Azure: Part 3_文化 & 方法_Azure 中文精选_InfoQ精选文章