Übung – Bereitstellen einer Spring AI-Anwendung für Azure-Container-Apps

Abgeschlossen

In dieser Einheit stellen Sie Ihre Spring AI-Anwendung für skalierbares und serverloses Containerhosting in Azure-Container-Apps bereit.

Einrichten von Umgebungsvariablen

Für diese Übung benötigen Sie einige Umgebungsvariablen aus vorherigen Übungen. Wenn Sie dasselbe Bash-Fenster verwenden, sollten diese Variablen weiterhin vorhanden sein. Wenn die Variablen nicht mehr verfügbar sind, verwenden Sie die folgenden Befehle, um sie neu zu erstellen. Ersetzen Sie die <...> Platzhalter unbedingt durch Ihre eigenen Werte, und verwenden Sie dieselben Werte, die Sie zuvor verwendet haben.

export RESOURCE_GROUP=<resource-group>
export LOCATION=<location>
export OPENAI_RESOURCE_NAME=OpenAISpringAI
export AZURE_OPENAI_ENDPOINT=$(az cognitiveservices account show \
    --resource-group $RESOURCE_GROUP \
    --name $OPENAI_RESOURCE_NAME \
    --query "properties.endpoint" \
    --output tsv \
    | tr -d '\r')
export AZURE_OPENAI_API_KEY=$(az cognitiveservices account keys list \
    --resource-group $RESOURCE_GROUP \
    --name $OPENAI_RESOURCE_NAME \
    --query "key1" \
    --output tsv \
    | tr -d '\r')
export DB_SERVER_NAME=<server-name>
export PGHOST=$(az postgres flexible-server show \
    --resource-group $RESOURCE_GROUP \
    --name $DB_SERVER_NAME \
    --query fullyQualifiedDomainName \
    --output tsv \
    | tr -d '\r')

Sie benötigen auch einige neue Umgebungsvariablen für diese Einheit. Verwenden Sie den folgenden Befehl, um diese Variablen zu definieren. Achten Sie darauf, die <...> Platzhalter durch Ihre eigenen Werte zu ersetzen.

export CONTAINER_APP_NAME=<container-app-name>
export MANAGED_IDENTITY_NAME=<managed-identity-name>
export ENVIRONMENT=<Azure-Container-Apps-environment>

Mit diesen Umgebungsvariablen können Sie die Anwendung jetzt in Azure-Container-Apps bereitstellen.

Dockerfile erstellen

Erstellen Sie als Nächstes eine Dockerfile-Datei , und fügen Sie den folgenden Inhalt hinzu. Diese Datei wird verwendet, um ein Docker-Image mit dem Anwendungscode für die Bereitstellung in Azure-Container-Apps zu erstellen.

# Step 1: Use microsoft JDK image with maven3 to build the application
FROM mcr.microsoft.com/openjdk/jdk:17-mariner AS builder
RUN tdnf install maven3 -y
WORKDIR /app
COPY pom.xml ./
COPY src ./src
RUN mvn clean package -DskipTests

# Step 2: Use microsoft JDK image for the final image
FROM mcr.microsoft.com/openjdk/jdk:17-mariner
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]

Bereitstellen der Containeranwendung

Verwenden Sie den folgenden Befehl, um die Anwendung bereitzustellen:

az containerapp up \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --environment $ENVIRONMENT \
    --source . \
    --ingress external \
    --target-port 8080 \
    --location $LOCATION

Dieser Befehl führt die folgenden Aufgaben aus:

  • Erstellt die Ressourcengruppe, sofern sie noch nicht vorhanden ist.
  • Erstellt die Container-Apps-Umgebung mit einem Log Analytics-Arbeitsbereich. Die Umgebung wird mit dem im environment Parameter angegebenen Wert benannt.
  • Erstellt eine Azure Container Registry-Instanz.
  • Erstellt das Containerimage mithilfe des Quellcodes und der Dockerfile im durch den source Parameter angegebenen Verzeichnis und überträgt es dann an die Registrierung.
  • Erstellt und stellt die Container-App mithilfe des erstellten Containerimages bereit. Die Container-App wird mit dem im name Parameter angegebenen Wert benannt.
  • Konfiguriert 8080 als HTTP-Port, den die Container-App zur Annahme eingehenden Datenverkehrs verwendet.
  • Stellt die Container-App in der im location Parameter angegebenen Region bereit.

Verwenden Sie den folgenden Befehl, um die Protokolle Ihrer Container-App anzuzeigen:

az containerapp logs show \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --tail 80

Das folgende Beispiel zeigt ein typisches Protokoll. Wenn Sie die Protokolle überprüfen, können Sie sehen, dass die Anwendung aufgrund fehlender Konfigurationswerte nicht erfolgreich gestartet wird, was zu diesem Zeitpunkt erwartet wird.

