1. 序章

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

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

2. Mavenの依存関係と構成

まず、そこでクラウドサービスを利用するにはAzureサブスクリプションが必要です。 現在、無料アカウントここにサインアップできます。

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

> 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"
}

Mavensettings.xmlでAzureサービスプリンシパル認証設定を構成します 、次のセクションの助けを借りて、 :

<server>
    <id>azure-auth</id>
    <configuration>
        <client>aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa</client>
        <tenant>tttttttt-tttt-tttt-tttt-tttttttttttt</tenant>
        <key>password</key>
        <environment>AZURE</environment>
    </configuration>
</server>

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

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

<plugin>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-webapp-maven-plugin</artifactId>
    <version>1.1.0</version>
    <configuration>
        <!-- ... -->
    </configuration>
</plugin>

最新のリリースバージョンはこちらで確認できます。

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

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

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

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

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

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

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

3.1. Webコンテナの展開

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

<configuration>
    <javaVersion>1.8</javaVersion>
    <javaWebContainer>tomcat 8.5</javaWebContainer>
    <!-- ... -->
</configuration>

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

<configuration>
    <linuxRuntime>tomcat 8.5-jre8</linuxRuntime>
    <!-- ... -->
</configuration>

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

<configuration>
    <authentication>
        <serverId>azure-auth</serverId>
    </authentication>
    <appName>spring-azure</appName>
    <resourceGroup>baeldung</resourceGroup>
    <!-- ... -->
</configuration>

アプリケーションをAzureにデプロイすると、AppServiceとして表示されます。 そこで、ここでプロパティを指定しました AppServiceに名前を付けます。 また、リソースとしてのApp Serviceは、 リソースグループコンテナ 、 それでも必要です。

これで、azure-webapp:deploy Maven target を使用してトリガーをプルする準備が整い、次の出力が表示されます。

> mvn clean package azure-webapp:deploy
...
[INFO] Start deploying to Web App spring-baeldung...
[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-baeldung.azurewebsites.net
...

これで、https:// spring -baeldung.azurewebsites.net/hello にアクセスして、「helloazure!」という応答を確認できます。

展開プロセス中に、Azureは自動的にAppServicePlanを作成しました。 Azure App Serviceプランの詳細については、公式ドキュメントを確認してください。 すでにAppServiceプランがある場合は、プロパティを設定できます新しいものを作成しないようにするには:

<configuration>
    <!-- ... -->
    <appServicePlanName>ServicePlanssssssss-bbbb-0000</appServicePlanName>
</configuration>

3.2. FTP展開

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

<configuration>
    <authentication>
        <serverId>azure-auth</serverId>
    </authentication>
    <appName>spring-baeldung</appName>
    <resourceGroup>baeldung</resourceGroup>
    <javaVersion>1.8</javaVersion>

    <deploymentType>ftp</deploymentType>
    <resources>
        <resource>
            <directory>${project.basedir}/target</directory>
            <targetPath>webapps</targetPath>
            <includes>
                <include>*.war</include>
            </includes>
        </resource>
    </resources>
</configuration>

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

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

> mvn clean package azure-webapp:deploy
...
[INFO] Start deploying to Web App spring-baeldung...
[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-baeldung --> /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-baeldung.azurewebsites.net

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

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

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

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

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

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

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

次に、ポータルのアプリでMySQLを有効にします。

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

4.2. Azureアプリ内MySQLを使用したSpringBootアプリケーション

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

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

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

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

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

Azureの展開では、 でazure-webapp-maven-pluginを構成する必要があります

<configuration>
    <authentication>
        <serverId>azure-auth</serverId>
    </authentication>
    <javaVersion>1.8</javaVersion>
    <resourceGroup>baeldung-group</resourceGroup>
    <appName>baeldung-webapp</appName>
    <appServicePlanName>bealdung-plan</appServicePlanName>
    <appSettings>
        <property>
            <name>spring.datasource.url</name>
            <value>jdbc:mysql://127.0.0.1:55738/localdb</value>
        </property>
        <property>
            <name>spring.datasource.username</name>
            <value>uuuuuu</value>
        </property>
        <property>
            <name>spring.datasource.password</name>
            <value>pppppp</value>
        </property>
    </appSettings>
</configuration>

これで、展開を開始できます。

> 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://baeldung-webapp.azurewebsites.net

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

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

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

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

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

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

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

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

Spring Bootアプリをドッキングする方法についての記事はすでにありますが、ここで別のMavenプラグインであるdocker-maven-pluginを使用して、ドッキングを自動化します。

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>1.1.0</version>
    <configuration>
        <!-- ... -->
    </configuration>
</plugin>

最新バージョンはここにあります。

5.1. Azureコンテナレジストリ

まず、 Dockerイメージをアップロードするには、AzureにContainerRegistryが必要です。

それでは、1つ作成しましょう。

az acr create --admin-enabled --resource-group baeldung-group \
  --location japanwest --name baeldungadr --sku Basic

Container Registryの認証情報も必要になります。これは、次を使用して照会できます。

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

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

<server>
    <id>baeldungadr</id>
    <username>baeldungadr</username>
    <password>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</password>
</server>

5.2. Mavenプラグインの構成

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

<properties>
    <!-- ... -->
    <azure.containerRegistry>baeldungadr</azure.containerRegistry>
    <docker.image.prefix>${azure.containerRegistry}.azurecr.io</docker.image.prefix>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>1.0.0</version>
            <configuration>
                <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                <registryUrl>https://${docker.image.prefix}</registryUrl>
                <serverId>${azure.containerRegistry}</serverId>
                <dockerDirectory>docker</dockerDirectory>
                <resources>
                    <resource>
                        <targetPath>/</targetPath>
                        <directory>${project.build.directory}</directory>
                        <include>${project.build.finalName}.jar</include>
                    </resource>
                </resources>
            </configuration>
        </plugin>
        <!-- ... -->
    </plugins>
</build>

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

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

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インスタンスでSpringBootAppを実行する

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

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

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

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

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

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

5.4. Dockerコンテナのデプロイ

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

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

<configuration>
    <containerSettings>
        <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
        <registryUrl>https://${docker.image.prefix}</registryUrl>
        <serverId>${azure.containerRegistry}</serverId>
    </containerSettings>
    <!-- ... -->
</configuration>

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

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

6. 結論

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

いつものように、コードサンプルの完全な実装は、Githubにあります。