Edit Page

Building, Publishing, and Deploying Docker Containers

Containerizing and Deploying a Python Application with Docker and Azure

In this lecture note, you will learn how to dockerize an application written in Python, publish the Docker image into DockerHub, and deploy the container on the cloud.

We can publish images into any Docker registry such as:

  • Docker Hub
  • GitHub Container Registry
  • GitLab Container Registry

Step 1: Dockerize the Python App

We will use the sample sentiment analysis API that we have used in previous lectures.

  1. Clone the app
git clone https://gitlab.com/cpit490/sentiment-analysis-api.git
cd sentiment-analysis-api
  1. Open the app in your code editor (e.g., VS Code).

  2. Create a new Dockerfile with the following:

FROM python:3.11-slim

# Set the working directory
WORKDIR /app

# Copy the requirements file
COPY requirements.txt .

# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application files
COPY . .

# Expose the port the app runs on
EXPOSE 3000

# Define the command to run the application
CMD ["python", "server.py"]
  1. Build the Docker image:
docker build -t sentiment-analysis-api .
  • The . refers to the path of the directory that contains the Dockerfile, which is the current directory.
  • -t flag tags the image with a name for easy reference.
  1. Run the container
docker run -p 4000:3000 sentiment-analysis-api
  • -p 4000:3000 maps port 4000 on your host machine to port 3000 inside the container.
  • sentiment-analysis-api is the name of the Docker image we built in the previous step.

Step 2: Test the API in the Running Docker Container

Using curl:

curl -X POST http://localhost:4000/sentiment  \
-H "Content-Type: application/json" \
-d '{"text":"The food was wonderful, not too spicy and not too mild; just perfect! I will come back for sure!"}' 

Using Postman:

  1. Open Postman
  2. Create a new POST request to http://localhost:4000/sentiment
  3. Set the Content-Type header to application/json
  4. In the body, select “raw” and “JSON” format
  5. Add the following JSON payload:
    {"text": "The food was wonderful, not too spicy and not too mild; just perfect! I will come back for sure!"}
    
  6. Send the request and verify the response

Step 3: Publish the Image to Docker Hub

  1. Create an account on Docker Hub: Sign up for a free Docker Hub account if you don’t have one.

    • Next, login to Docker Hub on your default browser.
  2. Create a Personal Access Token: For security reasons, Docker Hub requires Personal Access Tokens (PATs) instead of passwords for CLI authentication.

    To create a personal access token:

    • Sign in to Docker Hub
    • Select your avatar in the top-right corner and from the drop-down menu select Account settings
    • Select Personal access tokens
    • Select Generate new token
    • Configure your token:
      • Description: Use a descriptive name (e.g., “Docker CLI Access”)
      • Expiration date: Set based on your security policies
      • Access permissions: Select Read, Write, Delete
    • Select Generate
    • Important: Copy the token and save it securely. You won’t be able to retrieve it once you exit the screen.
  3. Authenticate with Docker Hub: Login to Docker Hub from the Docker CLI using your username and Personal Access Token.

docker login
  • Enter your Docker Hub username and the Personal Access Token from the previous step.
  • It should show Login Succeeded.
  1. Tag your image with your Docker Hub username

The docker tag command creates a new tag (name) for an existing Docker image.

# Replace 'yourusername' with your actual Docker Hub username
docker tag sentiment-analysis-api yourusername/sentiment-analysis-api:latest
  • sentiment-analysis-api is Source image name (the original image we built locally in step 1).
  • yourusername/sentiment-analysis-api:latest is the new tag name with three parts:
    • yourusername - Docker Hub username (replace ‘yourusername’ with your actual Docker Hub username)
    • sentiment-analysis-api is the Docker Hub Repository name
    • latest This is the Tag version (refers to the most recent version)
  1. Push the image to Docker Hub
# Push the tagged image
docker push yourusername/sentiment-analysis-api:latest
  1. Verify the upload
    • Go to your Docker Hub dashboard
    • You should see your sentiment-analysis-api repository listed under your Docker Hub account.

Step 4: Deploy the Published Docker Image

We will deploy the published Docker image into Azure Container Apps, a fully managed serverless container platform for deploying modern apps and microservices using serverless containers.

