Azure App Service Unable to Connect to Azure Cosmos DB (MongoDB API)

Amin Kharaghani 0 Reputation points
2024-10-08T20:25:34.7333333+00:00

Hello!

I'm experiencing an issue where my Flask application hosted on Azure App Service cannot connect to my Azure Cosmos DB (MongoDB API). The connection works fine on my local machine, but fails when deployed to Azure.

Environment:

  1. Azure App Service: Free tier
  2. Azure Cosmos DB (MongoDB API): Free tier
  3. Application Framework: Flask
  4. Database Driver: PyMongo

What I've Done:

  1. Firewall Configurations: Added the outbound IP addresses of my Azure App Service to the allowed IP addresses in the Cosmos DB firewall settings. For testing purposes, I even allowed all public IP addresses in the Cosmos DB firewall settings.
  2. Connection Strings: Tried both mongodb:// and mongodb+srv:// connection strings. The connection string works on my local machine with  mongodb+srv protocol.
  3. SSL/TLS Settings: Ensured SSL is enabled by including ssl=true in the connection string. Configured tls=True and provided tlsCAFile using the certifi.where() method in the MongoClient.
  4. Environment Variables: Confirmed that MONGO_URI, DATABASE_NAME, and OPENAI_API_KEY are correctly set in Azure App Service.

Error Message:

When running on Azure App Service, I receive the following error in the logs:

ERROR:app:Failed to connect to MongoDB: <hostname>:27017: [Errno -5] No address associated with hostname

Code Snippets:

  1. .env File (Sensitive information replaced with placeholders): 
MONGO_URI="mongodb+srv://<username>:<password>@<hostname>/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"
DATABASE_NAME="database-name"
OPENAI_API_KEY="openai-api-key"

  1. app.py:  
  from flask import Flask, request, jsonify, send_from_directory
  from dotenv import load_dotenv
  from flask_cors import CORS
  from pymongo import MongoClient
  import certifi
  import os
  import logging
  
  # Configure logging
  logging.basicConfig(level=logging.INFO)
  logger = logging.getLogger(__name__)
  
  # Load environment variables
  if os.path.exists('.env'):
      load_dotenv()
  
  app = Flask(__name__)
  CORS(app)
  
  # MongoDB connection details
  MONGO_URI = os.getenv('MONGO_URI')
  DATABASE_NAME = os.getenv('DATABASE_NAME')
  
  try:
      if not MONGO_URI or not DATABASE_NAME:
          raise ValueError("MongoDB credentials are not set in the environment variables.")
  
      client = MongoClient(
          MONGO_URI,
          tls=True,
          tlsCAFile=certifi.where(),
          retryWrites=False,
          serverSelectionTimeoutMS=30000  # 30 seconds timeout
      )
      db = client[DATABASE_NAME]
      # Test the connection
      client.admin.command('ping')
      logger.info("Successfully connected to MongoDB")
  except Exception as e:
      logger.error(f"Failed to connect to MongoDB: {str(e)}")
      db = None

Notes:

  1. Password Encoding: The password in the MONGO_URI is URL-encoded due to special characters.
  2. SSL Certificate: Using certifi to handle SSL certificates.
  3. Test Endpoint: Added a /api/test-db endpoint to test the database connection.

What Works:

  1. When I run the application locally, it connects to Azure Cosmos DB without any issues using the same connection string.

What Doesn't Work:

  1. When deployed to Azure App Service, the application fails to connect to the database.
  2. The error suggests that the hostname cannot be resolved.

Additional Information:

  1. Azure Services Access: The option "Allow access from Azure services and resources within Azure to this Cosmos DB account" is enabled.
  2. Firewall Settings: Even with all public IP addresses allowed, the issue persists.
  3. Virtual Network: Not using any virtual network that restricts the Azure App Service.

Questions:

  1. Is there a limitation with the free tier of Azure App Service or Azure Cosmos DB that affects connectivity?
  2. Are there any additional network configurations required to allow my Azure App Service to connect to Azure Cosmos DB?
  3. Could there be an issue with SSL/TLS settings when using the free tier?
  4. Has anyone faced a similar issue or can provide insights into what might be going wrong?

Any help or suggestions would be greatly appreciated!


Thank you!

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,675 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,918 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Sina Salam 12,011 Reputation points
    2024-10-08T22:56:50.17+00:00

    Hello Amin Kharaghani,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    I understand that your Azure App Service unable to connect to Azure Cosmos DB (MongoDB API). You have really done a lot and thank you for the lucid explanatory.

    Let me go straight to your questions:

    Is there a limitation with the free tier of Azure App Service or Cosmos DB that affects connectivity?

    There are no specific limitations in terms of connectivity, but the free tier of Azure App Service has limited networking capabilities, which might affect DNS resolution or overall connection performance. Try upgrading to a paid tier to test if this resolves the issue.

    Are there any additional network configurations required to allow Azure App Service to connect to Cosmos DB?

    Since you’ve enabled "Allow access from Azure services" and added outbound IPs, no additional configurations should be necessary. However, double-check DNS resolution as it seems to be the root cause. Azure App Service might be having trouble resolving the DNS name of the Cosmos DB endpoint. This is more common with the mongodb+srv:// connection string format, which relies on DNS SRV records for sharded clusters. Try switching to the mongodb:// format in the connection string (without SRV protocol) and see if that resolves the issue.

    MONGO_URI="mongodb://<username>:<password>@<hostname>:<port>/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"
    

    Could there be an issue with SSL/TLS settings when using the free tier?

    SSL/TLS should work the same on both free and paid tiers. You are using certifi correctly, and it works locally, so SSL/TLS doesn’t appear to be the problem. However, ensure you're using the appropriate connection parameters (ssl=true or tls=true).

    Has anyone faced a similar issue or can provide insights into what might be going wrong?

    Many have faced DNS-related issues when using mongodb+srv:// in combination with Azure App Service. Using mongodb:// (without SRV) can resolve these DNS issues.

    I hope this is helpful! Do not hesitate to let me know if you have any other questions.


    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.