35,99 €
A Developer’s Guide to .NET in Azure helps you embark on a transformative journey through Microsoft Azure that is tailored to .NET developers. This book is a curated compendium that’ll enable you to master the creation of resilient, scalable, and highly available applications.
The book is divided into four parts, with Part 1 demystifying Azure for you and emphasizing the portal's utility and seamless integration. The chapters in this section help you configure your workspace for optimal Azure synergy. You’ll then move on to Part 2, where you’ll explore serverless computing, microservices, containerization, Dapr, and Azure Kubernetes Service for scalability, and build pragmatic, cost-effective applications using Azure Functions and Container apps. Part 3 delves into data and storage, showing you how to utilize Azure Blob Storage for unstructured data, Azure SQL Database for structured data, and Azure Cosmos DB for document-oriented data. The final part teaches you about messaging and security, utilizing Azure App Configuration, Event Hubs, Service Bus, Key Vault, and Azure AD B2C for robust, secure applications.
By the end of this book, you’ll have mastered Azure's responsive infrastructure for exceptional applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 690
Veröffentlichungsjahr: 2023
A Developer’s Guide to .NET in Azure
Build quick, scalable cloud-native applications and microservices with .NET 6.0 and Azure
Anuraj Parameswaran
Tamir Al Balkhi
BIRMINGHAM—MUMBAI
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Preet Ahuja
Senior Content Development Editor: Adrija Mitra
Technical Editor: Arjun Varma
Copy Editor: Safis Editing
Project Coordinator: Ashwin Dinesh Kharwa
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Jyoti Chauhan
Marketing Coordinator: Rohan Dobhal
First published: October 2023
Production reference: 1220923
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83763-301-2
www.packtpub.com
To my beloved family, consisting of Sreeja, Sidhardh, and Sivaardra, and to my parents, Parameswaran Namboothiri and Saraswathi, I dedicate this book with heartfelt gratitude. Your unwavering support, guidance, and boundless love have been the driving force behind my journey. Thank you for being a constant source of inspiration in my life.
– Anuraj Parameswaran
To my amazing mother and sister, thank you for your unwavering support and resilience. You have inspired me to overcome challenges and reach for greatness. Your love and strength are my endless source of inspiration. I am forever grateful.
– Tamir AlBalkhi
Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
I am deeply grateful to my colleagues at Socxo Solutions Pvt. Ltd. for their invaluable support and unwavering encouragement during the creation of this book. Their expertise and collaborative spirit enriched my work, and I extend my heartfelt appreciation to each member of the team. Thank you for inspiring me to strive for excellence.
Tamir Al Balkhi is a technology problem solver with 15 years of experience developing innovative and effective solutions for clients across various industries, including healthcare, finance, and retail. From steering small to medium-sized business projects to overseeing large enterprise implementations, Tamir has consistently demonstrated exceptional leadership and technical prowess. As a cloud architect and Chief Technology Officer (CTO), Tamir specializes in designing and delivering best-in-class cloud solutions within the Microsoft Azure ecosystem. His agile-first mindset and commitment to a test-driven delivery approach have been instrumental in his ability to deliver projects on time, within budget, and beyond client expectations.
Stéphane Eyskens started his career in 1999. Since a bit more than a decade ago, he has been at the forefront of cloud technologies, starting his Azure journey and embracing the emerging K8s platform. As a Microsoft Most Valuable Professional, Stephane contributes a lot by writing blog posts on Microsoft communities, as well as speaking at tech conferences. He has also authored multiple books on Azure and software architecture.
Matt R. Cole has functioned in many different roles over a career of more than 35 years. He was an early pioneer of VoIP. He architected and developed the VoIP system NASA used for all Space Shuttle launches and transmission out to the International Space Station. He worked with Microsoft on Azure Bonsai DRL. Matt led a digital transformation effort for MGM in Las Vegas. He has experience in C, C++, C#, .Net, Python, AI/ML, Swarm Technology, and computational neuroscience.
Matt has authored several books and contributed to several more. His current role is as a senior solutions architect for Dexian, where he works with one of the largest gas and oil companies in the world.
Kicking off our exploration of Microsoft Azure, this initial chapter aims to help you understand the Azure landscape. We introduce you to the Azure portal, where you can set up every resource that will be discussed in the upcoming chapters. We'll also help you set up your Azure development environment, including selecting and configuring your integrated development environment (IDE) for seamless Azure integration.
This part has the following chapter:
Chapter 1, Setting Up Your Development EnvironmentWelcome to the first chapter! This chapter will guide you through the steps to set up your development environment and create your first Azure project.
We will start by discussing how to create your Azure subscription, which is the first step in getting started with Azure development. We will provide you with a step-by-step guide on setting up your subscription, including selecting the right subscription type and configuring your account settings.
Next, we will dive into configuring your development environment. This includes setting up your machine with the software, tools, and dependencies required for Azure development. We will guide you through this process, ensuring you have a well-configured environment.
After that, we will set up your Visual Studio for success. Visual Studio is a robust integrated development environment (IDE) that provides the tools to build, test, and deploy your Azure projects. We will show you how to configure Visual Studio for Azure development, including how to set up your project templates and debugging tools.
Finally, we will walk you through creating your first project in Azure. We will provide a hands-on approach, guiding you through creating a new Azure project, setting up your project structure, and deploying your project to the cloud.
In this chapter, we will cover the following main topics:
Creating your Azure subscriptionConfiguring your development environmentSetting up your Visual Studio for successCreating your first projectBy the end of this chapter, you will have a solid understanding of how to create your Azure subscription, configure your development environment, set up Visual Studio for success, and create your first Azure project. So, let’s get started!
You need an Azure subscription to work with examples in this book. In this section, you will learn about how to create an Azure subscription. Let’s get started with the steps:
Open the browser, and navigate to https://azure.microsoft.com/en-in/free/.Figure 1.1 – Create your free Azure account screen
Click on the Start free button. On the second screen, you need to create an account. Click on the Create one! link.Figure 1.2 – Azure account setup – signing in with a live account/signing up for a live account
You can use either your existing email address or you can create a new email address. We are using the existing email option.Figure 1.3 – Creating a live account – email address
You need to create a password for your account and complete some CAPTCHA verification to create the account. Once it is completed, you will be redirected to an Azure account creation screen.Figure 1.4 – Azure account profile creation
On the screen, you need to provide your personal details, contact information, and your credit card information – for verification purposes. For verification purposes, $2 from your card will be charged and it will be credited to your card within one to two days.Once the signup is successfully completed, you will be able to see the success page as follows. From this screen, you will be able to access the Azure portal.
Figure 1.5 – Azure account creation – success page
Click on the Go to Azure portal button to access the Azure portal and you will be able to see a screen like this.Figure 1.6 – Azure portal
The preceding screenshot shows the Azure portal where you can create and manage resources.
In the portal, you can search for resources in the middle search bar, which will help you to search for resources have you created; the available Azure services that you can create; the Marketplace, which you can use to access resources from third-party providers; and documentation on the Azure service you are looking for.In this example, I am searching for Storage since there is no storage account created. It does not show any existing resources, but the portal shows me services such as Azure Storage Account and Storage browser, and then it shows some Marketplace suggestions and finally, the documentation related to the Storage keyword.Figure 1.7 – Searching for resources – the Azure portal
In the portal, after the search bar, you can see a Cloud Shell icon, which helps you execute commands in either PowerShell or Bash shell – you can use this feature to create resources using the command line.Figure 1.8 – Cloud Shell icon – Azure portal
The Directories + Subscriptions icon will help you switch between different active directories and subscriptions.Figure 1.9 – Directories + Subscriptions – Azure portal
Once you click on the button, you will be able to see all directories.
Figure 1.10 – Directories + Subscriptions page – Azure portal
In the portal, the notifications icon will show different notifications, such as remaining credit, resource provisioning status, and so on.Figure 1.11 – Notifications – Azure portal
Next is the settings icon, which helps you to customize the look and feel of the portal.Figure 1.12 – Settings – Azure portal
Clicking on the settings icon will take you portal settings page where we have the following options:
By default, it will open the Directories + Subscriptions page.You can click on the Appearance + startup views menu to configure the look and feel of the portal. In this section, you can also configure the first screen in terms of what you see on it when you log in.Figure 1.13 – Configure appearance and startup view – Azure portal
The Language + region option helps you to configure the currency format and date/time value.Figure 1.14 - Setting up language, date, and currency format – Azure portal
The My information section displays your email address and helps you to subscribe to different emails from Microsoft. You will be able to Export settings, which helps to export your current Azure portal configuration as a JSON file. The Delete all settings and private dashboards option helps you to remove all the settings and dashboards created.Figure 1.15 – My information – Azure portal
Finally, the Signing out + notifications page helps you to configure notifications and sign-out options.Figure 1.16 – Signing out and notifications configuration – Azure portal
Click on the Support + troubleshooting icon to learn about the health status of different Azure services. Also, you will be able to see different links to access billing FAQs, documentation, and the technical community.Figure 1.17 – The Support and troubleshooting option – Azure portal
Click on the Feedback icon to share your experience with the Azure portal.Figure 1.18 – Send feedback – Azure portal
Click on the Show Portal Menu option to see the Azure portal menu.Figure 1.19 – Azure portal
You can customize this menu, which will help you to access different services quickly. The Azure portal comes with a Dashboard view as well. You will be able to create different dashboards and share them with your other team members.
Figure 1.20 – Azure portal
Click on the Dashboard button to see your private dashboard – by default, it will show as My Dashboard.Figure 1.21 – Dashboard view – Azure portal
You can customize the dashboard. You can click on the Edit button, and on the screen, you can remove existing widgets and add different widgets.Figure 1.22 – Customizing the dashboard – Azure portal
Upon completing the customization, you can preview the changes, and then you will be able to save the changes by clicking on the Save button. You can share the dashboard with other users in the subscription using the Share button.Figure 1.23 – Share dashboard – Azure portal
In this section, we learned about creating an Azure account and how to customize and configure the Azure portal. You will be able to create and manage different Azure resources from the Azure portal.
Next, you will learn how to create a resource in the Azure portal:
You need to click on the + Create a resource button.Figure 1.24 – Azure portal – + Create a resource
On the next screen, you need to choose the resource you want to create.Figure 1.25 – Azure portal – Create a resource
For demo purposes, I will create a resource group. It’s a container that contains related resources in an Azure solution. It is a best practice to create resources related to a project or product in the same resource group. You can search for resource group and click on the first result. Then, you will be able to see the details of the service/resource you’re about to create.
Figure 1.26 – Azure portal – new resource group
Click on the Create button.On the Create a resource group screen, provide the name of the resource group – HelloWorld – set Subscription to Free Trial, and set Region to a region near your location.Figure 1.27 – Azure portal – Create a resource group – Basics screen
Click on the Review + create button to view the details of the resource you’re going to create, and then create the resource upon confirmation by clicking the button again. In the case of a resource group, you will only see the configuration values you created, but in the case of certain resources such as virtual machines or app services, you need to configure mandatory fields – then, you can click on Review + create – in such a scenario, you will be able to see the default values on this screen.Or you can assign tags to the resource on the Tags tab. Tags are key-value pairs that act as metadata for Azure resources, which helps you to identify resources. Tags are helpful for tracking, organizing, grouping, and analyzing costs for resources. It is a best practice to add tags to your Azure resources.
Figure 1.28 – Azure portal – associating tags
Upon clicking the Review + create button again, you will be able to see the details of the resources and the tags:Figure 1.29 – Azure portal – Create a resource group confirmation screen
This screen will also help you to create an automation script. You can download the Azure Resource Management (ARM) script by clicking on the Download a template for automation link.
Once you click on the Create button, Azure will create the resource group and you will get a notification.Figure 1.30 – Azure portal – Resource created notification
This way, you will be able to create resources in the Azure portal. Now you have learned how to create an account and create a free trial subscription in Azure portal. You also learned about how to create resources in Azure using the Azure portal. You will be able to create resources using the Azure CLI and Azure PowerShell as well. Next, you will learn about configuring your development environment.
Setting up your development environment is essential for success because it provides you with the necessary tools and resources to efficiently and effectively develop, test, and deploy your software. A properly configured development environment allows you to streamline your workflow, automate tasks, and catch errors early on in the development process. If you’re new to coding, I’m sure you’re wondering how to set up the right environment for you so that you can get coding quickly and easily. You want to be able to focus on what matters most: creating great code!
There are many different ways to do this, but here is a simple guide that will show you how to set up an IDE for .NET programming on Azure. This guide will give you a solid foundation upon which you can build your knowledge of Python and other programming languages.
If you already have an environment setup, please note we will be working through examples utilizing .NET 6.0 in this book and that needs to be installed on your machine. If you are starting from scratch, follow the instructions below to get started.
Follow these steps to install .NET 6.0:
Open your browser and go to this web page: https://dotnet.microsoft.com/en-us/download/dotnet. We will primarily be working in .NET 6.0 so make sure to choose the option related to the system you are using.Figure 1.31 – .NET Download page
You need to download the .NET 6.0 SDK. Once the Software Development Kit (SDK) has been downloaded, execute the downloaded executable, which will bring up the following setup screen.In a Windows operating system, the executable will show a welcome screen as follows (see Figure 1.32) from where you can install the .NET SDK. In Windows, it will prompt for administrator access.
Figure 1.32 – .NET SDK – Windows installation
On Mac machines, it will show a welcome screen like this.
Figure 1.33 – .NET SDK – Mac installation
In Linux distributions, .NET SDK supports two types of installation – manual installation and script installation. With manual installation, we need to download the .NET SDK, execute the files, and configure paths. In script installation, we can download a .NET installation script from here: https://dot.net/v1/dotnet-install.sh. For developers or normal users, scripted installation is recommended. Once we have downloaded the script, we need to make it executable using the chmod command, and then execute the script.
Here are the bash commands to do this:
> wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh > chmod +x ./dotnet-install.sh > ./dotnet-install.shThis will install the .NET 6.0 SDK in most of the Linux distributions. You can find more details about the installation here: https://learn.microsoft.com/dotnet/core/install/linux?WT.mc_id=DT-MVP-5002040.
Now that we’ve successfully installed .NET 6.0, we can continue setting up our IDEs.
You need to set up and configure the development environment for building your applications in .NET and Azure. In this section, you will configure Visual Studio Code (VS Code) and Visual Studio. Visual Studio Code is an open source editor for building ASP.NET Core and C# applications.
Follow these steps to install Visual Studio Code:
Visit the Microsoft site to download Visual Studio Code: https://visualstudio.microsoft.com/downloads/Figure 1.34 – Visual Studio/VS Code download page
Based on your development machine’s operating system, download the applicable VS Code executable.Figure 1.35 – VS Code – download page
Accept the terms and conditions and continue with the installation:Figure 1.36 – VS Code Editor
Unlike on Windows and Mac, installing VS Code on Linux is easy – we just need to run the following command: sudo snap install --classic code. This will install VS Code on Linux. For more information on the VS Code installation, check out this page: https://code.visualstudio.com/docs/setup/linux.Click on Extensions or press the Ctrl + Shift + X shortcut keys on Windows or Cmd + Shift + X on Mac and install the following extensions:Azure ToolsAzure CLI ToolsAzure PipelinesAzure Kubernetes ServiceAzure Storage ExplorerC# ExtensionFollow these steps to install Visual Studio Community Edition 2022:
Visit the Microsoft site to download Visual Studio:https://visualstudio.microsoft.com/downloads/Figure 1.37 – Visual Studio download page
Install Azure Development and the accompanying packages for .NET development; the Visual Studio setup will prompt for different installation configurations or workloads.Figure 1.38 – Visual Studio – installation configuration
Sign in to the cloud account you previously created to access the Azure resources within your IDE.Figure 1.39 – Visual Studio – first screen
In this section, you learned about installing and configuring your development environment. VS Code is a cross-platform editor for debugging applications and Visual Studio is a fully featured IDE for building and debugging applications.
Now is the time to create our first project!
After installing all of the prerequisite software listed in step 2, under the Installing Visual Studio Community 2022 section, you should be able to begin building them without the need for any extra settings. To get things going, we’ll write a straightforward function that we’ll attempt to execute to make sure everything is set up and prepared. Start up Visual Studio 2022 Community Edition and select Create a new project to get started.
Figure 1.40 – Visual Studio – welcome screen
Now you can select an Azure Function from the list of choices and follow the steps to get started with the project. On the first screen, configure your new project screen. We need to set the project name, project location, and solution name. On the Additional information screen, we need to configure the framework, function trigger, and authorization level. Please see the following configuration values:
Figure 1.41 – Visual Studio – creating an Azure Functions app
Project Name: FunctionApp1
Project Location: C:\USER\PROJECTFOLDER
Solution Name: FunctionApp1
Functions Worker: .NET 6.0
Function: http trigger
Authorization Level: Function
After you click the OK button, you should see a screen similar to the following screenshot (see Figure 1.42). This indicates that a new function file has been created, and some standard code has already been added as a starting point. We will discuss how to create a function and its properties in the chapter of this book specifically related to Azure Functions (Chapter 5). For now, we won’t go into too much detail.
Figure 1.42 – Azure Functions project in Visual Studio
This is how, we can create an Azure Function using Visual Studio. We can other project types such as ASP.NET Core MVC, Blazor, and ASP.NET Core Web APIs. We will explore other project types in the upcoming chapters. Visual Studio will also help us to debug, deploy, and monitor the applications in Azure.
Congratulations on completing your first chapter on your Azure development journey! By now, you should have a solid understanding of how to set up your development environment, configure Visual Studio for Azure development, and create your first Azure project. These skills will serve as a foundation for your future Azure development work.
Remember, Azure is a powerful cloud platform with many services and solutions. By continuing to learn about and explore Azure, you can take advantage of its many benefits, including scalability, flexibility, and cost savings.
We hope this chapter has provided you with a valuable introduction to Azure development and inspired you to continue learning and exploring the world of cloud computing. The next chapter will dive deeper into Azure services and show you how to develop applications using some core services. In the next chapter, you will learn about containers, installing Docker, and building applications with container support. So, stay tuned and keep learning!
In this part, you will learn about the key aspects of Microsoft Azure. Initially, you'll dive into containerization and enrich your knowledge by understanding the Distributed Application Runtime (Dapr), enabling you to construct resilient, stateful microservices easily, and design microservices with Azure Kubernetes Service (AKS). Finally, you'll be introduced to the power of serverless computing with Azure Functions and Azure Container Apps, and you will learn how to deploy practical, scalable applications that optimize cost. Each chapter promises a balance of theoretical understanding and practical application, paving the way for a holistic learning experience and equipping you with the necessary tools to develop scalable, resilient, and highly available applications.
This part has the following chapters:
Chapter 2, Creating Docker Containers on AzureChapter 3, Building Resilient Applications with DaprChapter 4, Designing Microservices with AKS and Containers in AzureChapter 5, Building Serverless Apps with Azure Functions and Container AppsContainers are a standard way of packaging application source code, dependencies, and configuration together so that it can be deployed anywhere without worrying about the dependencies and their versions. Docker is a company that offers a container platform. In this chapter, we will learn about Docker basics, how to create a Docker image, how to configure a private Docker registry, and finally, how to configure continuous integration (CI) and continuous deployment (CD) with a container registry. In later chapters, we will learn about Azure Container Apps and Azure Kubernetes Service (AKS) services that use Docker images and help us deploy Docker images at scale.
In this chapter, we’re going to cover the following main topics:
Installing DockerExploring Docker and basic Docker commandsCreating Docker images for your ASP.NET Core applicationCreating and configuring Azure Container RegistryDeploying web apps to Azure App Service from Azure Container RegistryConfiguring CI/ CD with Azure Container RegistryIn this chapter, you’ll see examples using ASP.NET Core, and you need the .NET SDK installed on your machine. If the .NET SDK is not installed, check out Chapter 1 for instructions on how to do it. For building and debugging, you need either Visual Studio or VS Code.
In this section, you will install Docker Desktop on your Windows machine. Docker is a software company that offers a containerization platform. There are other container software providers as well, but Docker is the most popular one.
In Windows, you can install Docker with the WSL (short for Windows Subsystem for Linux) backend or the Hyper V backend. The WSL backend is preferred, as WSL 2 provides better performance than the Hyper-V backend. You need a Windows 10 or Windows 11 computer with a 64-bit processor, 4 GB RAM, and hardware virtualization support must be enabled. You can find more details at https://docs.docker.com/desktop/install/windows-install/. You can also find the installation setup in this URL.
Once you download the Docker Desktop Installer (Docker Desktop Installer.exe) and execute it, the setup will check your system for the prerequisites and then show a prompt like this:
Figure 2.1: Docker Desktop installation screen
Since WSL is enabled in this machine, it is showing a prompt with WSL configuration. You can click Ok to continue. Next, the setup executable will download the required files. This may take some time based on your internet connection. Once the installation is complete, you will see a screen with a Close button. You can click on the Close button to finish the installation.
Next, from the desktop (if you selected the Add shortcut to desktop option in Figure 2.1), you’re able to access the Docker Desktop icon. Double-click on the icon and it will start Docker Desktop. You need to accept the Docker subscription service agreement. Once you accept the agreement, Docker Desktop will start and will show the Docker Desktop Tutorial screen; you can skip this. You will then get the Docker Desktop dashboard screen.
Figure 2.2: Docker Desktop dashboard window
You will be able to manage and configure Docker Desktop from this window. You can verify the installation by opening a Terminal or PowerShell or command window and executing the docker version command, which will display information like this:
> docker versionOnce it is executed, you will be able to see the results in the console window, which will display the Docker client version and Docker server version.
To install Docker on other platforms, check out https://docs.docker.com/get-docker/.
In this section, we learned about what Docker is, how to install Docker Desktop on your machine, and how you can find out the Docker version by using the docker version command. In the next section, we will explore Docker in more depth and learn about basic Docker commands.
In this section, you will learn about Docker and a few Docker commands that are required to create and manage Docker images.
Containers provide a standard way to package your application source code, configurations, and dependencies into a single object. Containerization helps provide a separation of concerns – the development team can focus on implementing the business functionality and application logic, and the IT and operations teams can focus on deployment and management without bothering about the application dependencies, software versions, and configurations.
Docker is written in the Go language and uses a client-server architecture. When you install Docker Desktop, you will be installing both the client and server, also known as Docker daemon, on your machine. The Docker client communicates to the Docker daemon through REST APIs. Here are some Docker architecture components:
Docker image – This is a template that helps you to build a container. This contains the software dependencies and configuration of your application, which are used to create containers. The naming convention of Docker images is like this repository name: tag – if no version is specified, the latest tag is applied.Docker container – This is the instance of the Docker image. For example, if you consider a Docker image as a class in object-oriented programming, then the Docker container will be the instance of the class. It consists of your application code, dependencies, and configuration that helps to run your application.Docker registry – This is where you can store Docker images so that you can distribute them to Docker users. There are different registries available – Docker Hub is a Docker registry from Docker, Azure Container Registry (ACR) is from Azure, and GitHub Container Registry (GHCR) is from GitHub. You will be able to publish the images as public or private. Later in this chapter, you will learn more about ACR.Docker daemon – The Docker daemon runs as a service in your machine and listens for API requests from the Docker client – the Docker CLI or Docker Compose. Docker daemon manages the containers, images, volumes, and networking.Docker client – This is a command-line tool that helps you to interact with the The Docker daemon. You can connect to external Docker daemons as well.Here is the basic architecture of Docker:
Figure 2.3: Docker Desktop architecture
When you execute the docker version command, in the result, you will be able to see the versions of both the Docker client and Docker server or Docker daemon.
Next, we will explore some Docker commands that you need to create, manage, and deploy a Docker image to ACR.
In the Terminal, if you execute the docker help command, you will be able to see all the Docker commands – certain commands are only available in certain versions . For example, Docker recently introduced a feature called extensions, so Docker commands to manage extensions are only available in the new versions.
In this section, we will learn about the Docker development life cycle. It refers to the various stages and processes involved in developing and deploying applications using Docker. Docker allows you to package applications and their dependencies into containers, which can be easily moved between different environments, ensuring consistent behavior across development, testing, and production.
Figure 2.4: Docker development life cycle
Once we install and configure Docker Desktop in the development machine, we will create a Dockerfile along with the application code. We can either push the code to Azure DevOps or any other source control tools and the DevOps tool will build the Docker image and push it to the container registry, or we can build the Docker image from the development machine, test it, and push the image to the container registry. By using DevOps tools, we will be able to automate various tests, such as unit tests, integration tests, and security tests. From the container registry, by using Webhooks, we can automate the deployment to Azure App Service or any other hosting platform such as AKS or Azure Container Apps. We can use Azure Monitor or Azure Application Insights to monitor the performance and behavior of the containers. We can use Azure Monitor logs to troubleshoot any issues. Azure Monitor also helps to inspect the container state. We will be exploring the various components of the Docker life cycle in this chapter.
As mentioned earlier, there are a lot of Docker commands available. In this section, however, you will learn only a few of the ones that help to create and manage Docker images and containers:
docker run – Runs a command in a new containerdocker pull – Pulls an image or a repository from a registrydocker images – Lists all Docker images in the host machinedocker tag – Creates a tag for the Docker image, which is required to deploy to the container registrydocker login – Logs in to a container registrydocker build – Builds a container from a DockerfileThe docker run command helps you to run a Docker container. If you try to run a container that doesn’t exist in your local host, Docker will download it from your configured container registry – by default, it will be Docker Hub. If the container image doesn’t exist in the container registry, Docker will show an error message – either the image doesn’t exist or it may require a login.
Here is an example. Run the docker run command with the hello-world image like this:
> docker run hello-worldWhen you execute this command, the Docker client will send the details to the Docker daemon. Since the container doesn’t exist in your Docker host, it will download it from Docker Hub:
Figure 2.5: The docker run hello-world command result
Once it is downloaded, it will run the container, which basically prints out a hello world message on the screen. If you run the command again, you will see the container prints the message – it will not download the image again as it is already available.
When you’re running web applications or databases, you may need to pass the port numbers as the parameter. To learn more about the docker run command, execute the command with the --help parameter – this parameter works with all Docker commands.
This command helps you to pull the Docker images from the Docker registry. If the image exists in the local machine, it won’t download the image again:
> docker pull hello-worldHere is an example; when you execute it for the first time, it can’t find the image locally, so it is downloaded from Docker Hub:
Figure 2.6: The docker pull hello-world command result
But when you execute it for a second time, it is not downloaded from Docker Hub.
This docker images command or docker image list command will help you list all the images in your machine:
> docker imagesIt will display the repository (name), tag, image ID, when the image was created, and the size of the image:
Figure 2.7: The docker image list command result
As you see, only one image exists – hello-world – and you can see the tag as latest. The image ID is a unique number, it was created 14 months ago, and the size is 13.3 KB. You can filter images with the name as the parameter, like this:
> docker images hello-worldThis command will list all the hello-world images with different versions.
This command helps you to tag a Docker container. This command is useful when you publish a Docker image to a container registry. To publish a Docker image, you need to follow a naming convention for the images, depending on the Docker registry. For Docker Hub, the naming convention is dockerhub-username/repository:tag. For ACR, it is acrname.azurecr.io/repository:tag. Unlike earlier commands, this command requires two parameters, source name and tag, and target name and tag. Here is an example:
> docker tag hello-world:latest packtpubebook.azurecr.io/hello-world:1.0.0When you execute this command, it doesn’t display any message, but if you execute the docker images command, you will be able to see two container images:
Figure 2.8: The docker tag command result
If you notice, the details – the image ID, created time, and size – of both images are the same except for the repository name and tag.
The docker login command helps you to log in to a Docker container registry. You need to provide the registry as the parameter for this command.
You will log in to a container registry after you provision one in the Creating and configuring Azure Container Registry section of this chapter.
This is one of the most important commands, used to build an image from a Dockerfile.
A Dockerfile is a regular text file that helps you to build container images. It contains different instructions or commands that you can execute in the Docker CLI. The format of a Dockerfile is like this:
INSTRUCTION argumentsA Dockerfile can have comments that start with a hash symbol (#). The instructions are not case-sensitive – it is the convention to use uppercase. The Dockerfile should start with a FROM instruction. The FROM instruction requires an image. Docker runs the instructions in the Dockerfile in the order of the commands written in the file. Here is an example of a Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime WORKDIR /app COPY published/ ./ ENTRYPOINT ["dotnet", "Chapter2.dll"]This Dockerfile uses the ASP.NET Core 6.0 runtime as the base image – FROM mcr.microsoft.com/dotnet/aspnet:6.0. The WORKDIR instruction sets the working directory as /app. Then, the COPY instruction copies the contents of the published directory to the /app directory, and finally, the ENTRYPOINT instruction helps to execute the dotnet command with the Chapter2.dll file.
In this section, we explored Docker, looked at various Docker commands, and saw how to create a Dockerfile. In the next section, we will learn how to create a Dockerfile for your ASP.NET Core application and create a Docker image of the application.
You can create, dockerize, or containerize your application using different tools. In this section, you will learn how to containerize your application with a Dockerfile, Docker CLI, VS Code, and Visual Studio.
Follow these steps to get started:
First, you need to create an empty .NET Core 6.0 web app. Here is the command to create an empty web app; you can create any type of ASP.NET Core application – MVC, Web API, or Razor Pages:> dotnet new web -o Chapter02 --framework net6.0The -o parameter creates the project in the Chapter02 folder and the framework version is .NET 6.0 – this is required if you don’t have multiple versions installed on your machine.
Next, in the project root folder, create a file with the name Dockerfile – no file extension. Then, paste the following code into the Dockerfile: FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime WORKDIR /app COPY published/ ./ ENTRYPOINT ["dotnet", "Chapter02.dll"]Next, you need to execute the command to publish the web app using the dotnet publish command. This is a very basic Dockerfile that is used to host the ASP.NET Core application. In the next section, you will learn about how to build the source code in a Docker container. Since the Dockerfile is using the published folder in the root folder, you need to execute the command with the output folder parameter, like this:> dotnet publish --configuration Release --output publishedNext, execute the docker build command like this:> docker build -t packtbook.azurecr.io/chapter02:1.0.0 .The docker build command’s -t parameter builds and tags the Docker image. The dot (.) specifies the location of the Dockerfile – in our case, it is the Chapter02 folder or the current directory. If the Dockerfile exists in a different directory, you need to mention it.
Figure 2.9: docker build command execution
Finally, you can run the container using the docker run command, like this:> docker run --publish 5000:80 packtbook.azurecr.io/Chapter02:1.0.0This command runs the Docker container, which exposes port 5000. The application is running on port 80 inside the container, so the web app will be accessible via localhost:5000. This is a very basic Dockerfile. If you’re using VS Code with a Docker extension or Visual Studio, you will be able to create a Dockerfile for your web application without writing any code.
.NET 7.0 – bonus tip
In .NET 7.0, Microsoft introduced a feature that helps publish Docker images without creating a Dockerfile. First, you need to add the reference of the Microsoft.NET.Build.Containers NuGet package to the project with the following command:
> dotnet add package Microsoft.NET.Build.Containers
Next, you can publish the Docker image using the following command:
> dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer
