Multi-stage docker build to deploy Python App to Azure Function App

Prasad ReddyPrasad Reddy
3 min read

Deploying a Python application to an Azure Function App using a multi-stage Docker build involves several steps to ensure efficiency and reliability. This process allows you to create a lightweight and optimized Docker image by separating the build environment from the runtime environment. Hereโ€™s a detailed guide on how to achieve this.

GitHub Repo

https://github.com/vprasadreddy/azure-functions-python-app-docker-multistage-build

Azure Functions Base Images Registry from Microsoft

๐Ÿ’ก
Azure Functions base images Microsoft Container Registry: https://mcr.microsoft.com/catalog?search=functions

Prerequisites

After Prerequisites are installed, create an Azure Function App based on Python framework

Project Folder Structure

Create a new directory/folder

Create a new directory/folder called azure-functions-python-app-multistage-build

mkdir azure-functions-python-app-multistage-build
cd azure-functions-python-app-multistage-build

Initialize Azure Function App

func init --worker-runtime python --docker

Create a Function

The below command will create a function and replaces the contents in the file function_app.py

func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"

function_app.py

import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.route(route="HttpExample", auth_level=func.AuthLevel.ANONYMOUS)
def HttpExample(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

Modify Dockerfile

Copy and paste the below code into existing Docker file and save it. In Stage1, we are building the Python app using a light-weight base image. Next, in Stage2 we are using an image compatible for Python Azure Function App deployment from Microsoft registry.

Dockerfile

# Multi stage Dockerfile to deploy Python code to Azure Function App.

# Stage1
# Use Python base image
FROM python:3.11 AS build

COPY requirements.txt /
RUN pip install --target /home/site/wwwroot -r /requirements.txt

# Stage2
# Use Microsoft Azure Functions base image as it is needed for Function App to be up and running.
# FROM mcr.microsoft.com/azure-functions/python:4-python3.10
FROM mcr.microsoft.com/azure-functions/base:4.0

ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true

# Copy the build files from Stage1
COPY --from=build /home/site/wwwroot /home/site/wwwroot

COPY . /home/site/wwwroot

Build Docker Image

docker build -t azure-functions-python-app .

Create a Docker container based out of the Image

By default Azure Functions run on port 80 and the default image tag is latest until and unless if we specify a tag explicitly.

docker run -d -p 8888:80 azure-functions-python-app

Browse localhost with port 8888 and the Function App should be up and running with default page.

http://localhost:8888

Navigate to HttpExample function that we created in previous steps.

http://localhost:8888/api/HttpExample

Conclusion

I hope you liked this article and learned how to create a docker image with multiple stages for Python App to deploy to Azure Function App.

Please give a like ๐Ÿ‘ and follow me for more such interesting and useful articles ๐Ÿ˜Š

0
Subscribe to my newsletter

Read articles from Prasad Reddy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prasad Reddy
Prasad Reddy

Cloud & DevOps Engineer