Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
Java
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Javachevron-right

Getting Started With Azure Spring Apps and MongoDB Atlas: A Step-by-Step Guide

Maxime Beugnet5 min read • Published Jan 27, 2024 • Updated Jan 27, 2024
AzureSpringAtlasJava
FULL APPLICATION
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Introduction

Embrace the fusion of cloud computing and modern application development as we delve into the integration of Azure Spring Apps and MongoDB. In this tutorial, we'll guide you through the process of creating and deploying a Spring Boot application in the Azure Cloud, leveraging the strengths of Azure's platform, Spring Boot's simplicity, and MongoDB's capabilities.
Whether you're a developer venturing into the cloud landscape or looking to refine your cloud-native skills, this step-by-step guide provides a concise roadmap. By the end of this journey, you'll have a fully functional Spring Boot application seamlessly running on Azure Spring Apps, with MongoDB handling your data storage needs and a REST API ready for interaction. Let's explore the synergy of these technologies and propel your cloud-native endeavors forward.

Prerequisites

  • Java 17
  • Maven 3.8.7
  • Git (or you can download the zip folder and unzip it locally)
  • MongoDB Atlas cluster (the M0 free tier is enough for this tutorial). If you don't have one, you can create one for free.
  • Access to your Azure account with enough permissions to start a new Spring App.
  • Install the Azure CLI to be able to deploy your Azure Spring App.
I'm using Debian, so I just had to run a single command line to install the Azure CLI. Read the documentation for your operating system.
1curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
Once it's installed, you should be able to run this command.
1az --version
It should return something like this.
1azure-cli 2.56.0
2
3core 2.56.0
4telemetry 1.1.0
5
6Extensions:
7spring 1.19.2
8
9Dependencies:
10msal 1.24.0b2
11azure-mgmt-resource 23.1.0b2
12
13Python location '/opt/az/bin/python3'
14Extensions directory '/home/polux/.azure/cliextensions'
15
16Python (Linux) 3.11.5 (main, Jan 8 2024, 09:08:48) [GCC 12.2.0]
17
18Legal docs and information: aka.ms/AzureCliLegal
19
20
21Your CLI is up-to-date.
Note: It's normal if you don't have the Spring extension yet. We'll install it in a minute.
You can log into your Azure account using the following command.
1az login
It should open a web browser in which you can authenticate to Azure. Then, the command should print something like this.
1[
2 {
3 "cloudName": "AzureCloud",
4 "homeTenantId": "<MY_TENANT_ID>",
5 "id": "<MY_SUBSCRIPTION_ID>",
6 "isDefault": true,
7 "managedByTenants": [],
8 "name": "MDB-DevRel",
9 "state": "Enabled",
10 "tenantId": "<MY_TENANT_ID>",
11 "user": {
12 "name": "maxime.beugnet@mongodb.com",
13 "type": "user"
14 }
15 }
16]
Once you are logged into your Azure account, you can type the following command to install the Spring extension.
1az extension add -n spring

Create a new Azure Spring App

