AzureにSpring Bootアプリをデプロイする

Spring BootアプリをAzureにデプロイする

1. 前書き

Microsoft Azureは、非常に強固なJavaサポートを備えています。

このチュートリアルでは、SpringBootアプリケーションをAzureプラットフォームで動作させる方法を段階的に説明します。

2. Mavenの依存関係と構成

まず、we do need an Azure subscription to make use of the cloud services there;現在、無料のアカウントhereにサインアップできます。

次に、プラットフォームにログインし、Azure CLIを使用してサービスプリンシパルを作成します。

> az login
To sign in, use a web browser to open the page \
https://microsoft.com/devicelogin and enter the code XXXXXXXX to authenticate.
> az ad sp create-for-rbac --name "app-name" --password "password"
{
    "appId": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
    "displayName": "app-name",
    "name": "http://app-name",
    "password": "password",
    "tenant": "tttttttt-tttt-tttt-tttt-tttttttttttt"
}

次のセクションの助けを借りて、<servers>の下のwe configure Azure service principal authentication settings in our Maven settings.xml


    azure-auth
    
        aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa
        tttttttt-tttt-tttt-tttt-tttttttttttt
        password
        AZURE
    

azure-webapp-maven-pluginを使用してSpring BootアプリケーションをMicrosoftプラットフォームにアップロードするときは、上記の認証構成に依存します。

次のMavenプラグインをpom.xmlに追加しましょう。


    com.microsoft.azure
    azure-webapp-maven-plugin
    1.1.0
    
        
    

最新リリースバージョンhereを確認できます。

このプラグインには多くの構成可能なプロパティがあります。これらのプロパティについては、次の概要で説明します。

3. Spring BootアプリをAzureにデプロイする

環境をセットアップしたので、SpringBootアプリケーションをAzureにデプロイしてみましょう。

/hello」にアクセスすると、アプリケーションは「hello azure!」で応答します。

@GetMapping("/hello")
public String hello() {
    return "hello azure!";
}

このプラットフォームでは、TomcatとJettyの両方にJava Web Appをデプロイできるようになりました。 azure-webapp-maven-pluginを使用すると、アプリケーションをデフォルト(ROOT)アプリケーションとしてサポートされているWebコンテナーに直接デプロイすることも、FTP経由でデプロイすることもできます。

アプリケーションをWebコンテナにデプロイするため、WARアーカイブとしてパッケージ化する必要があることに注意してください。 簡単に思い出してください。how to deploy a Spring Boot WAR into Tomcatを紹介する記事があります。

3.1. Webコンテナの展開

WindowsインスタンスのTomcatにデプロイする場合は、azure-webapp-maven-pluginに次の構成を使用します。


    1.8
    tomcat 8.5
    

Linuxインスタンスの場合、次の構成を試してください。


    tomcat 8.5-jre8
    

Azure認証を忘れないでください。


    
        azure-auth
    
    spring-azure
    example
    

アプリケーションをAzureにデプロイすると、AppServiceとして表示されます。 そこで、ここでは、プロパティ<appName>を指定してAppServiceに名前を付けました。 また、リソースとしてのApp Serviceはresource group containerによって保持される必要があるため、<resourceGroup>も必要です。

Now we’re ready to pull the trigger using the azure-webapp:deploy Maven target、出力が表示されます:

> mvn clean package azure-webapp:deploy
...
[INFO] Start deploying to Web App spring-example...
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: cccccccc-cccc-cccc-cccc-cccccccccccc] \
Instance discovery was successful
[INFO] Target Web App doesn't exist. Creating a new one...
[INFO] Creating App Service Plan 'ServicePlanssssssss-bbbb-0000'...
[INFO] Successfully created App Service Plan.
[INFO] Successfully created Web App.
[INFO] Starting to deploy the war file...
[INFO] Successfully deployed Web App at \
https://spring-example.azurewebsites.net
...

Now we can access https://spring-example.azurewebsites.net/helloを実行し、応答「helloazure!」を確認します。

展開プロセス中に、Azureは自動的にApp Serviceプランを作成しました。 Azure App Serviceプランの詳細については、official documentを確認してください。 すでにAppServiceプランがある場合は、プロパティ<appServicePlanName>を設定して、新しいプランが作成されないようにすることができます。


    
    ServicePlanssssssss-bbbb-0000

3.2. FTP展開

FTP経由でデプロイするには、構成を使用できます。


    
        azure-auth
    
    spring-example
    example
    1.8

    ftp
    
        
            ${project.basedir}/target
            webapps
            
                *.war
            
        
    

