In this tutorial, you learn how to build, configure, and deploy a secure Spring Boot application in Azure App Service that connects to a MongoDB database in Azure (actually, a Cosmos DB database with MongoDB API). When you're finished, you'll have a Java SE application running on Azure App Service on Linux.
In this tutorial, you learn how to:
You can quickly deploy the sample app in this tutorial and see it running in Azure. Just run the following commands in the Azure Cloud Shell, and follow the prompt:
mkdir msdocs-spring-boot-mongodb-sample-app
cd msdocs-spring-boot-mongodb-sample-app
azd init --template msdocs-spring-boot-mongodb-sample-app
azd up
1. Run the sample
First, you set up a sample data-driven app as a starting point. For your convenience, the sample repository, includes a dev container configuration. The dev container has everything you need to develop an application, including the MongoDB database, cache, and all environment variables needed by the sample application. The dev container can run in a GitHub codespace, which means you can run the sample on any computer with a web browser.
Step 2: In the GitHub fork:
Step 3: In the codespace terminal:
mvn package spring-boot:run
.Your application running on port 8080 is available.
, select Open in Browser. You should see the sample application in a new browser tab. To stop the Jetty server, type Ctrl
+C
.Tip
You can ask GitHub Copilot about this repository. For example:
Having issues? Check the Troubleshooting section.
2. Create App Service and Cosmos DBFirst, you create the Azure resources. The steps used in this tutorial create a set of secure-by-default resources that include App Service and Azure Cosmos DB. For the creation process, you specify:
Sign in to the Azure portal and follow these steps to create your Azure App Service resources.
Step 1: In the Azure portal:
Step 2: In the Create Web App + Database page, fill out the form as follows.
Step 3: The deployment takes a few minutes to complete. Once deployment completes, select the Go to resource button. You're taken directly to the App Service app, but the following resources are created:
Having issues? Check the Troubleshooting section.
3. Secure connection secretsThe creation wizard generated the connectivity string for you already as an app setting. However, the security best practice is to keep secrets out of App Service completely. You'll move your secrets to a key vault and change your app setting to a Key Vault reference with the help of Service Connectors.
Step 1: In the App Service page:
Step 2: Create a key vault for secure management of secrets.
Step 3:
Step 4:
Step 5: In the Create connection dialog for the Key Vault connection:
Step 6: You're back in the edit dialog for defaultConnector.
Step 7: To verify your changes:
@Microsoft.KeyVault(...)
, which means that it's a key vault reference because the secret is now managed in the key vault.Having issues? Check the Troubleshooting section.
4. Deploy sample codeIn this step, you configure GitHub deployment using GitHub Actions. It's just one of many ways to deploy to App Service, but also a great way to have continuous integration in your deployment process. By default, every git push
to your GitHub repository kicks off the build and deploy action.
Step 1: In the left menu, select Deployment > Deployment Center.
Step 2: In the Deployment Center page:
.github/workflows
directory. By default, the deployment center creates a user-assigned identity for the workflow to authenticate using Microsoft Entra (OIDC authentication). For alternative authentication options, see Deploy to App Service using GitHub Actions.Step 3:
The string 'java21' is not valid SeVer notation for a Java version
. If you want, select the failed build step in the page to get more information.Step 4: The error shows that something went wrong during the GitHub workflow. To fix it, pull the latest changes into your codespace first. Back in the GitHub codespace of your sample fork, run git pull origin starter-no-infra
. This pulls the newly committed workflow file into your codespace.
Step 5 (Option 1: with GitHub Copilot):
Step 5 (Option 2: without GitHub Copilot):
setup-java@v4
action.java-version
to '21'
.Step 6:
Fix error in java-version
. Or, select and let GitHub Copilot generate a commit message for you.Step 7: Back in the Deployment Center page in the Azure portal:
Step 8: You're taken to your GitHub repository and see that the GitHub action is running. The workflow file defines two separate stages, build and deploy. Wait for the GitHub run to show a status of Complete.
Having issues? Check the Troubleshooting section.
5. Browse to the appStep 1: In the App Service page:
Step 2: Add a few tasks to the list. Congratulations, you're running a web app in Azure App Service, with secure connectivity to Azure Cosmos DB.
Having issues? Check the Troubleshooting section.
6. Stream diagnostic logsAzure App Service captures all messages output to the console to help you diagnose issues with your application. The sample application includes standard Log4j logging statements to demonstrate this capability, as shown in the following snippet:
private static Logger logger = LoggerFactory.getLogger(TodoListController.class);
@Autowired
private TodoItemRepository todoItemRepository;
public TodoListController() {
}
/**
* HTTP GET
*/
@GetMapping(path = "/api/todolist/{index}", produces = {MediaType.APPLICATION_JSON_VALUE})
public TodoItem getTodoItem(@PathVariable("index") String index) {
logger.info("GET request access '/api/todolist/{}' path.", index);
return todoItemRepository.findById(index).get();
}
Step 1: In the App Service page:
Step 2: From the left menu, select Log stream. You see the logs for your app, including platform logs and logs from inside the container.
Learn more about logging in Java apps in the series on Enable Azure Monitor OpenTelemetry for .NET, Node.js, Python and Java applications.
Having issues? Check the Troubleshooting section.
7. Clean up resourcesWhen you're finished, you can delete all of the resources from your Azure subscription by deleting the resource group.
Step 1: In the search bar at the top of the Azure portal:
Step 2: In the resource group page, select Delete resource group.
Step 3:
In this step, you create the Azure resources and deploy a sample app to App Service on Linux. The steps used in this tutorial create a set of secure-by-default resources that include App Service and Azure Cosmos DB.
The dev container already has the Azure Developer CLI (AZD).
From the repository root, run azd init
.
azd init --template javase-app-service-cosmos-redis-infra
When prompted, give the following answers:
Question Answer The current directory is not empty. Would you like to initialize a project here in '<your-directory>'? Y What would you like to do with these files? Keep my existing files unchanged Enter a new environment name Type a unique name. The AZD template uses this name as part of the DNS name of your web app in Azure (<app-name>-<hash>.azurewebsites.net
). Alphanumeric characters and hyphens are allowed.Sign into Azure by running the azd auth login
command and following the prompt:
azd auth login
Create the necessary Azure resources and deploy the app code with the azd up
command. Follow the prompt to select the desired subscription and location for the Azure resources.
azd up
The azd up
command takes about 15 minutes to complete (the Redis cache takes the most time). It also compiles and deploys your application code, but you'll modify your code later to work with App Service. While it's running, the command provides messages about the provisioning and deployment process, including a link to the deployment in Azure. When it finishes, the command also displays a link to the deploy application.
This AZD template contains files (azure.yaml and the infra directory) that generate a secure-by-default architecture with the following Azure resources:
Having issues? Check the Troubleshooting section.
3. Verify connection stringsThe AZD template you use generated the connectivity variables for you already as app settings and outputs the them to the terminal for your convenience. App settings are one way to keep connection secrets out of your code repository.
In the AZD output, find the app setting spring.data.mongodb.uri
. Only the setting names are displayed. They look like this in the AZD output:
App Service app has the following app settings: - spring.data.mongodb.uri - spring.data.mongodb.database - spring.redis.host - spring.redis.port - spring.redis.password - spring.redis.database - spring.redis.ssl - spring.cloud.azure.keyvault.secret.credential.managed_identity_enabled - spring.cloud.azure.keyvault.secret.endpoint - azure.keyvault.uri - azure.keyvault.scope
spring.data.mongodb.uri
contains the connection URI to the Cosmos DB database in Azure. It's a standard Spring Data variable, which your application is already using in the src/main/resources/application.properties file.
In the explorer, navigate to src/main/resources/application.properties and see that your Spring Boot app is already using the spring.data.mongodb.uri
variable to access data.
For your convenience, the AZD template output shows you the direct link to the app's app settings page. Find the link and open it in a new browser tab.
If you look at the value of spring.data.mongodb.uri
, it should be @Microsoft.KeyVault(...)
, which means that it's a key vault reference because the secret is managed in the key vault.
Having issues? Check the Troubleshooting section.
4. Browse to the appIn the AZD output, find the URL of your app and navigate to it in the browser. The URL looks like this in the AZD output:
Deploying services (azd deploy) (â) Done: Deploying service web - Endpoint: <URL>
Add a few tasks to the list.
Congratulations, you're running a web app in Azure App Service, with secure connectivity to Azure Cosmos DB.
Having issues? Check the Troubleshooting section.
5. Stream diagnostic logsAzure App Service can capture console logs to help you diagnose issues with your application. For convenience, the AZD template already enabled logging to the local file system and is shipping the logs to a Log Analytics workspace.
The sample application includes standard Log4j logging statements to demonstrate this capability, as shown in the following snippet:
private static Logger logger = LoggerFactory.getLogger(TodoListController.class);
@Autowired
private TodoItemRepository todoItemRepository;
public TodoListController() {
}
/**
* HTTP GET
*/
@GetMapping(path = "/api/todolist/{index}", produces = {MediaType.APPLICATION_JSON_VALUE})
public TodoItem getTodoItem(@PathVariable("index") String index) {
logger.info("GET request access '/api/todolist/{}' path.", index);
return todoItemRepository.findById(index).get();
}
In the AZD output, find the link to stream App Service logs and navigate to it in the browser. The link looks like this in the AZD output:
Stream App Service logs at: <URL>
Learn more about logging in Java apps in the series on Enable Azure Monitor OpenTelemetry for .NET, Node.js, Python and Java applications.
Having issues? Check the Troubleshooting section.
6. Clean up resourcesTo delete all Azure resources in the current deployment environment, run azd down
and follow the prompts.
azd down
Troubleshooting
Depending on your subscription and the region you select, you might see the deployment status for Azure Cosmos DB to be Conflict
, with the following message in Operation details:
Sorry, we are currently experiencing high demand in <region> region, and cannot fulfill your request at this time.
The error is most likely caused by a limit on your subscription for the region you select. Try choosing a different region for your deployment.
The deployed sample app doesn't show the tasks list appIf you see a Hey, Java developers!
page instead of the tasks list app, App Service is most likely still loading the updated container from your most recent code deployment. Wait a few minutes and refresh the page.
Pricing for the created resources is as follows:
The Java SE container in App Service already has network connectivity to Cosmos DB, but doesn't contain any migration tools or other MongoDB tools. You have a few options:
Using the autogenerated workflow file from App Service as an example, each git push
kicks off a new build and deployment run. From a local clone of the GitHub repository, you make the desired updates and push to GitHub. For example:
git add .
git commit -m "<some-message>"
git push origin main
I don't have permissions to create a user-assigned identity
See Set up GitHub Actions deployment from the Deployment Center.
What can I do with GitHub Copilot in my codespace?You might notice that the GitHub Copilot chat view was already there for you when you created the codespace. For your convenience, we include the GitHub Copilot chat extension in the container definition (see .devcontainer/devcontainer.json). However, you need a GitHub Copilot account (30-day free trial available).
A few tips for you when you talk to GitHub Copilot:
@workspace
. For more information, see Use the @workspace agent.@workspace
) even where to make the changes, but it's not allowed to make the changes for you. It's up to you to add the suggested changes and test it.Learn more about running Java apps on App Service in the developer guide.
Configure a Java app in Azure App Service
Learn how to secure your app with a custom domain and certificate.
Secure with custom domain and certificate
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4