Transitioning to NET core on red hat enterprise linux

137 94 0
Transitioning to  NET core on red hat enterprise linux

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Programming Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Transitioning to NET Core on Red Hat Enterprise Linux by Don Schenck Copyright © 2017 O’Reilly Media All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://oreilly.com/safari) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Nan Barber and Susan Conant Production Editor: Melanie Yarbrough Copyeditor: Gillian McGarvey Proofreader: Jasmine Kwityn Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest September 2016: First Edition Revision History for the First Edition 2016-09-20: First Release 2016-10-21: Second Release 2016-12-06: Third Release The O’Reilly logo is a registered trademark of O’Reilly Media, Inc Transitioning to NET Core on Red Hat Enterprise Linux, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work Use of the information and instructions contained in this work is at your own risk If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights 978-1-491-97055-3 [LSI] What to Expect from This Book This book is targeted at — but not limited toNET developers with any level of experience Starting with a basic “Hello World” console application, it moves along through ASP.NET, MVC, and Entity Framework applications, eventually arriving at a full-featured application running in a Linux container Because the code in this book is limited to C#, your existing knowledge of NET and C# will largely determine the speed at which you progress through this volume More experienced developers will be interested in the few key differences when developing for Linux (and there are quite a few), whereas beginning developers can use this book to learn more advanced programming techniques — the fact that those techniques are related to NET Core is just icing on the cake If you’ve spent most of your time writing code in a language other than C#, with Linux as your native operating system, don’t fret Though knowledge of C# is highly recommended, even a novice developer with a desire to learn can use this volume, perhaps in concert with another manual that guides the reader in C# development Some Assumptions This book assumes some previous experience with the NET Framework Again, while it’s technically not necessary to have prior knowledge when you begin reading, you will need to be familiar with NET (either by experience or education) to understand what’s happening Again, not to worry — the knowledge needed isn’t as deep as you might fear Grasp a few key concepts and you’ll be good to go For the purposes of simplicity, the Linux distribution used in the examples will be Red Hat Enterprise Linux (RHEL) Any adjustments necessary for other Linux distributions will be pointed out as we go Your Environment To follow along with the narrative and code, you need to install the Red Hat Container Development Kit (CDK) and clone or download a repository from GitHub Step-by-step instructions are provided in Chapter Formatting The following typographical conventions are used in this book: Text will be in the typeface you are reading now // Code is formatted like this: using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Command-line commands will be shown like this Italic Indicates new terms, URLs, email addresses, filenames, and file extensions Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords Constant width bold Shows commands or other text that should be typed literally by the user Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context Step 6: Start Debugging Open a command window in your Visual Studio IDE (Menu→View→Other Windows→Command Window) and type the following command, replacing the path to the options file (/OptionsFile) with the path to your OffRoadDebug.xml file: Debug.MIDebugLaunch /Executable:dotnet /OptionsFile:C:\src\mvc\OffRoadDebug.xml With this, your application will launch and you can set breakpoints and see variable values just as in Windows Note that if you view your VM session in a terminal session, you will not see the application running However, you can use the following command to verify that your command is running: ps -a You should expect an output that is similar to the one shown in Figure 11-4 Figure 11-4 The dotnet process Running this command, ps a, will show the dotnet command running with your DLL as the command parameter, as shown in Figure 11-5 Figure 11-5 dotnet running an application Finally, point your browser to the URL (10.1.2.2:5000 if using the Red Hat CDK) and you’ll see your website Happy debugging! Chapter 12 .NET Core, Linux, and Containers Microservices are the latest rage (or fad, depending on your view), and they go hand in hand with Linux containers Realizing that a VM is overkill for running one microservice, Linux containers fit the bill perfectly Small, quick to create, and highly portable, containers are here to stay Although NET is new to the Linux world, it is already a viable choice for creating container-based microservices Where the old NET required large swaths of disk space and memory, the new, more modular and lightweight version means that using a container is a valid choice For example, the difference between a RHEL image and a RHEL image with NET is only 140 MB Clearly, this is not your father’s NET Creating a container image using the Red Hat image as a base involves a few tricks This is because the image supplied by Red Hat is intended for use with their OpenShift container platform ASSOCIATED SOURCE CODE The source code used was created in Chapter Building the Image For now, let’s see how to build an image that we can use outside of OpenShift We’ll start by creating a new NET project in a new directory: mkdir mvc_docker cd mvc_docker dotnet new -t web Remember to change the Program.cs class to use the proper URL: http://0.0.0.0:5000 With the basic MVC application built, it’s time to construct the image Note that for this example you will need to have your VM registered with the Red Hat subscription manager This is because when building the image, the build command will inherit any necessary rights from the host — in this case, your VM You are prompted to register the VM when it starts (during vagrant up) If you didn’t register it then, you need to run vagrant halt and then vagrant up and select the option to register Configuring the Image The next step is to create the configuration to hold the image build instructions The following example uses the RHEL NET image to build an image containing your application Create a file named Dockerfile and add the following: FROM registry.access.redhat.com/dotnet/dotnetcore-10-rhel7 ADD /opt/app-root/src/ WORKDIR /opt/app-root/src/ EXPOSE 5000 RUN ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet restore"] RUN ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet build"] CMD ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet run"] If this is new to you, don’t fret I’ll explain it from top to bottom: FROM registry.access.redhat.com/dotnet/dotnetcore10-rhel7 This uses the official “.NET on RHEL” image as supplied by Red Hat Because it’s the official image, it will contain a version of RHEL and the latest version of NET ADD /opt/app-root/src/ This copies the contents of the current directory to the target directory in the image This is where the application ends up WORKDIR /opt/app-root/src/ This sets the working directory in your image EXPOSE 5000 When running in a container, you need to specify which port(s) will be exposed to the outside world In this case, it’s port 5000 This does not need to match your application; you can map your application’s port to this setting Without this setting, a port will be automatically assigned RUN ["/bin/bash", "-c", "/opt/rh/rhdotnetcore10/root/usr/bin/dotnet restore"] Using RUN causes the command that follows it to be executed when the image is being built In our case, we’re running dotnet restore in order to get all the dependencies into our image RUN ["/bin/bash", "-c", "/opt/rh/rhdotnetcore10/root/usr/bin/dotnet build"] This will build the application while the image is being created We don’t want it to build at runtime, as that will increase the container startup time Build it now, once, and save time every time this image is used CMD ["/bin/bash", "-c", "/opt/rh/rhdotnetcore10/root/usr/bin/dotnet run"] Using CMD causes the command that follows it to be executed when a container that uses this image is started This is not executed during the build phase With this in place, we build the image with the following command: docker build -t mvc_docker The -t option allows you to name and tag the image for later reference By default, using a single name (it must be all lowercase) will create a tag of :latest The preceding example would yield mvc_docker:latest You can create your own, for example: docker build -t mvc_docker:v1 docker build -t mvc_docker:v2 and so on Finally, notice the period at the end of the command This tells the build command to use the configuration file (Dockerfile) in the current directory A lot more is available when building For more information, use the docker build help command Running the Image in a Container Once this image is built, we can run it and view the web page Before that, you can view information about the image by running docker images, which lists all of your images Notice the size of the image, which now includes the bits for RHEL, NET, and your application Detailed information about your image — it’s interesting and worth viewing — can be obtained with the command docker inspect mvc_docker:latest Finally, to run the image, use the following command: docker run -d -p 5000:5000 mvc_docker:latest After this, open a browser and point it to the IP address 10.1.2.2:5000, where you’ll see your basic MVC website running in a container, using NET on Linux Chapter 13 Final Notes One of the challenges of writing a book is weighing time-to-create versus time-to-staleness of the content Take too long to write a book and by the time it’s finished it’s outdated With that in mind, this tome was written with one intent: to get the reader moving in the right direction as quickly as possible It’s not the be-all and end-all of NET on Linux, and there’s a lot more that can be covered But with this in hand, a willingness to learn and experiment, and some deft web search skills, the reader can be cranking out first-class NET applications just like that (snaps fingers) More and deeper coverage can be found on my ever-expanding web presence; simply visit redhatloves.net on a regular basis to stay up to date or learn more Another valuable website is obviously Microsoft’s NET Core page Finally, I’d be remiss if I didn’t give a solid “thank you” to my greatest inspiration and teacher, who — in 1991 — taught me the single most important thing to remember: When you write code, it’s not a communication between a programmer and a machine; it’s a communication between a programmer and another programmer Thank you, Paul Conte About the Author A developer since the beginning of time, Don Schenck is currently a Director of Developer Experience at Red Hat, with a focus on Microsoft NET on Linux His mission is to bring NET developers into the Linux and open source communities Prior to Red Hat, Don was a frontend and mobile developer He enjoys — no, loves — cooking and hates the designated hitter rule What to Expect from This Book Some Assumptions Your Environment Formatting NET Core Is the Future What’s Missing What’s New Setting Up Your Environment Your Red Hat Account Installing the CDK Disable Hyper-V Start Your VM Getting the Source Code Getting Started: From Zero to “Hello World” in One Chapter From Zero to “Hello World” in One Chapter Overview of NET Installing NET NET CLR NET CoreFX NET CLI ASP.NET Core Tooling Installation Instructions Other Linux Distros Keeping Current Your First NET Application on Linux Diving into the “Hello World” Application The dotnet new Command The dotnet restore Command What Gets Restored? Where Do the Dependencies Go? Library Versioning in project.json What Gets Built? “Hello World” for the Web The Kestrel Web Server The project.json File “Microsoft.AspNetCore.Server.IISIntegration”: “1.0.0” “Microsoft.AspNetCore.HttpOverrides”:" 1.0.0” “Microsoft.AspNetCore.Server.Kestrel”: “1.0.0” “frameworks”: “netcoreapp1.0” Program.cs: Where the Magic Happens ASP.NET and MVC Creating a Basic MVC Web Application MVC: An Inside Look Environments Error-Handling Example Startup Conventions and Environments Creating a RESTful Microservice RESTful Microservices Using Entity Framework Core Adding EF Is Easy The EF Command Other New Parts Creating a Standalone Application Creating the Application The Debug Build The Release Build Visual Studio Code Installing Visual Studio Code Launching VS Code 10 Editing from Windows The Key: Sharing Step 1: Create a Share on Your Windows PC Step 2: Share the Folder Step 3: Share the Folder with Your Linux VM Step 4: Restart the VM Step 5: Move into the VM and View the Directory 11 “Off-Road” Debugging Installation and Configuration Step 1: Enable Visual Studio on Windows Step 2: Install CLRDBG on the Linux VM Step 3: Set Up SSH Step 4: Share a Folder/Directory Step 5: Create Launch Options File Step 6: Start Debugging 12 .NET Core, Linux, and Containers Building the Image Configuring the Image Running the Image in a Container 13 Final Notes ...Programming Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Transitioning to NET Core on Red Hat Enterprise Linux by Don Schenck Copyright © 2017 O’Reilly... running the following command: git clone https://github.com/donschenck/NetOnLinuxBook You’ll now have a directory, NetOnLinuxBook, that contains subdirectories for this book NOTE When applicable,... stated that SignalR will be ported to NET Core NOTE From this point on, unless the difference is worth noting, references to NET CoreCLR, CoreFX, and the like, will be simplified to “ .NET What’s

Ngày đăng: 04/03/2019, 16:03

Từ khóa liên quan

Mục lục

  • What to Expect from This Book

    • Some Assumptions

    • Your Environment

    • Formatting

    • .NET Core Is the Future

    • What’s Missing

    • What’s New

    • 1. Setting Up Your Environment

      • Your Red Hat Account

      • Installing the CDK

      • Disable Hyper-V

      • Start Your VM

      • Getting the Source Code

      • 2. Getting Started: From Zero to “Hello World” in One Chapter

        • From Zero to “Hello World” in One Chapter

        • Overview of .NET

        • Installing .NET

          • .NET CLR

          • .NET CoreFX

          • .NET CLI

          • ASP.NET Core

          • Tooling

          • Installation Instructions

          • Other Linux Distros

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan