1. Trang chủ
  2. » Công Nghệ Thông Tin

IT training transitioning to NET core on red hat enterprise linux khotailieu

85 55 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 85
Dung lượng 2,66 MB

Nội dung

Co m pl im en ts of Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Beijing Boston Farnham Sebastopol Tokyo 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://safaribooksonline.com) 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 September 2016: Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest First Edition Revision History for the First Edition 2016-09-20: 2016-10-21: First Release First 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 limi‐ tation 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 responsi‐ bility to ensure that your use thereof complies with such licenses and/or rights 978-1-491-97308-0 [LSI] Table of Contents What to Expect from This Book v Setting Up Your Environment Your Red Hat Account Installing the CDK Disable Hyper-V Start Your VM Getting the Source Code 1 Getting Started: From Zero to “Hello World” in One Chapter From Zero to “Hello World” in One Chapter Overview of NET Installing NET Your First NET Application on Linux 7 12 Diving into the “Hello World” Application 15 The dotnet new Command The dotnet restore Command Library Versioning in project.json What Gets Built? 15 17 19 20 “Hello World” for the Web 21 The Kestrel Web Server The project.json File Program.cs: Where the Magic Happens 21 23 25 iii ASP.NET and MVC 29 Creating a Basic MVC Web Application MVC: An Inside Look Environments Error-Handling Example Startup Conventions and Environments 29 31 35 36 38 Creating a RESTful Microservice 39 RESTful Microservices 39 Using Entity Framework Core 43 Adding EF Is Easy The EF Command Other New Parts 44 45 45 Creating a Standalone Application 47 Creating the Application The Debug Build The Release Build 47 48 49 Visual Studio Code 51 Installing Visual Studio Code Launching VS Code 51 52 10 Editing from Windows 55 The Key: Sharing 56 11 “Off-Road” Debugging 59 Installation and Configuration 59 12 .NET Core, Linux, and Containers 67 Building the Image Configuring the Image Running the Image in a Container 68 68 70 13 Final Notes 71 iv | Table of Contents What to Expect from This Book This book is targeted at—but not limited to—.NET 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 appli‐ cation 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 differ‐ ences 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 con‐ cert with another manual that guides the reader in C# development Some Assumptions This book assumes some previous experience with the NET Frame‐ work 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 v For the purposes of simplicity, the Linux distribution used in the examples will be Red Hat Enterprise Linux (RHEL) Any adjust‐ ments 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, data‐ bases, data types, environment variables, statements, and key‐ words Constant width bold Shows commands or other text that should be typed literally by the user vi | What to Expect from This Book Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context This element signifies a tip or suggestion This element signifies a general note This element indicates a warning or caution .NET Core Is the Future In November 2014, Microsoft announced that the NET Framework would be transitioned to an open source development model This announcement was met with surprise and open arms by the NET community Although Microsoft had, up to that moment, done an admirable job of soliciting input from developers about NET fea‐ tures and bugs, making the source available meant a much higher level of engagement The standard open source model of using a GitHub repo—with issues, milestones, pull requests, and the related discussions—meant that anyone, anywhere could have instant and transparent access to the development team Developers could par‐ ticipate in discussions and research defects and workarounds Schedules and roadmaps would now be available to everyone, lead‐ ing to more realistic expectations Surprise announcements would give way to planned milestones Meanwhile, developers outside the NET world saw this as an opportunity to bring their open source experience and knowledge to one of the more pervasive software development platforms The free exchange of ideas, code reviews, and sense of community found its place inside the Microsoft-centric developer’s world The infusion of What to Expect from This Book | vii 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 applica‐ tion running However, you can use the following command to ver‐ ify 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 run‐ ning 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! Installation and Configuration | 65 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, con‐ tainers 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 67 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 direc‐ tory: 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 neces‐ sary 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: 68 | Chapter 12: NET Core, Linux, and Containers FROM registry.access.redhat.com/dotnet/dotnetcore-10rhel7 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/rh-dotnetcore10/ 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/rh-dotnetcore10/ 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/rh-dotnetcore10/ 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 exe‐ cuted 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 refer‐ ence By default, using a single name (it must be all lowercase) will Configuring the Image | 69 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 cur‐ rent 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 appli‐ cation 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 70 | Chapter 12: NET Core, Linux, and Containers 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 endall 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 firstclass 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 great‐ est 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 pro‐ grammer and a machine; it’s a communication between a program‐ mer and another programmer Thank you, Paul Conte 71 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—cook‐ ing and hates the designated hitter rule ... Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Beijing Boston Farnham Sebastopol Tokyo Transitioning to NET Core on Red Hat Enterprise Linux by Don Schenck Copyright... associated with this book You can this by running the fol‐ lowing command: git clone https://github.com/donschenck/NetOnLinuxBook You’ll now have a directory, NetOnLinuxBook, that contains subdir‐ ectories... have a Red Hat Enterprise Linux subscription, fol‐ low these instructions to install NET Core Note that you will need administrator privileges to perform the installation: sudo subscription-manager

Ngày đăng: 12/11/2019, 22:33

TỪ KHÓA LIÊN QUAN