Setting CORS in Azure Functions running inside docker container

Viewed 1074

I have created an azure function that exposes an API that is being used in another project. I would like to enable the team that works on the front end to have a Docker image of our API to help them in their development. I have packed my azure function using the Dockerfile that is being generated when running func init LocalFunctionsProject --worker-runtime dotnet --docker as per this guide

This results in the following Dockerfile contents:

FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS installer-env

COPY . /src/dotnet-function-app
RUN cd /src/dotnet-function-app && \
    mkdir -p /home/site/wwwroot && \
    dotnet publish *.csproj --output /home/site/wwwroot

FROM mcr.microsoft.com/azure-functions/dotnet:2.0
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true


COPY --from=installer-env ["/home/site/wwwroot", "/home/site/wwwroot"]

I have then created a docker-compose.yml file on the front end project:

version: "3.7"
services:
  frontend:
    image: frontend:latest
    build: .  
    ports: 
      - "3000:3000"  
    env_file: 
      - frontend.docker.env
  backend: 
    image: backend:latest
    env_file:
      - backend.docker.env
    ports: 
      - "8080:80"   

This succesfully spins up two containers, one with the front end and another with the backend. Inside my frontend.docker.env I have set my variable to point to the backend so that calls from the front end are directed to http://backend/api/myendpoint However this is where everything fails, Im getting a CORS issue:

What I have tried:

  1. Whenever I call my backend from the exposed 8080 port from Postman, everyhting is working fine. I have tried to manually add an Access-Control-Allow-Origin header set to * on my response which I can verify is coming through in Postman. However the front end is still getting the CORS issue.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://backend/api/myendpoint. (Reason: CORS request did not succeed)

  1. My other approach is changing the web.config inside the azure-functions-host file manually by running the following instruction on my Dockerfile:

RUN sed -i 's/<customHeaders>/<customHeaders><add name="Access-Control-Allow-Origin" value="*" \/><add name="Access-Control-Allow-Headers" value="Content-Type" \/><add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" \/>/g' azure-functions-host/web.config

After that I see the following headers coming from the response in Postman:

Access-Control-Allow-Headers = X-Requested-With,content-type

Access-Control-Allow-Methods = GET, POST, OPTIONS, PUT, PATCH, DELETE

Access-Control-Allow-Origin = *

However Im still facing the same issue. Postman works, the frontend doesnt... Do you have any idea what the issue might be, or how to properly set CORS

0 Answers
Related