Step 4.1: Create Container Apps Environment

Container Apps require an environment to run in. This environment acts as a secure boundary around a group of container apps.

  1. Navigate to Container Apps:

    • In the Azure Portal search bar, type “Container Apps” and select it
    • Click + CreateContainer App
  2. Create Container App:

    • Under Project details enter:
      • Subscription: Select your subscription
      • Resource group: Select a resource group
      • Container app name: sentiment-analysis-api
      • Deployment source: Container image
    • Under Container Apps Environment enter:
      • Region: select a region (e.g., East US)
      • Container Apps environment: Click on Create new environment
        • Environment name: enter a name (e.g., sentiment-analysis-api-manage-environment)
        • Zone redundancy: Disabled, we do not need our container App Environment to be zone redundant.
        • Under the Monitoring tab, Logs Destination, select Don’t save logs
        • Under the Networking tab, Public Network Access, select Enable: Allows incoming traffic from the public internet.
        • Virtual Network, Use your own virtual network, select No
        • Click Create
        • Under Container Apps environment, select the created container app environment.
  3. Configure Container Settings:

    • Click Next: Container
    • Uncheck “Use quickstart image” to use your own Docker image
    • Configure the container:
      • Name: sentiment-api
      • Image source: Select “Docker Hub or other registries”
      • Image type: select Public
      • Registry login server: docker.io
      • Image and tag: yourusername/sentiment-analysis-api:latest (replace yourusername with your actual Docker Hub username (e.g., kalharbi/sentiment-analysis-api`)
      • Leave the Command and Argument overrides blank.
      • Development stack: Unspecified
      • Workload profile: Select the default Up tp 4 vCPUs, 8Gib memory
      • CPU and Memory: Select 0.25 CPU cores, 0.5 Gi memory or similar.
  4. Configure Ingress Settings:

    • Click Next: Bindings (skip this step for now)
    • Click Next: Ingress
    • Configure ingress to allow external access:
      • Ingress: Check to Enable Ingress
      • Ingress traffic: Select “Accepting traffic from anywhere”
      • Ingress type: Select “HTTP”
      • Target port: Enter 3000 (this is the port that the containerized Python app listens on inside the container)
  5. Review and Create:

    • Click Next: Tags (optional - you can skip this)
    • Click Next: Review + Create
    • Review all your settings carefully
    • Click Create
    • Wait for the deployment to complete (this may take 3-5 minutes)

Step 4.2: Get the Application URL

  1. Navigate to your Container App:
    • Once the Deployment is successful, click on Go to Resource.sentiment-analysis-app
    • In the Overview section, you’ll see the Application Url
    • Copy this URL - it will look something like: https://sentiment-analysis-app.victorioushill-12345678.eastus.azurecontainerapps.io

Step 4.5: Test the Deployed Application

Now We can test the deployed API to make sure it’s working correctly.

Using curl:

# Replace <your-app-url> with the actual URL from Azure Portal.
curl -X POST https://<your-app-url>/sentiment \
-H "Content-Type: application/json" \
-d '{"text":"The food was wonderful, not too spicy and not too mild; just perfect! I will come back for sure!"}'

Using Postman:

  1. Open Postman
  2. Create a new POST request to https://<your-app-url>/sentiment
  3. Set the Content-Type header to application/json
  4. In the body, select “raw” and “JSON” format
  5. Add the following JSON payload:
    {"text": "The food was wonderful, not too spicy and not too mild; just perfect! I will come back for sure!"}
    
  6. Send the request and verify you get a sentiment analysis response

Step 4.6: Monitor Your Application

Azure Container Apps provides built-in monitoring capabilities:

  1. View Application Logs:

    • In your Container App, navigate to MonitoringLog stream
    • View real-time logs from your application
    • This is helpful for debugging issues
  2. Check Application Metrics:

    • Go to MonitoringMetrics
    • View CPU usage, memory usage, HTTP request count, and response times
  3. Scale Your Application:

    • Go to ApplicationScale and replicas
    • Configure minimum and maximum replicas based on expected load
    • Set up scaling rules based on HTTP requests or other metrics