上記の構成では、プラグインにディレクトリ$\{project.basedir}/targetでWARファイルを見つけさせ、Tomcatコンテナのwebappsディレクトリにデプロイします。

最終的なアーティファクトの名前がazure-0.1.war,であるとすると、デプロイを開始すると、次のような出力が表示されます。

> mvn clean package azure-webapp:deploy
...
[INFO] Start deploying to Web App spring-example...
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: cccccccc-cccc-cccc-cccc-cccccccccccc] \
Instance discovery was successful
[INFO] Target Web App doesn't exist. Creating a new one...
[INFO] Creating App Service Plan 'ServicePlanxxxxxxxx-xxxx-xxxx'...
[INFO] Successfully created App Service Plan.
[INFO] Successfully created Web App.
...
[INFO] Finished uploading directory: \
/xxx/.../target/azure-webapps/spring-example --> /site/wwwroot
[INFO] Successfully uploaded files to FTP server: \
xxxx-xxxx-xxx-xxx.ftp.azurewebsites.windows.net
[INFO] Successfully deployed Web App at \
https://spring-example.azurewebsites.net

ここでは、アプリケーションをTomcatのデフォルトのWebアプリとしてデプロイしなかったため、「https://spring-example.azurewebsites.net/azure-0.1/hello」からのみアクセスできることに注意してください。 サーバーは「hello azure!」と応答します。予想通り。

4. カスタムアプリケーション設定でデプロイする

ほとんどの場合、Spring Bootアプリケーションでは、サービスを提供するためにデータアクセスが必要です。 Azureは、SQL Server、MySQL、PostgreSQLなどのデータベースをサポートするようになりました。

簡単にするために、その構成は他のAzureデータベースサービスと非常に似ているため、データソースとしてアプリ内MySQLを使用します。

4.1. Azureでアプリ内MySQLを有効にする

アプリ内MySQLを有効にしてウェブアプリを作成するためのワンライナーがないため、最初にCLIを使用してウェブアプリを作成する必要があります。

az group create --location japanwest --name bealdung-group
az appservice plan create --name example-plan --resource-group bealdung-group --sku B1
az webapp create --name example-webapp --resource-group example-group \
  --plan example-plan --runtime java|1.8|Tomcat|8.5

次に、enable MySQL in App inthe portal

image

アプリ内MySQLを有効にすると、ファイルシステムの/home/data/mysqlディレクトリの下にあるMYSQLCONNSTR_xxx.txtという名前のファイルで、デフォルトのデータベース、データソースURL、およびデフォルトのアカウント情報を見つけることができます。

4.2. Azure In-App MySQLを使用したSpring Bootアプリケーション

ここでは、デモンストレーションのニーズに応じて、Userエンティティと、registerおよびlistUsers:に使用される2つのエンドポイントを作成します。

@PostMapping("/user")
public String register(@RequestParam String name) {
    userRepository.save(userNamed(name));
    return "registered";
}

@GetMapping("/user")
public Iterable userlist() {
    return userRepository.findAll();
}

ローカル環境でH2データベースを使用し、Azure上のMySQLに切り替えます。 通常、データソースのプロパティはapplication.propertiesファイルで構成します。

spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=

Azureデプロイメントの場合、we need to configure azure-webapp-maven-plugin in *<appSettings>*:


    
        azure-auth
    
    1.8
    example-group
    example-webapp
    bealdung-plan
    
        
            spring.datasource.url
            jdbc:mysql://127.0.0.1:55738/localdb
        
        
            spring.datasource.username
            uuuuuu
        
        
            spring.datasource.password
            pppppp
        
    

これでデプロイを開始できます:

> mvn clean package azure-webapp:deploy
...
[INFO] Start deploying to Web App custom-webapp...
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: cccccccc-cccc-cccc-cccc-cccccccccccc] \
Instance discovery was successful
[INFO] Updating target Web App...
[INFO] Successfully updated Web App.
[INFO] Starting to deploy the war file...
[INFO] Successfully deployed Web App at \
https://example-webapp.azurewebsites.net

ログから、展開が完了したことがわかります。

新しいエンドポイントをテストしてみましょう。

> curl -d "" -X POST https://example-webapp.azurewebsites.net/user\?name\=example
registered

> curl https://example-webapp.azurewebsites.net/user
[{"id":1,"name":"example"}]

サーバーの応答はそれをすべて言います。 できます!