{"TimeStamp": "2025-03-04T19:04:52.7673831+00:00", "Log": "F Caused by: org.postgresql.util.PSQLException:
FATAL: Azure AD user token for role[AzureAdmin] is neither an AAD_AUTH_TOKENTYPE_APP_USER or an
AAD_AUTH_TOKENTYPE_APP_OBO token."}

Um die Anwendung nach Änderungen erneut bereitzustellen, können Sie den folgenden Befehl verwenden:

az containerapp update \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --source .

Aktivieren einer verwalteten Identität

Die Container-App muss sich beim PostgresSQL-Server authentifizieren können. Sie verwenden vom System zugewiesene verwaltete Identitäten für die Authentifizierung.

Verwenden Sie den folgenden Befehl, um eine vom System zugewiesene verwaltete Identität für Ihre Container-App zu aktivieren:

az containerapp identity assign \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --system-assigned

Um die ID der vom System zugewiesenen verwalteten Identität abzurufen und anzuzeigen, verwenden Sie die folgenden Befehle:

export MANAGED_IDENTITY_ID=$(az containerapp show \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --query 'identity.principalId' \
    --output tsv \
    | tr -d '\r')
echo "Managed Identity ID: $MANAGED_IDENTITY_ID"

Um die verwaltete Identität Ihrer Container-App für den Zugriff auf die flexible Azure-Datenbank für PostgreSQL-Serverinstanz zu autorisieren, verwenden Sie den folgenden Befehl:

az postgres flexible-server ad-admin create \
    --resource-group $RESOURCE_GROUP \
    --server-name $DB_SERVER_NAME \
    --display-name $MANAGED_IDENTITY_NAME \
    --object-id $MANAGED_IDENTITY_ID \
    --type ServicePrincipal

Konfigurieren der Container-App-Umgebung und des Geheimnisses

Verwenden Sie den folgenden Befehl, um einen geheimen Schlüssel für vertrauliche Werte zu erstellen:

az containerapp secret set \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --secrets \
      azure-openai-api-key=$AZURE_OPENAI_API_KEY

Verwenden Sie als Nächstes den folgenden Befehl, um Umgebungsvariablen festzulegen:

az containerapp update \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --set-env-vars \
      SPRING_AI_AZURE_OPENAI_API_KEY=secretref:azure-openai-api-key \
      SPRING_AI_AZURE_OPENAI_ENDPOINT=${AZURE_OPENAI_ENDPOINT} \
      SPRING_DATASOURCE_USERNAME=${MANAGED_IDENTITY_NAME} \
      SPRING_DATASOURCE_URL=jdbc:postgresql://${PGHOST}/postgres?sslmode=require \
      SPRING_AI_VECTORSTORE_PGVECTOR_SCHEMA_NAME=containerapp

Dieser Befehl verwendet absichtlich einen anderen pgvector Schemanamen, um Konflikte daran zu vermeiden, denselben Schemanamen mit einem anderen Benutzer zu verwenden.

Überprüfen Sie die Bereitstellung

Verwenden Sie den folgenden Befehl, um die CONTAINER-App-URL abzurufen:

export URL=$(az containerapp show \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --query properties.configuration.ingress.fqdn \
    --output tsv)

Verwenden Sie den folgenden Befehl, um den Endpunkt zu testen:

curl -G "https://$URL/api/rag" \
    --data-urlencode "query=How does QuestionAnswerAdvisor work in Spring AI?"

Die Antwort sollte dem folgenden Beispiel ähneln:

In the context of **Spring AI**, the **QuestionAnswerAdvisor** operates as a key component for enabling **Retrieval Augmented Generation (RAG)**, which combines user queries with external contextual data to produce accurate and relevant AI responses.

Verwenden Sie den folgenden Befehl, um eine andere Frage auszuprobieren, die sich nicht im Vektorspeicher befindet:

curl -G "https://$URL/api/rag" \
    --data-urlencode "query=What is vector similarity search?"

Die Antwort sollte dem folgenden Beispiel ähneln:

**Vector similarity search** refers to the process of comparing and ranking data points - represented as vectors - based on their similarity in a multi-dimensional space. This method is commonly used in applications like information retrieval, recommendation systems, natural language processing, and computer vision.

Verwenden Sie den folgenden Befehl, um den Endpunkt der Bloggenerierung zu testen:

curl -G "https://$URL/api/blog" \
    --data-urlencode "topic=Java on Azure"

Aufgrund des Überprüfungszyklus dauert die Bearbeitung dieser Anforderung länger. Nach Abschluss des Vorgangs sollte eine JSON-Antwort angezeigt werden, die sowohl den Bloginhalt als auch Metadaten zum Generierungsprozess enthält, wie im folgenden Beispiel gezeigt:

{
  "metadata": {
    "totalTokensUsed": 8637,
    "approved": false,
    "tokenUsage": {
      "promptTokens": 5324,
      "totalTokens": 8637,
      "completionTokens": 3313
    },
    "model": "Azure OpenAI",
    "editorFeedback": [
      {
        "feedback": "**Feedback:**\n\n1. **Sentence Count Issue:** The draft exceeds the strict 10-sentence maximum requirement. It contains 11 sentences. To comply with the rules, you need to condense the content without losing essential details.\n\n2. **Clarity and Flow of Ideas:** While the draft is informative, the transition between sections feels slightly mechanical. For instance, the sentence about deploying a Spring Boot application being simple could flow better into the discussion about monitoring and diagnostics. Consider smoothing out these transitions to make the blog more cohesive.\n\n3. **Engagement and Reader Interest:** The tone is professional but lacks a conversational spark that would fully engage the reader. Adding a brief anecdote, rhetorical question, or vivid example could help draw readers in. For example, you could open with a scenario like, \"Imagine deploying your Java app to the cloud in minutes, while Azure handles the heavy lifting.\"\n\n4. **Professional Yet Conversational Tone:** While polished, the tone leans slightly towards technical documentation rather than a conversational blog. Use more approachable phrasing to make it relatable to broader audiences, such as developers exploring Azure for the first time.\n\n5. **Structure and Organization:** The draft provides valuable information but feels slightly dense. Breaking it into smaller, more digestible sections or trimming less critical details can improve readability. For example, you could consolidate the points about Azure's tools and services into a single sentence to save space.\n\n6. **Actionable Suggestions:**\n   - Reduce sentence count to meet the 10-sentence maximum by combining or trimming redundant ideas. For example, integrate the points about Azure's services and Spring Boot deployment into a single concise statement.\n   - Add a conversational hook or engaging opening sentence to draw readers in immediately.\n   - Improve transitions between ideas to enhance flow and readability. For instance, connect the infrastructure management point more naturally to the monitoring and diagnostics capabilities.\n   - Consider rephrasing to strike a balance between technical detail and approachable language.\n\n7. **Conclusion Improvement:** The conclusion is strong but could be more dynamic. Consider ending with a forward-looking statement or call-to-action, such as, \"Explore how Azure can revolutionize your Java development journey today.\"\n\nBy implementing these changes, the blog can achieve a more refined, engaging, and reader-friendly result while adhering to the rules.",
        "iteration": 1
      },
      {
        "feedback": "**Feedback:**\n\n1. **Sentence Count:** The draft contains 11 sentences, exceeding the 10-sentence limit. This violates the stated guidelines and must be corrected. Revising for conciseness is necessary.\n\n2. **Clarity and Flow:** While the ideas are clear, the flow feels slightly disjointed. The transitions between Java frameworks, tools, and Azure services could be smoother to create a more cohesive narrative. Consider linking sections with transitional phrases to enhance readability.\n\n3. **Engagement and Reader Interest:** The opening sentence is engaging but could be more specific to immediately hook the reader. For example, instead of \"Imagine deploying your Java app to the cloud,\" consider adding a concrete benefit or scenario that resonates with developers.\n\n4. **Professional yet Conversational Tone:** The tone is professional but leans too heavily on technical descriptions without enough conversational elements. Adding relatable examples or posing direct questions might make the blog more inviting.\n\n5. **Structure and Organization:** The structure is logical but somewhat crowded. Too many points are packed into a small space, leading to information overload. Break the content into digestible chunks and prioritize key ideas.\n\n6. **Adherence to the 10-Sentence Limit:** Beyond trimming the number of sentences, ensure each sentence delivers maximum impact. Avoid redundancy, such as mentioning \"Azure manages infrastructure effortlessly\" and \"Azure supports popular Java frameworks to simplify your development journey,\" which overlap conceptually.\n\n7. **Suggestions for Improvement:**\n   - Reduce sentence count to meet the 10-sentence limit while retaining the essential points.\n   - Strengthen transitions to improve flow.\n   - Rewrite the opening sentence to include a more compelling example or benefit.\n   - Focus on fewer Azure services for clarity and emphasize their unique value instead of listing too many features.\n   - Add a more engaging closing statement that calls the reader to action or leaves a memorable impression.\n\n**Actionable Revision Steps:**\n- Consolidate redundant ideas.\n- Use a more concise, focused approach to highlight Azure's benefits for Java developers.\n- Revise for a conversational yet professional tone that balances technical details with reader engagement.\n\nThis draft shows promise but requires significant refinement to meet the strict evaluation standards.",
        "iteration": 2
      },
      {
        "feedback": "Here is my detailed feedback on the draft:\n\n1. **Sentence Count**: The blog draft contains **10 sentences**, meeting the sentence limit requirement. However, adhering to the rule that all first iterations must receive a NEEDS_IMPROVEMENT rating, the draft will be evaluated critically.\n\n2. **Clarity and Flow of Ideas**: The draft is clear and flows logically, but it lacks specificity in some areas. For instance, phrases like \"Azure simplifies the process\" and \"streamline development workflows\" are somewhat vague. Readers may appreciate concrete examples or brief technical details to substantiate these claims. For example, how exactly does the integration with IntelliJ IDEA streamline workflows?\n\n3. **Engagement and Reader Interest**: While the draft is informative, it could enhance engagement by including a compelling hook. The opening sentence is functional but lacks the punch to immediately captivate readers. Consider starting with a thought-provoking question, statistic, or anecdote tied to Java and cloud computing.\n\n4. **Tone**: The tone is professional yet conversational, which works well for the target audience. However, certain phrases like \"letting you focus on what matters most—your code\" feel slightly generic. Adding a more nuanced observation tailored to Java developers could elevate the tone further.\n\n5. **Structure and Organization**: The structure is solid, but the final call-to-action (\"Ready to take your Java projects to the next level?\") is abrupt and lacks a sense of closure. A stronger conclusion could summarize the benefits discussed and tie them back to the opening idea, creating a more cohesive experience.\n\n6. **Suggestions for Improvement**:  \n   - Add more specificity to claims about Azure's tools and services to make the draft more actionable and informative.  \n   - Craft a more engaging opening sentence to draw readers in immediately.  \n   - Refine the conclusion to provide a sense of completion and reinforce the value proposition.  \n   - Consider rephrasing generic statements to better resonate with the Java developer audience.  \n\nOverall, the draft has potential but needs refinement in its engagement techniques, specificity, and structural polish.",
        "iteration": 3
      }
    ],
    "iterations": 3
  },
  "topic": "Java on Azure",
  "content": "JAVA ON AZURE  \n\nWhat if deploying your Java app to the cloud was as simple as a few clicks, instantly connecting you to millions of users worldwide? Java, the backbone of enterprise software development, pairs effortlessly with Microsoft Azure to transform how developers create, deploy, and scale cloud applications. Whether you're crafting microservices with Spring Boot or managing enterprise systems with Jakarta EE, Azure empowers you with tools and services designed for speed and reliability.  \n\nTake IntelliJ IDEA integration, for example—it streamlines workflows by enabling developers to deploy directly from their IDE, eliminating the need for complex manual setups. Azure App Service simplifies operations even further, allowing you to publish Spring Boot applications with minimal configuration, while Azure Kubernetes Service (AKS) handles container orchestration seamlessly. These features let you focus on writing clean, efficient code without getting bogged down by infrastructure concerns.  \n\nAzure also ensures your applications perform flawlessly with Application Insights, providing end-to-end monitoring for debugging and optimization. Built-in security measures like compliance certifications and encryption safeguard your data, while the pay-as-you-go pricing model lets you scale intelligently based on project demands.  \n\nWith Azure, Java developers can embrace a cloud-first future without compromising on efficiency or control. Ready to unlock new possibilities for your Java projects? Explore how Azure can revolutionize your development journey today.  "
}

Skalieren von Azure-Container-Apps

Standardmäßig ist Ihre Container-App so konfiguriert, dass null Mindestreplikate und eine HTTP-Skalierungsregel verwendet werden, um 10 Anforderungen pro Replikat zu verarbeiten. Verwenden Sie den folgenden Befehl, um die Skalierungskonfiguration zu konfigurieren:

az containerapp update \
    --resource-group $RESOURCE_GROUP \
    --name $CONTAINER_APP_NAME \
    --min-replicas 1 \
    --max-replicas 10 \
    --scale-rule-name http-scaler \
    --scale-rule-type http \
    --scale-rule-http-concurrency 15

Säuberungsaktion

Nachdem Sie die Tests abgeschlossen haben, verwenden Sie die folgenden Befehle, um Ressourcen zu entfernen:

az group delete \
    --name $RESOURCE_GROUP \
    --yes \
    --no-wait

Zusammenfassung der Einheit

In dieser Einheit haben Sie erfolgreich eine Spring AI-Anwendung für Azure Container-Apps mit skalierbarem und serverlosen Containerhosting bereitgestellt. Sie richten erforderliche Umgebungsvariablen ein, erstellt eine Dockerfile-Datei zum Erstellen des Anwendungsimages und bereitstellen die Container-App mithilfe von Azure CLI-Befehlen. Sie haben die verwaltete Identität für die sichere Authentifizierung an den PostgreSQL-Server aktiviert und geheime Schlüssel und Umgebungsvariablen für die Anwendung konfiguriert. Schließlich haben Sie die Bereitstellung überprüft, indem Sie den Anwendungsendpunkt testen und gelernt haben, wie Ressourcen nach dem Testen bereinigt werden.