แก้ไข

แชร์ผ่าน


Build and run a containerized Python web app locally with MongoDB

This article is part of a tutorial about how to containerize and deploy a containerized Python web app to Azure App Service. App Service enables you to run containerized web apps and deploy through continuous integration/continuous deployment (CI/CD) capabilities with Docker Hub, Azure Container Registry, and Visual Studio Team Services. In this part of the tutorial, you learn how to build and run the containerized Python web app locally. This step is optional and isn't required to deploy the sample app to Azure.

Running a Docker image locally in your development environment requires setup beyond deployment to Azure. Think of it as an investment that can make future development cycles easier, especially when you move beyond sample apps and you start to create your own web apps. To deploy the sample apps for Django and Flask, you can skip this step and go to the next step in this tutorial. You can always return after deploying to Azure and work through these steps.

The following service diagram highlights the components covered in this article.

A screenshot of the Tutorial - Containerized Python App on Azure with local part highlighted.

1. Clone or download the sample app

Clone the repository:

# Django
git clone https://github.com/Azure-Samples/msdocs-python-django-container-web-app.git

# Flask
git clone https://github.com/Azure-Samples/msdocs-python-flask-container-web-app.git

Then navigate into that folder:

# Django
cd msdocs-python-django-container-web-app

# Flask
cd msdocs-python-flask-container-web-app

2. Build a Docker image

If you're using one of the framework sample apps available for Django and Flask, you're set to go. If you're working with your own sample app, take a look to see how the sample apps are set up, in particular the Dockerfile in the root directory.

These instructions require Visual Studio Code and the Docker extension. Go to the sample folder you cloned or downloaded and open VS Code with the command code ..

Note

The steps in this section require the Docker daemon to be running. In some installations, for example on Windows, you need to open Docker Desktop, which starts the daemon, before proceeding.

Instructions Screenshot
Open the Docker extension.

If the Docker extension reports an error "Failed to connect", make sure Docker is installed and running. If this is your first time working with Docker, you probably won't have any containers, images, or connected registries.
A screenshot showing how to open the Docker extension in Visual Studio Code.
Build the image.
  • In the project Explorer showing the project files, right-click the Dockerfile and select Build Image....

  • Alternately, you can use the Command Palette (F1 or Ctrl+Shift+P) and type "Docker Images: Build Images" to invoke the command.

For more information about Dockerfile syntax, see the Dockerfile reference.
A screenshot showing how to build the Docker image in Visual Studio Code.
Confirm the image was built.
  • Go to the IMAGES section of the Docker extension.

  • Look for recently built image. The name of the container image is "msdocspythoncontainerwebapp", which is set in the .vscode/tasks.json file.

A screenshot showing how to confirm the built image in Visual Studio Code.

At this point, you have built an image locally. The image you created has the name "msdocspythoncontainerwebapp" and tag "latest". Tags are a way to define version information, intended use, stability, or other information. For more information, see Recommendations for tagging and versioning container images.

Images that are built from VS Code or from using the Docker CLI directly can also be viewed with the Docker Desktop application.

3. Set up MongoDB

For this tutorial, you need a MongoDB database named restaurants_reviews and a collection named restaurants_reviews. The steps in this section show you how to use a local installation of MongoDB or Azure Cosmos DB for MongoDB to create and access the database and collection.

Important

Don't use a MongoDB database you'll use in production. In this tutorial, you'll store the MongoDB connection string in an environment variable. This makes it observable by anyone capable of inspecting your container (for example, using docker inspect).

Step 1: Install MongoDB if it isn't already.

You can check for the installation of MongoDB by using the MongoDB Shell (mongosh).

  • The following command enters the shell and gives you the version of both mongosh and mongoDB server installed on your system:

    mongosh
    
  • The following command gives you just the version of MongoDB server installed on your system:

    mongosh --quiet --exec 'db.version()'
    

If these commands don't work, you might need to explicitly install mongosh or connect mongosh to your MongoDB server.

An alternative in some installations is to directly invoke the Mongo daemon.

mongod --version

Step 2: Edit the mongod.cfg file to add your computer's IP address.

The mongod configuration file has a bindIp key that defines hostnames and IP addresses that MongoDB listens for client connections. Add the current IP of your local development computer. The sample app running locally in a Docker container will communicate to the host machine with this address.