To begin with, on the home page of Azure, click on Create a resource.
Create a resource
Then, select Azure Spring Apps in the marketplace.
Azure Spring Apps
Create a new Azure Spring App.
Create a new Azure Spring App
Now, you can select your subscription and your resource group. Create a new one if necessary. You can also create a service name and select the region.
Basics to create an Azure Spring App
For the other options, you can use your best judgment depending on your situation but here is what I did for this tutorial, which isn't meant for production use...
  • Basics:
    • Hosting: "Basic" (not for production use, but it's fine for me)
    • Zone Redundant: Disable
    • Deploy sample project: No
  • Diagnostic settings:
    • Enable by default.
  • Application Insights:
    • Disable (You probably want to keep this in production)
  • Networking:
    • Deploy in your own virtual network: No
  • Tags:
    • I didn't add any
Here is my Review and create summary:
Review and create
Once you are happy, click on Create and wait a minute for your deployment to be ready to use.

Prepare our Spring application

In this tutorial, we are deploying this Java, Spring Boot, and MongoDB template, available on GitHub. If you want to learn more about this template, you can read my article, but in a few words: It's a simple CRUD Spring application that manages a persons collection, stored in MongoDB with a REST API.
  • Clone or download a zip of this repository.
1git clone git@github.com:mongodb-developer/java-spring-boot-mongodb-starter.git
1cd java-spring-boot-mongodb-starter
2mvn clean package
If everything went as planned, you should now have a JAR file available in your target folder named java-spring-boot-mongodb-starter-1.0.0.jar.

Create our microservice

In Azure, you can now click on Go to resource to access your new Azure Spring App.
Go to resource
Now, we can create our first microservice. Click on Create App.
Create app
Insert a name for your application, select Java 17, and click Create.
Go to resource
You can now access your new microservice.
Access your microservice

Environment variables

In our Java project, our application.properties file contains the following:
1spring.data.mongodb.uri=${MONGODB_URI:mongodb://localhost}
This means that our Spring application will try to find a MongoDB URI in the MONGODB_URI environment variable first, and will default to mongodb://localhost if it doesn't exist.
As we want to connect our microservice to our cluster in MongoDB Atlas, we have to set this environment variable correctly.
1mongodb+srv://user:password@free.ab12c.mongodb.net/?retryWrites=true&w=majority
  • Create a new environment variable in your configuration.
Create a new environment variable
Note: If you don't have a database user, it's time to create one and use the login and password in your connection string.

Atlas network access

MongoDB Atlas clusters only accept TCP connections from known IP addresses.
As our Spring application will try to connect to our MongoDB cluster, we need to add the IP address of our microservice in the Atlas Network Access list.
  • Retrieve the outbound IP address in the Networking tab of our Azure Spring App.
Retrieve the outbound IP address
  • Add this IP address to the network access list in Atlas.
Add IP address in the Network Access list in Atlas

Deploy our microservice

We can now deploy our JAR file!
Click on the Apps tab and Deploy app.
Deploy app tab
You'll see the instructions to deploy your application.
Deploy app instructions
  • We have to set our Subscription ID:
1az account set -s <SUBSCRIPTION_ID>
  • We can deploy!
1az spring app deploy -s mongodb-spring-apps -g MaximeSpringApps -n mongodb-persons-app --artifact-path target/java-spring-boot-mongodb-starter-1.0.0.jar
If everything went well, you should see some logs happily telling you that the Spring app fired up successfully and hooked up with our MongoDB Atlas cluster.
Microservice deployed

Assign an endpoint

Finally, we need to assign an endpoint to our service to start discussing with the REST API.
Assign endpoint
Retrieve the endpoint to test the REST API. For me, it's:
Retrieve endpoint
1https://mongodb-spring-apps-mongodb-persons-app.azuremicroservices.io

Test the REST API

You can create a person using the following cURL command. Don't forget to change the endpoint.
1curl -X 'POST' \
2 'https://mongodb-spring-apps-mongodb-persons-app.azuremicroservices.io/api/person' \
3 -H 'accept: */*' \
4 -H 'Content-Type: application/json' \
5 -d '{
6 "firstName": "Maxime",
7 "lastName": "Beugnet",
8 "age": 35,
9 "address": {
10 "number": 123,
11 "street": "rue de la Paix",
12 "postcode": "75000",
13 "city": "Paris",
14 "country": "France"
15 },
16 "insurance": true,
17 "cars": [
18 {
19 "brand": "Peugeot",
20 "model": "3008",
21 "maxSpeedKmH": 280
22 }
23 ]
24}'
You can retrieve the persons from the MongoDB cluster in Atlas using the following cURL command.
1curl "https://mongodb-spring-apps-mongodb-persons-app.azuremicroservices.io/api/persons"
Which should print something like this.
1[
2 {
3 "id": "65adc7d0a227f7388c594704",
4 "firstName": "Maxime",
5 "lastName": "Beugnet",
6 "age": 35,
7 "address": {
8 "number": 123,
9 "street": "rue de la Paix",
10 "postcode": "75000",
11 "city": "Paris",
12 "country": "France"
13 },
14 "createdAt": "2024-01-22T01:55:23.093+00:00",
15 "insurance": true,
16 "cars": [
17 {
18 "brand": "Peugeot",
19 "model": "3008",
20 "maxSpeedKmH": 280.0
21 }
22 ]
23 }
24]
In our MongoDB Atlas cluster, we can confirm that the data was saved correctly.
persons collection in MongoDB Atlas
And because this project also uses Swagger and OpenAPI3, you can access the Swagger UI here:
1https://<YOUR_ENDPOINT>/swagger-ui/index.html
Swagger UI

Conclusion

And that's a wrap! You've smoothly navigated the realms of Azure Spring Apps and MongoDB, crafting a dynamic Spring Boot application in the Azure Cloud. Your microservice is up, the REST API is ready, and MongoDB is seamlessly managing your data.
Consider creating a free Atlas cluster and start exploring all the features MongoDB Atlas has to offer.
Got questions or itching to share your success? Head over to the MongoDB Community Forum – we're all ears and ready to help!
Cheers to your successful deployment, and here's to the exciting ventures ahead! Happy coding! 🚀

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

How to Build a Search Service in Java


Apr 23, 2024 | 11 min read
Article

Why Unstructured Data is a Good Fit for Java


Sep 16, 2024 | 7 min read
Tutorial

Single-Collection Designs in MongoDB with Spring Data (Part 1)


Sep 09, 2024 | 10 min read
Article

Streamlining Java Application Development With MongoDB: A Comprehensive Guide to Using Testcontainers


Jul 22, 2024 | 7 min read
Table of Contents