Build and Deploy a Microsoft .NET Core Web API application to Amazon App Runner using CloudFormation

海外精选
海外精选的内容汇集了全球优质的亚马逊云科技相关技术内容。同时,内容中提到的“AWS” 是 “Amazon Web Services” 的缩写,在此网站不作为商标展示。
0
0
{"value":"In this blog we show you how to build a Microsoft.NET Web API application with [Amazon Aurora](https://aws.amazon.com/cn/rds/aurora/?trk=cndc-detail) Database using [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail). [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail) makes it easy for developers to quickly deploy containerized web applications and APIs, and helps us start with our source code or a container image.\n\nContainer workload management tasks, such as managing deployments, scaling infrastructure, or keeping it updated, can get cumbersome. [AWS App Runner](https://aws.amazon.com/apprunner/) is a great alternative for customers without any prior containers or infrastructure experience, as it is a fully managed service that takes care of building and deploying your application, load balancing traffic, or autoscaling up or down per your application needs. App Runner retrieves your source code from GitHub or source image from Amazon ECR repository in your AWS account, and creates and maintains a running web service for you in the AWS Cloud.\n\nRecently, App Runner introduced Amazon Virtual Private Cloud (VPC) support. With this feature, you don’t need to have your AWS services publicly accessible. App Runner applications can connect to private endpoints in your VPC, and you can enable a more secure and compliant environment by removing public access to these resources. Check out this [post](https://aws.amazon.com/blogs/aws/new-for-app-runner-vpc-support/) to learn more about how to enable a more secure and compliant environment by removing public access to these resources.\n\nYou can connect App Runner services to databases in [Amazon Relational Database Service (RDS)](https://aws.amazon.com/rds/), Redis or Memcached caches in [Amazon ElastiCache](https://aws.amazon.com/elasticache/), or your own applications running in [Amazon Elastic Container Service (Amazon ECS)](https://aws.amazon.com/ecs/), [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/), [Amazon Elastic Compute Cloud (Amazon EC2)](https://aws.amazon.com/ec2/), or on-premises and connected via [AWS Direct Connect](https://aws.amazon.com/directconnect/). The [VPC connectors](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apprunner-vpcconnector.html) in App Runner work similarly to [VPC networkin](https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/)g in [AWS Lambda](https://aws.amazon.com/lambda/) and are based on [AWS Hyperplane](https://www.youtube.com/watch?v=dfEcd3zqPOA&t=4661s), the internal Amazon network function virtualization system behind AWS services and resources like [Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html), [NAT Gateway](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html), and [AWS PrivateLink](https://aws.amazon.com/privatelink/).\n\nMicrosoft workloads have a lot of Web APIs that are native to Microsoft methods for serving front-end applications (like ASP.NET, ASP.NET Razor/MVC, ReactJS or Angular Application). These applications traditionally talk to Microsoft SQL Server database for CRUD operations. [Entity Framework Core](https://docs.microsoft.com/en-us/ef/core/) (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), which enables .NET developers to work with a database using .NET objects. This helps to eliminate the need for most of the data-access code that typically needs to be written. We use MySql.EntityFramework to connect to [Amazon RDS](https://aws.amazon.com/cn/rds/?trk=cndc-detail) in this blog.\n\nMany of these existing .NET Core applications can be containerized using [Docker](https://www.docker.com/) and AWS services like [Amazon EC2](https://aws.amazon.com/ec2/)/ [Amazon Elastic Container Service (ECS)](https://aws.amazon.com/ecs/)/ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://aws.amazon.com/eks), and can interface with databases like [Amazon Aurora Database](https://aws.amazon.com/rds/aurora/) providing a full blown API application system. In our previous blogs, we showed you how to build a similar Microsoft.NET Web API application with [Amazon Aurora](https://aws.amazon.com/cn/rds/aurora/?trk=cndc-detail) Database using [AWS CloudFormation](https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-cloudformation/) and [AWS CDK](https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-aws-cdk/). In this blog the application architecture is complemented by build tools like [AWS CodeCommit](https://aws.amazon.com/codecommit/) [AWS CodeBuild](https://aws.amazon.com/codebuild/) using [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail). We will create a simple Microsoft .NET Web API for a ToDo Application. See below, the solution architecture diagram of Microsoft .NET Core Web API Application Orchestration . The sample ToDo application will communicate with an [Amazon Aurora](https://aws.amazon.com/cn/rds/aurora/?trk=cndc-detail) Serverless database for basic CRUD operations. Provided CloudFormation templates will build a Web API deployed in [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail) connecting to a RDS Aurora back-end.\n\n![image.png](https://dev-media.amazoncloud.cn/40d24e1a984f492c8be093075a58412a_image.png)\n\n#### **AWS services used in this solution**\n- [Amazon Aurora Serverless](https://aws.amazon.com/rds/aurora/serverless/) is an on-demand, auto-scaling configuration for [Amazon Aurora](https://aws.amazon.com/rds/aurora/). It automatically starts up, shuts down, and scales capacity up or down based on your application’s needs.\n- [AWS App Runner](https://aws.amazon.com/apprunner/) is a managed service that makes it easy for developers to quickly deploy containerized web applications and APIs is used using Docker template containers and allows you to easily run and scale containerized applications on AWS. The ToDo solution for this blog post includes a sample Dockerfile for a .NET Core 3.1 application. Web API code uses AWS SDK Packages like System Manager, MySql EntityFrameworkCore to interact with the database.\n- [Amazon Elastic Container Registry (ECR)](https://aws.amazon.com/ecr/), the AWS provided Docker container registry is used and integrated with App Runner, simplifying the development to production workflow.\n- [AWS CodeBuild](https://aws.amazon.com/codebuild/) is used to manage the continuous integration of development code into Amazon ECR as a containerized image.\n- [AWS CodeCommit](https://aws.amazon.com/codecommit/) is used as the code repository and integrates with [AWS CodeBuild](https://aws.amazon.com/cn/codebuild/?trk=cndc-detail) for continuous integration process.\n\n#### **Prerequisites**\nDocker Containers to deploy the Microsoft .NET Web API Application. Make sure Docker daemon is running if you are trying to run the manual scripts (that builds application image and pushes to Amazon ECR). The following are required to setup your development environment:\n1. [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)\n2. Dotnet CLI: Web API application was built using Microsoft .NET core [3.1](https://dotnet.microsoft.com/en-us/download/dotnet/3.1). Please refer Microsoft Documentation for installation.\n3. Docker: Install [Docker](https://docs.docker.com/get-docker/) depending on your hardware specification. Make sure the docker daemon is running\n4. Additionally, we use AWS SDK, MySql data packages for the Microsoft .NET project and have added them as nuget packages to the solution. In this solution, we use Mysql data to connect to MySql/Aurora database and also AWS SDK Systems Manager to connect to Amazon Systems Manager.\n\n```\\n<PackageReference Include=\\"AWSSDK.SimpleSystemsManagement\\" Version=\\"3.3.106\\" />\\n<PackageReference Include=\\"Amazon.Extensions.Configuration.SystemsManager\\" Version=\\"1.2.0\\" />\\n<PackageReference Include=\\"MySql.EntityFrameworkCore\\" Version=\\"3.1.10+m8.0.23\\" />\\n```\n#### **Solution Walkthrough**\nBelow section will provide steps to provision the infrastructure (and services) and deploy the application. Upon deploying the solution, two [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) stacks namely “net-core-stack-ecr” and “net-core-stack-infra” will be created. CI/CD is achieved through buildspec.yaml file for subsequent checkins on the [AWS CodeCommit](https://aws.amazon.com/cn/codecommit/?trk=cndc-detail) repo that will be used by the [AWS CodeBuild](https://aws.amazon.com/cn/codebuild/?trk=cndc-detail).\n\n##### **Clone the code**\n- Clone the solution code which contains .net api and CloudFormation templates from this [GitHub](https://github.com/aws-samples/aws-apprunner-netcore) location. The source code includes two folders — ‘code’ and ‘config’. The ‘code’ folder has the necessary .NET ToDo Web API solution, and the config folder has the [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) templates, and the script files used for deployment.\n\t- config/net-core-app-ecr.yaml – This template spins up Amazon ECR.\n\t- config/net-core-app-infra.yaml – This template creates a new VPC with [Amazon RDS](https://aws.amazon.com/cn/rds/?trk=cndc-detail), [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail), [AWS CodeBuild](https://aws.amazon.com/cn/codebuild/?trk=cndc-detail), [AWS CodeCommit](https://aws.amazon.com/cn/codecommit/?trk=cndc-detail), Amazon Systems Manager.\n\t- config/buildspec.yaml – This yaml is used by CodeBuild. Steps include building the dotnet application, pushes the image to AWS ECR. Upon pushing a new image to AWS ECR, App Runner will redeploy/re-run the application which will be exposed as an endpoint.\n\t- config/exec_docker.sh – Used by “exec.sh” script when creating the infrastructure for the first time.\n- exec.sh (root folder) – This script is used only during the initial setup to push the dotnet application image to AWS ECR. Provide your AWS Account Number to the script as input. Make sure to setup “aws configure” in the cli to the same account number before executing this script.\n- cleanup.sh (root folder) – This script is used to clean up the entire deployment for this solution.\n\n##### **Deployment**\nThis solution can be provisioned in two ways: fully automated with the provided script(s) (option 1) or can be installed using cli commands (option 2).\n\n###### **Option 1: Run the “exec.sh”**\n```\\nchmod +x exec.sh\\n./exec.sh <YOUR_ACCOUNT_NUMBER>\\n```\nYou will notice two CloudFormation stacks are created (net-core-stack-ecr and net-core-stack-infra). Output of the net-core-stack-infra will provide [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail) Service Url endpoint. Take a few moments to review the services that are spun up in the [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) console.\n\n###### **Option 2: Deploy individual CloudFormation stacks and push image to ECR**\n\nDeploy Amazon ECR CloudFormation stack (config/net-core-app-ecr.yaml)\n```\\naws cloudformation create-stack --stack-name net-core-stack-ecr --template-body file://config/net-core-app-ecr.yaml --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=AppStackName,ParameterValue=net-core-stack-ecr\\n```\nBuild and Deploy application code to Amazon ECR\n\nXML\n```\\ncd code\\ndotnet build .\\nECR_REPO=net-core-stack-repo\\nACCOUNT_NUMBER=<YOUR_ACCOUNT_NUMBER>\\nREGION=us-east-1\\nAPP_SVC=todo/apprunnerdotnetsvc\\n### build the AWS App Runner docker image, tag and push it to AWS ECR\\ndocker build -t \$APP_SVC .\\ndocker tag \$APP_SVC \$ACCOUNT_NUMBER.dkr.ecr.us-east-1.amazonaws.com/\$ECR_REPO:latest\\naws ecr get-login-password --region \$REGION | docker login --username AWS --password-stdin \$ACCOUNT_NUMBER.dkr.ecr.\$REGION.amazonaws.com\\ndocker push \$ACCOUNT_NUMBER.dkr.ecr.us-east-1.amazonaws.com/\$ECR_REPO:latest\\ncd ..\\n```\nDeploy the other CloudFormation stack for infra/services needed for the solution (config/net-core-app-infra.yaml)\n```\\naws cloudformation create-stack --stack-name net-core-stack-infra --template-body file://config/net-core-app-infra.yaml --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=AppStackName,ParameterValue=net-core-stack-infra\\n```\n##### **Application CICD**\nWith the above deployment we have successful setup a CICD solution which will enable you to make further updates to the dotnet application code and manage automatic deployment to [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail). You can clone the code from [AWS CodeCommit](https://aws.amazon.com/cn/codecommit/?trk=cndc-detail) into a local folder and make updates as needed.\n\nBelow are commands to clone and push updates to [AWS CodeCommit](https://aws.amazon.com/cn/codecommit/?trk=cndc-detail):\n```\\n# set source directory where you have this current code downloaded from github\\nSOURCE_DIR=\$pwd\\n# copy and git push steps to codecommit\\nmkdir codecommit\\ncd codecommit\\ngit clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/net-core-stack-ecr-repo\\ncd ..\\nmkdir codecommit/net-core-stack-ecr-repo/code codecommit/net-core-stack-ecr-repo/config\\ncp -R SOURCE_DIR/code/* codecommit/net-core-stack-ecr-repo/code\\ncp -R SOURCE_DIR/config/* codecommit/net-core-stack-ecr-repo/config\\ncd codecommit/net-core-stack-ecr-repo\\ngit add .\\ngit commit -m \\"test cicd commit\\"\\ngit push\\n\\n```\n#### **Solution Validation**\nVerify by visiting the App Runner console to view the application (net-core-stack-apprunner-svc) that has been deployed. In the application, visit the “Logs” tab to view the details about service creation, image pull from ECR, health check on port 8080 before routing traffic to application. A sample Event log will be as below.\n```\\n02-02-2022 04:00:28 PM [AppRunner] Service status is set to RUNNING.\\n02-02-2022 04:00:28 PM [AppRunner] Service creation completed successfully.\\n02-02-2022 04:00:27 PM [AppRunner] Successfully routed incoming traffic to application.\\n02-02-2022 03:59:56 PM [AppRunner] Health check is successful. Routing traffic to application.\\n02-02-2022 03:58:59 PM [AppRunner] Performing health check on port '8080'.\\n02-02-2022 03:58:51 PM [AppRunner] Provisioning instances and deploying image.\\n02-02-2022 03:58:39 PM [AppRunner] Successfully pulled image from ECR.\\n02-02-2022 03:56:54 PM [AppRunner] Successfully created pipeline for automatic deployments.\\n02-02-2022 03:56:35 PM [AppRunner] Service status is set to OPERATION_IN_PROGRESS.\\n02-02-2022 03:56:35 PM [AppRunner] Service creation started.\\n```\nGo to [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) console and in the Infra stack output tab get the “AppRunnerServiceUrl” to test the health check api on a browser. A sample url will be like – http://gcdpsgaztx.us-east-1.awsapprunner.com/api/values\nTo test the application endpoint, you can use tools like Postman, ARC Rest Client or Browser extensions like RestMan. Select “content-type” as “application/json”, POST as raw data/json – sample input below -https:///api/todo\n```\\n{\\n\\"Task\\": \\"new ToDo Application\\",\\n\\"Status\\": \\"Done\\"\\n}\\n```\nUse the same url and fire a GET call to see the previously posted todo item as response.\n```\\nhttps://<YOUR_APP_RUNNER_URL>/api/todo/Done\\n```\n#### **Clean Up**\nOption 1: You can run the provided “cleanup.sh” to clean up the entire solution\n```\\nchmod +x cleanup.sh\\n.\\\\cleanup.sh\\n```\nOption 2: If you like to individually execute the following commands.\n```\\naws ecr batch-delete-image --repository-name net-core-stack-ecr-repo --image-ids imageTag=latest\\n\\naws ecr batch-delete-image --repository-name net-core-stack-ecr-repo --image-ids imageTag=untagged`Delete the entire infrastructure\\n```\n```\\naws cloudformation delete-stack --stack-name net-core-stack-ecr \\naws cloudformation delete-stack --stack-name net-core-stack-infra\\n```\n#### **Troubleshooting**\n\n- **[AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) Stacks Failure**: If you notice any of the CloudFormation stack failures below steps would help to triage.\n\t- ecr-stack: Make sure Docker daemon is running; Check the CloudFormation “Outputs” of the ecr-stack to verify the ECR arn. Look at the Events tab to see if any failures have occurred.\n\t- infra stack: Review the AWS service limits. Ex: 5 VPCs per region; Make sure ECR stack is created with docker image (application code as docker container images in there). Look at the Events tab to see if any failures have occurred.\n- **RDSCluster Connectivit**\n\t- Use AWS RDS console to verify the new RDS cluster. Connectivity to RDS Endpoints/credentials will be in [AWS Systems Manager](https://aws.amazon.com/cn/systems-manager/?trk=cndc-detail).\n\t- Table/Model entity will not be created unless ToDo Url POST is triggered.\n\t- Note: Inactivity in Aurora Serverless – RDS Table could put the RDS in suspended state to reduce the cost. You might receive a communication error after no activity while trying to invoke the database DDL/DML statements. If the application provided API times out (especially after the initial setup, you may have to invoke the POST/GET call invoke on the /api/todo endpoint). You might notice this by connecting to the SQL in Query Editor with below output.Retrying the select queries will warm up the RDS database for subsequent connection to be served.\n```\\nCommunications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server\\n```\n\n- AWS AppRunner\n\t- Verify App Runner application “Event Logs” and “Deployment logs”.\n\t- By default, the application is coded to run in port 8080. Make sure they are seen in application log.\n\t- Check the health check url to see the test endpoint\n\t- Check the ToDo Url to post the data from tools like Postman or RestMan (Google Chrome/MS Edge plugin). Check if the data is available in RDS database.\n\n#### **Conclusion**\nTo recap, in this post we built and deployed an ASP.NET Core Web API application that interacts with various AWS Services. We also walked through in this example how to deploy Microsoft .NET Core application code as containers with infrastructure as code. We encourage you to test this example and see for yourself how this overall application design works within AWS. Then, it will be just the matter of replacing your individual code base (buildspec/WebAPI, MVC, or other Microsoft .NET core application) and package them as Docker container and let the [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail) handle the process efficiently.\n\nIf you implement this example and run into any issues, or have any questions or feedback about this blog please provide your comments below!\n\n##### **References**\n- [AWS App Runner Documentation](https://docs.aws.amazon.com/apprunner/)\n- [New for App Runner – VPC Support | AWS News Blog (amazon.com)](https://aws.amazon.com/blogs/aws/new-for-app-runner-vpc-support/)\n- [Networking with App Runner – AWS App Runner (amazon.com)](https://docs.aws.amazon.com/apprunner/latest/dg/network.html)\n- [Developing a Microsoft .NET Core Web API application with Aurora Database using CloudFormation](https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-cloudformation/)\n- [Build and deploy a Spring Boot application to AWS App Runner with a CI/CD pipeline using Terraform](https://aws.amazon.com/blogs/containers/build-and-deploy-a-spring-boot-application-to-aws-app-runner-with-a-ci-cd-pipeline-using-terraform/)\n\n##### **About the Authors**\n\n![image.png](https://dev-media.amazoncloud.cn/e320ac21653c40cab748ce71f006392a_image.png)\n\nSivasubramanian Ramani (Siva Ramani) is a Sr Cloud Application Architect at AWS. His expertise is in application optimization, serverless solutions and using Microsoft application workloads with AWS.\n\n![image.png](https://dev-media.amazoncloud.cn/3d583dbbdb30445fa0733bf24e28980d_image.png)\n\nNaveen Balaraman is a Cloud Application Architect at Amazon Web Services. He is passionate about Containers, serverless Applications, Architecting Microservices and helping customers leverage the power of AWS cloud.","render":"<p>In this blog we show you how to build a Microsoft.NET Web API application with Amazon Aurora Database using AWS App Runner. AWS App Runner makes it easy for developers to quickly deploy containerized web applications and APIs, and helps us start with our source code or a container image.</p>\n<p>Container workload management tasks, such as managing deployments, scaling infrastructure, or keeping it updated, can get cumbersome. <a href=\\"https://aws.amazon.com/apprunner/\\" target=\\"_blank\\">AWS App Runner</a> is a great alternative for customers without any prior containers or infrastructure experience, as it is a fully managed service that takes care of building and deploying your application, load balancing traffic, or autoscaling up or down per your application needs. App Runner retrieves your source code from GitHub or source image from Amazon ECR repository in your AWS account, and creates and maintains a running web service for you in the AWS Cloud.</p>\\n<p>Recently, App Runner introduced Amazon Virtual Private Cloud (VPC) support. With this feature, you don’t need to have your AWS services publicly accessible. App Runner applications can connect to private endpoints in your VPC, and you can enable a more secure and compliant environment by removing public access to these resources. Check out this <a href=\\"https://aws.amazon.com/blogs/aws/new-for-app-runner-vpc-support/\\" target=\\"_blank\\">post</a> to learn more about how to enable a more secure and compliant environment by removing public access to these resources.</p>\\n<p>You can connect App Runner services to databases in <a href=\\"https://aws.amazon.com/rds/\\" target=\\"_blank\\">Amazon Relational Database Service (RDS)</a>, Redis or Memcached caches in <a href=\\"https://aws.amazon.com/elasticache/\\" target=\\"_blank\\">Amazon ElastiCache</a>, or your own applications running in <a href=\\"https://aws.amazon.com/ecs/\\" target=\\"_blank\\">Amazon Elastic Container Service (Amazon ECS)</a>, <a href=\\"https://aws.amazon.com/eks/\\" target=\\"_blank\\">Amazon Elastic Kubernetes Service (EKS)</a>, <a href=\\"https://aws.amazon.com/ec2/\\" target=\\"_blank\\">Amazon Elastic Compute Cloud (Amazon EC2)</a>, or on-premises and connected via <a href=\\"https://aws.amazon.com/directconnect/\\" target=\\"_blank\\">AWS Direct Connect</a>. The <a href=\\"https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apprunner-vpcconnector.html\\" target=\\"_blank\\">VPC connectors</a> in App Runner work similarly to <a href=\\"https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/\\" target=\\"_blank\\">VPC networkin</a>g in <a href=\\"https://aws.amazon.com/lambda/\\" target=\\"_blank\\">AWS Lambda</a> and are based on <a href=\\"https://www.youtube.com/watch?v=dfEcd3zqPOA&amp;t=4661s\\" target=\\"_blank\\">AWS Hyperplane</a>, the internal Amazon network function virtualization system behind AWS services and resources like <a href=\\"https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html\\" target=\\"_blank\\">Network Load Balancer</a>, <a href=\\"https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html\\" target=\\"_blank\\">NAT Gateway</a>, and <a href=\\"https://aws.amazon.com/privatelink/\\" target=\\"_blank\\">AWS PrivateLink</a>.</p>\\n<p>Microsoft workloads have a lot of Web APIs that are native to Microsoft methods for serving front-end applications (like ASP.NET, ASP.NET Razor/MVC, ReactJS or Angular Application). These applications traditionally talk to Microsoft SQL Server database for CRUD operations. <a href=\\"https://docs.microsoft.com/en-us/ef/core/\\" target=\\"_blank\\">Entity Framework Core</a> (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), which enables .NET developers to work with a database using .NET objects. This helps to eliminate the need for most of the data-access code that typically needs to be written. We use MySql.EntityFramework to connect to [Amazon RDS](https://aws.amazon.com/cn/rds/?trk=cndc-detail) in this blog.</p>\\n<p>Many of these existing .NET Core applications can be containerized using <a href=\\"https://www.docker.com/\\" target=\\"_blank\\">Docker</a> and AWS services like <a href=\\"https://aws.amazon.com/ec2/\\" target=\\"_blank\\">Amazon EC2</a>/ <a href=\\"https://aws.amazon.com/ecs/\\" target=\\"_blank\\">Amazon Elastic Container Service (ECS)</a>/ <a href=\\"https://aws.amazon.com/eks\\" target=\\"_blank\\">Amazon Elastic Kubernetes Service (Amazon EKS)</a>, and can interface with databases like <a href=\\"https://aws.amazon.com/rds/aurora/\\" target=\\"_blank\\">Amazon Aurora Database</a> providing a full blown API application system. In our previous blogs, we showed you how to build a similar Microsoft.NET Web API application with [Amazon Aurora](https://aws.amazon.com/cn/rds/aurora/?trk=cndc-detail) Database using <a href=\\"https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-cloudformation/\\" target=\\"_blank\\">AWS CloudFormation</a> and <a href=\\"https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-aws-cdk/\\" target=\\"_blank\\">AWS CDK</a>. In this blog the application architecture is complemented by build tools like <a href=\\"https://aws.amazon.com/codecommit/\\" target=\\"_blank\\">AWS CodeCommit</a> <a href=\\"https://aws.amazon.com/codebuild/\\" target=\\"_blank\\">AWS CodeBuild</a> using [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail). We will create a simple Microsoft .NET Web API for a ToDo Application. See below, the solution architecture diagram of Microsoft .NET Core Web API Application Orchestration . The sample ToDo application will communicate with an [Amazon Aurora](https://aws.amazon.com/cn/rds/aurora/?trk=cndc-detail) Serverless database for basic CRUD operations. Provided CloudFormation templates will build a Web API deployed in [AWS App Runner](https://aws.amazon.com/cn/apprunner/?trk=cndc-detail) connecting to a RDS Aurora back-end.</p>\\n<p><img src=\\"https://dev-media.amazoncloud.cn/40d24e1a984f492c8be093075a58412a_image.png\\" alt=\\"image.png\\" /></p>\n<h4><a id=\\"AWS_services_used_in_this_solution_14\\"></a><strong>AWS services used in this solution</strong></h4>\\n<ul>\\n<li><a href=\\"https://aws.amazon.com/rds/aurora/serverless/\\" target=\\"_blank\\">Amazon Aurora Serverless</a> is an on-demand, auto-scaling configuration for <a href=\\"https://aws.amazon.com/rds/aurora/\\" target=\\"_blank\\">Amazon Aurora</a>. It automatically starts up, shuts down, and scales capacity up or down based on your application’s needs.</li>\\n<li><a href=\\"https://aws.amazon.com/apprunner/\\" target=\\"_blank\\">AWS App Runner</a> is a managed service that makes it easy for developers to quickly deploy containerized web applications and APIs is used using Docker template containers and allows you to easily run and scale containerized applications on AWS. The ToDo solution for this blog post includes a sample Dockerfile for a .NET Core 3.1 application. Web API code uses AWS SDK Packages like System Manager, MySql EntityFrameworkCore to interact with the database.</li>\\n<li><a href=\\"https://aws.amazon.com/ecr/\\" target=\\"_blank\\">Amazon Elastic Container Registry (ECR)</a>, the AWS provided Docker container registry is used and integrated with App Runner, simplifying the development to production workflow.</li>\\n<li><a href=\\"https://aws.amazon.com/codebuild/\\" target=\\"_blank\\">AWS CodeBuild</a> is used to manage the continuous integration of development code into Amazon ECR as a containerized image.</li>\\n<li><a href=\\"https://aws.amazon.com/codecommit/\\" target=\\"_blank\\">AWS CodeCommit</a> is used as the code repository and integrates with [AWS CodeBuild](https://aws.amazon.com/cn/codebuild/?trk=cndc-detail) for continuous integration process.</li>\\n</ul>\n<h4><a id=\\"Prerequisites_21\\"></a><strong>Prerequisites</strong></h4>\\n<p>Docker Containers to deploy the Microsoft .NET Web API Application. Make sure Docker daemon is running if you are trying to run the manual scripts (that builds application image and pushes to Amazon ECR). The following are required to setup your development environment:</p>\n<ol>\\n<li><a href=\\"https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html\\" target=\\"_blank\\">AWS CLI</a></li>\\n<li>Dotnet CLI: Web API application was built using Microsoft .NET core <a href=\\"https://dotnet.microsoft.com/en-us/download/dotnet/3.1\\" target=\\"_blank\\">3.1</a>. Please refer Microsoft Documentation for installation.</li>\\n<li>Docker: Install <a href=\\"https://docs.docker.com/get-docker/\\" target=\\"_blank\\">Docker</a> depending on your hardware specification. Make sure the docker daemon is running</li>\\n<li>Additionally, we use AWS SDK, MySql data packages for the Microsoft .NET project and have added them as nuget packages to the solution. In this solution, we use Mysql data to connect to MySql/Aurora database and also AWS SDK Systems Manager to connect to Amazon Systems Manager.</li>\n</ol>\\n<pre><code class=\\"lang-\\">&lt;PackageReference Include=&quot;AWSSDK.SimpleSystemsManagement&quot; Version=&quot;3.3.106&quot; /&gt;\\n&lt;PackageReference Include=&quot;Amazon.Extensions.Configuration.SystemsManager&quot; Version=&quot;1.2.0&quot; /&gt;\\n&lt;PackageReference Include=&quot;MySql.EntityFrameworkCore&quot; Version=&quot;3.1.10+m8.0.23&quot; /&gt;\\n</code></pre>\\n<h4><a id=\\"Solution_Walkthrough_33\\"></a><strong>Solution Walkthrough</strong></h4>\\n<p>Below section will provide steps to provision the infrastructure (and services) and deploy the application. Upon deploying the solution, two AWS CloudFormation stacks namely “net-core-stack-ecr” and “net-core-stack-infra” will be created. CI/CD is achieved through buildspec.yaml file for subsequent checkins on the AWS CodeCommit repo that will be used by the AWS CodeBuild.</p>\n<h5><a id=\\"Clone_the_code_36\\"></a><strong>Clone the code</strong></h5>\\n<ul>\\n<li>Clone the solution code which contains .net api and CloudFormation templates from this <a href=\\"https://github.com/aws-samples/aws-apprunner-netcore\\" target=\\"_blank\\">GitHub</a> location. The source code includes two folders — ‘code’ and ‘config’. The ‘code’ folder has the necessary .NET ToDo Web API solution, and the config folder has the [AWS CloudFormation](https://aws.amazon.com/cn/cloudformation/?trk=cndc-detail) templates, and the script files used for deployment.\n<ul>\\n<li>config/net-core-app-ecr.yaml – This template spins up Amazon ECR.</li>\n<li>config/net-core-app-infra.yaml – This template creates a new VPC with Amazon RDS, AWS App Runner, AWS CodeBuild, AWS CodeCommit, Amazon Systems Manager.</li>\n<li>config/buildspec.yaml – This yaml is used by CodeBuild. Steps include building the dotnet application, pushes the image to AWS ECR. Upon pushing a new image to AWS ECR, App Runner will redeploy/re-run the application which will be exposed as an endpoint.</li>\n<li>config/exec_docker.sh – Used by “exec.sh” script when creating the infrastructure for the first time.</li>\n</ul>\\n</li>\n<li>exec.sh (root folder) – This script is used only during the initial setup to push the dotnet application image to AWS ECR. Provide your AWS Account Number to the script as input. Make sure to setup “aws configure” in the cli to the same account number before executing this script.</li>\n<li>cleanup.sh (root folder) – This script is used to clean up the entire deployment for this solution.</li>\n</ul>\\n<h5><a id=\\"Deployment_45\\"></a><strong>Deployment</strong></h5>\\n<p>This solution can be provisioned in two ways: fully automated with the provided script(s) (option 1) or can be installed using cli commands (option 2).</p>\n<h6><a id=\\"Option_1_Run_the_execsh_48\\"></a><strong>Option 1: Run the “exec.sh”</strong></h6>\\n<pre><code class=\\"lang-\\">chmod +x exec.sh\\n./exec.sh &lt;YOUR_ACCOUNT_NUMBER&gt;\\n</code></pre>\\n<p>You will notice two CloudFormation stacks are created (net-core-stack-ecr and net-core-stack-infra). Output of the net-core-stack-infra will provide AWS App Runner Service Url endpoint. Take a few moments to review the services that are spun up in the AWS CloudFormation console.</p>\n<h6><a id=\\"Option_2_Deploy_individual_CloudFormation_stacks_and_push_image_to_ECR_55\\"></a><strong>Option 2: Deploy individual CloudFormation stacks and push image to ECR</strong></h6>\\n<p>Deploy Amazon ECR CloudFormation stack (config/net-core-app-ecr.yaml)</p>\n<pre><code class=\\"lang-\\">aws cloudformation create-stack --stack-name net-core-stack-ecr --template-body file://config/net-core-app-ecr.yaml --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=AppStackName,ParameterValue=net-core-stack-ecr\\n</code></pre>\\n<p>Build and Deploy application code to Amazon ECR</p>\n<p>XML</p>\n<pre><code class=\\"lang-\\">cd code\\ndotnet build .\\nECR_REPO=net-core-stack-repo\\nACCOUNT_NUMBER=&lt;YOUR_ACCOUNT_NUMBER&gt;\\nREGION=us-east-1\\nAPP_SVC=todo/apprunnerdotnetsvc\\n### build the AWS App Runner docker image, tag and push it to AWS ECR\\ndocker build -t \$APP_SVC .\\ndocker tag \$APP_SVC \$ACCOUNT_NUMBER.dkr.ecr.us-east-1.amazonaws.com/\$ECR_REPO:latest\\naws ecr get-login-password --region \$REGION | docker login --username AWS --password-stdin \$ACCOUNT_NUMBER.dkr.ecr.\$REGION.amazonaws.com\\ndocker push \$ACCOUNT_NUMBER.dkr.ecr.us-east-1.amazonaws.com/\$ECR_REPO:latest\\ncd ..\\n</code></pre>\\n<p>Deploy the other CloudFormation stack for infra/services needed for the solution (config/net-core-app-infra.yaml)</p>\n<pre><code class=\\"lang-\\">aws cloudformation create-stack --stack-name net-core-stack-infra --template-body file://config/net-core-app-infra.yaml --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=AppStackName,ParameterValue=net-core-stack-infra\\n</code></pre>\\n<h5><a id=\\"Application_CICD_82\\"></a><strong>Application CICD</strong></h5>\\n<p>With the above deployment we have successful setup a CICD solution which will enable you to make further updates to the dotnet application code and manage automatic deployment to AWS App Runner. You can clone the code from AWS CodeCommit into a local folder and make updates as needed.</p>\n<p>Below are commands to clone and push updates to AWS CodeCommit:</p>\n<pre><code class=\\"lang-\\"># set source directory where you have this current code downloaded from github\\nSOURCE_DIR=\$pwd\\n# copy and git push steps to codecommit\\nmkdir codecommit\\ncd codecommit\\ngit clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/net-core-stack-ecr-repo\\ncd ..\\nmkdir codecommit/net-core-stack-ecr-repo/code codecommit/net-core-stack-ecr-repo/config\\ncp -R SOURCE_DIR/code/* codecommit/net-core-stack-ecr-repo/code\\ncp -R SOURCE_DIR/config/* codecommit/net-core-stack-ecr-repo/config\\ncd codecommit/net-core-stack-ecr-repo\\ngit add .\\ngit commit -m &quot;test cicd commit&quot;\\ngit push\\n\\n</code></pre>\\n<h4><a id=\\"Solution_Validation_103\\"></a><strong>Solution Validation</strong></h4>\\n<p>Verify by visiting the App Runner console to view the application (net-core-stack-apprunner-svc) that has been deployed. In the application, visit the “Logs” tab to view the details about service creation, image pull from ECR, health check on port 8080 before routing traffic to application. A sample Event log will be as below.</p>\n<pre><code class=\\"lang-\\">02-02-2022 04:00:28 PM [AppRunner] Service status is set to RUNNING.\\n02-02-2022 04:00:28 PM [AppRunner] Service creation completed successfully.\\n02-02-2022 04:00:27 PM [AppRunner] Successfully routed incoming traffic to application.\\n02-02-2022 03:59:56 PM [AppRunner] Health check is successful. Routing traffic to application.\\n02-02-2022 03:58:59 PM [AppRunner] Performing health check on port '8080'.\\n02-02-2022 03:58:51 PM [AppRunner] Provisioning instances and deploying image.\\n02-02-2022 03:58:39 PM [AppRunner] Successfully pulled image from ECR.\\n02-02-2022 03:56:54 PM [AppRunner] Successfully created pipeline for automatic deployments.\\n02-02-2022 03:56:35 PM [AppRunner] Service status is set to OPERATION_IN_PROGRESS.\\n02-02-2022 03:56:35 PM [AppRunner] Service creation started.\\n</code></pre>\\n<p>Go to AWS CloudFormation console and in the Infra stack output tab get the “AppRunnerServiceUrl” to test the health check api on a browser. A sample url will be like – http://gcdpsgaztx.us-east-1.awsapprunner.com/api/values<br />\\nTo test the application endpoint, you can use tools like Postman, ARC Rest Client or Browser extensions like RestMan. Select “content-type” as “application/json”, POST as raw data/json – sample input below -https:///api/todo</p>\n<pre><code class=\\"lang-\\">{\\n&quot;Task&quot;: &quot;new ToDo Application&quot;,\\n&quot;Status&quot;: &quot;Done&quot;\\n}\\n</code></pre>\\n<p>Use the same url and fire a GET call to see the previously posted todo item as response.</p>\n<pre><code class=\\"lang-\\">https://&lt;YOUR_APP_RUNNER_URL&gt;/api/todo/Done\\n</code></pre>\\n<h4><a id=\\"Clean_Up_129\\"></a><strong>Clean Up</strong></h4>\\n<p>Option 1: You can run the provided “cleanup.sh” to clean up the entire solution</p>\n<pre><code class=\\"lang-\\">chmod +x cleanup.sh\\n.\\\\cleanup.sh\\n</code></pre>\\n<p>Option 2: If you like to individually execute the following commands.</p>\n<pre><code class=\\"lang-\\">aws ecr batch-delete-image --repository-name net-core-stack-ecr-repo --image-ids imageTag=latest\\n\\naws ecr batch-delete-image --repository-name net-core-stack-ecr-repo --image-ids imageTag=untagged`Delete the entire infrastructure\\n</code></pre>\\n<pre><code class=\\"lang-\\">aws cloudformation delete-stack --stack-name net-core-stack-ecr \\naws cloudformation delete-stack --stack-name net-core-stack-infra\\n</code></pre>\\n<h4><a id=\\"Troubleshooting_145\\"></a><strong>Troubleshooting</strong></h4>\\n<ul>\\n<li><strong>AWS CloudFormation Stacks Failure</strong>: If you notice any of the CloudFormation stack failures below steps would help to triage.\n<ul>\\n<li>ecr-stack: Make sure Docker daemon is running; Check the CloudFormation “Outputs” of the ecr-stack to verify the ECR arn. Look at the Events tab to see if any failures have occurred.</li>\n<li>infra stack: Review the AWS service limits. Ex: 5 VPCs per region; Make sure ECR stack is created with docker image (application code as docker container images in there). Look at the Events tab to see if any failures have occurred.</li>\n</ul>\\n</li>\n<li><strong>RDSCluster Connectivit</strong>\n<ul>\\n<li>Use AWS RDS console to verify the new RDS cluster. Connectivity to RDS Endpoints/credentials will be in AWS Systems Manager.</li>\n<li>Table/Model entity will not be created unless ToDo Url POST is triggered.</li>\n<li>Note: Inactivity in Aurora Serverless – RDS Table could put the RDS in suspended state to reduce the cost. You might receive a communication error after no activity while trying to invoke the database DDL/DML statements. If the application provided API times out (especially after the initial setup, you may have to invoke the POST/GET call invoke on the /api/todo endpoint). You might notice this by connecting to the SQL in Query Editor with below output.Retrying the select queries will warm up the RDS database for subsequent connection to be served.</li>\n</ul>\\n</li>\n</ul>\\n<pre><code class=\\"lang-\\">Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server\\n</code></pre>\\n<ul>\\n<li>AWS AppRunner\\n<ul>\\n<li>Verify App Runner application “Event Logs” and “Deployment logs”.</li>\n<li>By default, the application is coded to run in port 8080. Make sure they are seen in application log.</li>\n<li>Check the health check url to see the test endpoint</li>\n<li>Check the ToDo Url to post the data from tools like Postman or RestMan (Google Chrome/MS Edge plugin). Check if the data is available in RDS database.</li>\n</ul>\\n</li>\n</ul>\\n<h4><a id=\\"Conclusion_164\\"></a><strong>Conclusion</strong></h4>\\n<p>To recap, in this post we built and deployed an ASP.NET Core Web API application that interacts with various AWS Services. We also walked through in this example how to deploy Microsoft .NET Core application code as containers with infrastructure as code. We encourage you to test this example and see for yourself how this overall application design works within AWS. Then, it will be just the matter of replacing your individual code base (buildspec/WebAPI, MVC, or other Microsoft .NET core application) and package them as Docker container and let the AWS App Runner handle the process efficiently.</p>\n<p>If you implement this example and run into any issues, or have any questions or feedback about this blog please provide your comments below!</p>\n<h5><a id=\\"References_169\\"></a><strong>References</strong></h5>\\n<ul>\\n<li><a href=\\"https://docs.aws.amazon.com/apprunner/\\" target=\\"_blank\\">AWS App Runner Documentation</a></li>\\n<li><a href=\\"https://aws.amazon.com/blogs/aws/new-for-app-runner-vpc-support/\\" target=\\"_blank\\">New for App Runner – VPC Support | AWS News Blog (amazon.com)</a></li>\\n<li><a href=\\"https://docs.aws.amazon.com/apprunner/latest/dg/network.html\\" target=\\"_blank\\">Networking with App Runner – AWS App Runner (amazon.com)</a></li>\\n<li><a href=\\"https://aws.amazon.com/blogs/developer/developing-a-microsoft-net-core-web-api-application-with-aurora-database-using-cloudformation/\\" target=\\"_blank\\">Developing a Microsoft .NET Core Web API application with Aurora Database using CloudFormation</a></li>\\n<li><a href=\\"https://aws.amazon.com/blogs/containers/build-and-deploy-a-spring-boot-application-to-aws-app-runner-with-a-ci-cd-pipeline-using-terraform/\\" target=\\"_blank\\">Build and deploy a Spring Boot application to AWS App Runner with a CI/CD pipeline using Terraform</a></li>\\n</ul>\n<h5><a id=\\"About_the_Authors_176\\"></a><strong>About the Authors</strong></h5>\\n<p><img src=\\"https://dev-media.amazoncloud.cn/e320ac21653c40cab748ce71f006392a_image.png\\" alt=\\"image.png\\" /></p>\n<p>Sivasubramanian Ramani (Siva Ramani) is a Sr Cloud Application Architect at AWS. His expertise is in application optimization, serverless solutions and using Microsoft application workloads with AWS.</p>\n<p><img src=\\"https://dev-media.amazoncloud.cn/3d583dbbdb30445fa0733bf24e28980d_image.png\\" alt=\\"image.png\\" /></p>\n<p>Naveen Balaraman is a Cloud Application Architect at Amazon Web Services. He is passionate about Containers, serverless Applications, Architecting Microservices and helping customers leverage the power of AWS cloud.</p>\n"}
目录
亚马逊云科技解决方案 基于行业客户应用场景及技术领域的解决方案
联系亚马逊云科技专家
亚马逊云科技解决方案
基于行业客户应用场景及技术领域的解决方案
联系专家
0
目录
关闭