For example, part of the configuration file should look like this:

net:
  port: 27017
  bindIp: 127.0.0.1,<local-ip-address>

Restart MongoDB to pick up changes to the configuration file.

Step 3: Create a database and collection in the local MongoDB database.

Set the database name to "restaurants_reviews" and the collection name to "restaurants_reviews". You can create a database and collection with the VS Code MongoDB extension, the MongoDB Shell (mongosh), or any other MondoDB-aware tool.

For the MongoDB shell, here are example commands to create the database and collection:

> help
> use restaurants_reviews
> db.restaurants_reviews.insertOne({})
> show dbs
> exit

At this point, your local MongoDB connection string is "mongodb://127.0.0.1:27017/", the database name is "restaurants_reviews", and the collection name is "restaurants_reviews".

4. Run the image locally in a container

With information on how to connect to a MongoDB, you're ready to run the container locally. The sample app expects MongoDB connection information to be passed in environment variables. There are several ways to get environment variables passed to container locally. Each has advantages and disadvantages in terms of security. You should avoid checking in any sensitive information or leaving sensitive information in code in the container.

Note

When deployed to Azure, the web app will get connection info from environment values set as App Service configuration settings and none of the modifications for the local development environment scenario apply.

Instructions Screenshot
In the .vscode folder of the sample app, the settings.json file defines what happens when you use the Docker extension and select Run or Run Interactive from the context menu of a Tag. The settings.json file contains two templates each for the (MongoDB local) and (MongoDB Azure) scenarios.

If you're using a local MongoDB database:
  • Replace both instances of <YOUR_IP_ADDRESS> with your IP address.

  • Replace both instances of <CONNECTION_STRING> with the connection string for your MongoDB database.

If you're using an Azure Cosmos DB for MongoDB database:
  • Replace both instances of <CONNECTION_STRING> with the Azure Cosmos DB for MongoDB connection string.
Set the docker.dockerPath configuration setting used by the templates. To set docker.dockerPath, open the VS Code Command Palette (Ctrl+Shift+P), enter "Preferences: Open Workspace Settings", then enter "docker.dockerPath" in the Search settings box. Enter "docker" (without the quotes) for the value of the setting.

Note

Both the database name and collection name are assumed to be restaurants_reviews.

A screenshot showing the settings.json file Visual Studio Code.
Run the image.
  • In the IMAGES section of the Docker extension, find the built image.

  • Expand the image to find the latest tag, right-click and select Run Interactive.

  • You'll be prompted to select the task appropriate for your scenario, either "Interactive run configuration (MongoDB local)" or "Interactive run configuration (MongoDB Azure)".

With interactive run, you'll see any print statements in the code, which can be useful for debugging. You can also select Run which is non-interactive and doesn't keep standard input open.

Important

This step fails if the default terminal profile is set to (Windows) Command Prompt. To change the default profile, open the VS Code Command Palette (Ctrl+Shift+P), enter "Terminal: Select Default Profile", and then select a different profile from the dropdown menu; for example Git Bash or PowerShell.

A screenshot showing how to run a Docker container in Visual Studio Code.
Confirm that the container is running.
  • In the CONTAINERS section of the Docker extension, find the container.

  • Expand the Individual Containers node and confirm that "msdocspythoncontainerwebapp" is running. You should see a green triangle symbol next to the container name if it's running.

A screenshot showing how to confirm a Docker container is running in Visual Studio Code.
Test the web app by right-clicking the container name and selecting Open in Browser.

The browser will open into your default browser as "http://127.0.0.1:8000" for Django or "http://127.0.0.1:5000/" for Flask.
A screenshot showing how to browse the endpoint of a Docker container in Visual Studio Code.
Stop the container.
  • In the CONTAINERS section of the Docker extension, find the running container.

  • Right click the container and select Stop.

A screenshot showing how to stop a running Docker container in Visual Studio Code.

Tip

You can also run the container selecting a run or debug configuration. The Docker extension tasks in tasks.json are called when you run or debug. The task called depends on what launch configuration you select. For the task "Docker: Python (MongoDB local)", specify <YOUR-IP-ADDRESS>. For the task "Docker: Python (MongoDB Azure)", specify <CONNECTION-STRING>.

You can also start a container from an image and stop it with the Docker Desktop application.

Next step