5. コンテナー化されたSpring BootアプリをAzureにデプロイする

前のセクションでは、アプリケーションをサーブレットコンテナ(この場合はTomcat)にデプロイする方法を示しました。 スタンドアロンの実行可能なjarとしてデプロイするのはどうですか?

今のところ、Spring Bootアプリケーションをコンテナ化する必要があるかもしれません。 具体的には、ドッキングして画像をAzureにアップロードできます。

how to dockerize a Spring Boot Appに関する記事はすでにありますが、ここではwe’re about to make use of another maven plugin: docker-maven-plugin, to automate dockerization for us:


    com.spotify
    docker-maven-plugin
    1.1.0
    
        
    

最新バージョンはhereで見つけることができます。

5.1. Azure Container Registry

まず、we need a Container Registry on Azure to upload our docker image.

それを作成しましょう:

az acr create --admin-enabled --resource-group example-group \
  --location japanwest --name exampleadr --sku Basic

Container Registryの認証情報も必要になります。これは、次の方法で照会できます。

> az acr credential show --name exampleadr --query passwords[0]
{
  "additionalProperties": {},
  "name": "password",
  "value": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

次に、Mavenのsettings.xmlに次のサーバー認証構成を追加します。


    exampleadr
    exampleadr
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

5.2. Mavenプラグインの構成

次のMavenプラグイン構成をpom.xmlに追加しましょう。


    
    exampleadr
    ${azure.containerRegistry}.azurecr.io



    
        
            com.spotify
            docker-maven-plugin
            1.0.0
            
                ${docker.image.prefix}/${project.artifactId}
                https://${docker.image.prefix}
                ${azure.containerRegistry}
                docker
                
                    
                        /
                        ${project.build.directory}
                        ${project.build.finalName}.jar
                    
                
            
        
        
    

上記の構成では、ドッカーイメージ名、レジストリURL、およびFTP展開のプロパティに類似したいくつかのプロパティを指定しました。

プラグインはDockerfileを見つけるために<dockerDirectory>の値を使用することに注意してください。 Dockerfiledockerディレクトリに置き、その内容は次のとおりです。

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD azure-0.1.jar app.jar
RUN sh -c 'touch /app.jar'
EXPOSE 8080
ENTRYPOINT [ "sh", "-c", "java -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

5.3. DockerインスタンスでSpring Bootアプリを実行する

これで、Dockerイメージを構築し、Azureレジストリにプッシュできます。

> mvn docker:build -DpushImage
...
[INFO] Building image exampleadr.azurecr.io/azure-0.1
...
Successfully built aaaaaaaaaaaa
Successfully tagged exampleadr.azurecr.io/azure-0.1:latest
[INFO] Built exampleadr.azurecr.io/azure-0.1
[INFO] Pushing exampleadr.azurecr.io/azure-0.1
The push refers to repository [exampleadr.azurecr.io/azure-0.1]
...
latest: digest: sha256:0f0f... size: 1375

アップロードが完了したら、exampleadrレジストリを確認しましょう。 リポジトリリストに画像が表示されます。

image

これで、イメージのインスタンスを実行する準備ができました。

image

インスタンスが起動したら、パブリックIPアドレスを介してアプリケーションが提供するサービスにアクセスできます。

> curl http://a.x.y.z:8080/hello
hello azure!

5.4. Dockerコンテナの展開

Azure、Docker Hub、またはプライベートレジストリからのものであるかどうかに関係なく、コンテナレジストリがあるとします。

次のazure-webapp-maven-pluginの構成を使用して、Spring BootWebアプリをコンテナーにデプロイすることもできます。


    
        ${docker.image.prefix}/${project.artifactId}
        https://${docker.image.prefix}
        ${azure.containerRegistry}
    
    

mvn azure-webapp:deployを実行すると、プラグインはWebアプリアーカイブを指定されたイメージのインスタンスにデプロイするのに役立ちます。

次に、インスタンスのIPアドレスまたはAzure AppServiceのURLを介してWebサービスにアクセスできます。

6. 結論

この記事では、デプロイ可能なWARまたはコンテナ内の実行可能なJARとして、Spring BootアプリケーションをAzureにデプロイする方法を紹介しました。 azure-webapp-maven-pluginのほとんどの機能について説明しましたが、まだ検討されていない豊富な機能がいくつかあります。 詳細については、hereを確認してください。

いつものように、コードサンプルの完全な実装はon Githubで見つけることができます。