Visual Studio Code and Docker develop ASP. NET core and MySQL applications

Source: Internet
Author: User
Tags generator mysql connection string sqlite docker for mac docker ps docker hub docker run connectionstrings


Visual Studio Code and Docker develop ASP. NET core and MySQL applications


The. NET ape met the little whale and felt more and more excited. Originally, the. NET ape was just looking out of the world through the window of the house, but watching the apple orchard on the other side of the channel more and more lush, I really do not want to be an ape. So, the. NET ape decided to catch the little whale ferry to the apple orchard to see.



The. NET ape on the little whale Ferries first asked a question, is there an IDE in the apple orchard that can be used to write C # code as powerful as Visual Studio? At this time, the sky flashed a gamma ray, Eric Hulk said, give you a Visual Studio Code, go play. So the. NET ape took the little whale's fast boat to the Apple Hill and started his Apple-eating trip.



... ... Small series can only suppress so much, or to dry it.



Today, let's look at how to develop an ASP. NET Core application using Visual Studio Code on MacOS, and use Docker for development debugging and deployment. Before using Visual Studio, we saw a good integration, the IDE has all the toolchain configuration, all you have to do is F5, today we will try hand-written dockerfile and docker-compose files. In addition, since we want to open source, we are completely, this time we no longer use SQLite or SQL Server as a database, and the use of open source world's most popular MySQL as our application backend database.


Preparing the development environment


First we need to download and install a few tools



1. Visual Studio Code and. Net Core



Visual Studio Code is a free, open source cross-platform coding editor for Developers, and other popular code editors like Sublime, Atom, which are very small, run fast, At the same time through a variety of plug-ins to support different development language writing. The difference is that the VSC plugin not only provides static language highlighting, automatic syntax detection and completion, but also provides more advanced compiler service support, which allows VSC to somewhat replace the IDE's capabilities for code compilation, debugging, and publishing operations.






: https://code.visualstudio.com
(You can also enter d4dtools in the public number to get the latest version of the code installation package, available in different versions of Windows/mac/linux)



ASP. NET Core is a cross-platform ASP. The installation package on MacOS can be downloaded from the following address






: http://dot.net



Note: If you have previously installed the. NET core of ASP. 5 or RC, you need to uninstall it before running the above installation command, download the dotnet-uninstall-pkgs.sh in the D4dtools network disk, and run it.



2. Node. js and NPM, as well as front-end tools such as Bower, Gulp and Grunt



node. JS is a JavaScript run engine that provides server-side JavaScript capabilities and includes NPM, a package manager that can be used to install Bower, Glup,grunt and other front-end tools.






: http://nodejs.org
(Windows and Mac versions with v4.4.7 LTS installation package in D4dtools)



Once the installation is complete, let's install the front end tool with the following command


NPM Install Bower Gulp Grunt-cli-g


3. Install the project template Generation tool Yeoman and ASP. Generator



Yeoman is a tool used to create a project template, used by Visual Studio developers must be very fond of the new project's boot tool, choose the type of project you want to use can create a running basic project framework, which makes starting a project or learning programming is very easy. The Yeman provides the same functionality.






Run the following command to complete the yeoman installation


NPM Install Yo-g


Different generator (template generators) are provided in Yeoman to provide the generation of different types of projects, in order to be able to generate an ASP. NET core application, we need to install the ASPNET generator


NPM Install Generator-aspnet-g


You can create a project after you install it






You can also create generator yourself, and refer to the GitHub source code of the ASPNET generator to learn.
Https://github.com/omnisharp/generator-aspnet



4. Docker for Mac



Like Docker for Windows, we can install Docker for Mac on MacOS to support the management of the Docker environment.






: Https://www.docker.com/products/docker
(D4dtools network disk: DOCKER.DMG)



At this point, our development environment is ready for completion.


Create an ASP. NET Core WebApp


With these tools, we can build applications very smoothly.



1. Create a project template



First create an app directory, source code directory


mkdir aspnet-mysql
cd aspnet-mysql
mkdir src


Then enter the SRC directory to create the project using Yoman


cd src
yo aspnet


Select Web application [without membership and Authorization] as the project type, bootstrap as the front end frame, and give the app name Aspnet-mysql






After the carriage return, Yoman creates the code file structure in the project and runs Bower install to complete the required JAVASCRIPT/CSS installation



Then run the following command to complete the installation of the NuGet dependency package for ASP.


cd aspnet-mysql
dotnet restore


Finally, type the following command to open the Visual Studio Code


Code.


At this point, VSC automatically generates the following configuration file for configuring the development debug Toolchain in the VSC


.vscode/launch.json
.vscode/task.json


Now you can switch to debug view and click the Run button to start debugging your app, or you can set breakpoints in your code, step through the same steps as in Visual Studio, and see the change in the value of the variable.






2. Create a MySQL container as a development database



The development of a database typically requires us to install a database engine on its own machine, and now with Docker, we can run a database engine in the container. There are many advantages to this, 1) your own machine can be very clean, do not worry about the various programs between the conflicting; 2) the database with the use of the open, when not used to switch off, do not occupy resources, 3) can be used every time with a clean database debugging, do not worry about the recovery of data status, if necessary, You can also synchronize the contents of the data volume in the container to the local computer.



To do this, first you need a containerized host, and you can refer to the second article in this series, "Docker4dotnet," the practice of containerized host



Here I use a Docker host running on a local vmwarefusion






First redirect The Docker command to this host with the following command


Eval $ (docker-machine env {machine-name})


Run the following command to start a MySQL database container, create a data called EF, and expose 3306 ports to your on-premises environment


Docker run--name mysql-dev-e mysql_root_password=p2ssw0rd-e mysql_database=ef-p 3306:3306-d MySQL


Parameter description:


    • Name: Give the container a name called Mysql-dev, so that it is easy to manage with the back, if you do not give a name, Docker will give a random name
    • -E: Configure the environment variables for the container, where I configured the
      • Mysql_root_password:root User Password
      • Mysql_database: New database name, MySQL container will create an empty database with the name EF as required
    • -P: Exposing ports, exposing 3306 ports for easy management


If you do not have a local MySQL image, Docker will go to the Docker hub to download, if you already have the image then the boot is really millisecond, you can use the management tool to connect to this container when the boot is complete, here I use the MySQL Workbench






You can see that the EF database has been created.



3. Configure the ASP. NET application to use MySQL as the Entity Framework data source



The default ASP. NET application uses SQL Server or LOCALDB as the data source on Windows, and SQLite is used on non-Windows systems. Here, LocalDB and SQLite can only be used as development debugging purposes, if need to put into production to use SQL Server, corresponding to open source products, we can choose MySQL as a substitute for SQL Server. In the previous step we have configured the MySQL server (container) for development, and now we need to configure the application so that the Entity Framework can use MySQL as the data source.



Here, we are using an open source library that is contributed by our domestic developers, and GitHub addresses the following:
Https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql



First, add the following references in the Dependencies configuration section of the Project.json file:


"POMELO.ENTITYFRAMEWORKCORE.MYSQL": "1.0.0-prerelease-20160726"


Add a Nuget.config profile at the same time and add the source address of the pomelo in it, mainly because the NuGet library is not officially released and will not be configured after release.


<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <packageSources>
 <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
 <add key="PomeloMysql" value="https://www.myget.org/F/pomelo/api/v2/"/>
 </packageSources>
</configuration>





Then run dotnet restore again, this time adding –configfile nuget.config This parameter to ensure that dotnet restore can use the NuGet source correctly


dotnet Restore--configfile Nuget.config


4. Add MVC model to the project



Now that we can create our entity classes in the project, and for the sake of demonstration convenience, I've added some sample data.



Code files Https://github.com/ups216/aspnet-mysql/blob/master/src/aspnet-mysql/Models/Blog.cs






Then add the dependency Injection code in the Configureservices method in the Starup.cs


services.AddDbContext(options=>
 options.UseMySql(Configuration.GetConnectionString("Mysql")));


Call Sampledata.initdb in the Configure method to create the sample data


Await Sampledata.initdb (app. ApplicationServices);


code file: Https://github.com/ups216/aspnet-mysql/blob/master/src/aspnet-mysql/Startup.cs



Create a connection string named MySQL in Appsetting.json


"ConnectionStrings": {
 "DefaultConnection": "Data Source=aspnetweb01.db",
 "Mysql": "Server={docker machine ip};database=ef;uid=root;pwd=P2ssw0rd;"
 }


code file: Https://github.com/ups216/aspnet-mysql/blob/master/src/aspnet-mysql/appsettings.json



Ensure that the UID and PWD parameters are consistent with the Mysql_database,mysql_root_password in the Docker Run command
The [Docker machine IP] address can be obtained by using the following command


Docker-machine IP


Now, once again using the VSC startup app for debugging, you can see that blogs and the users two tables have been created and written to sample data in the EF data in MySQL.





Use Docker packaging to publish your app


We have completed the creation of the ASP. NET application and have used a MySQL running in the container for development debugging, now we need to use Docker to package and run the application in the container.



1. Create Dockerfile



The app created with Yoman already contains a dockerfile, and we just need to make simple changes
The file contents are as follows


FROM microsoft/dotnet:latest
COPY . /app
WORKDIR /app
RUN ["dotnet", "restore", "--configfile", "nuget.config"]
RUN ["dotnet", "build"]
EXPOSE 5000/tcp
ENTRYPOINT ["dotnet", "run", "--server.urls", "http://0.0.0.0:5000"]


Code Link: https://github.com/ups216/aspnet-mysql/blob/master/src/aspnet-mysql/Dockerfile



This file is simple, let's see what it does:


    • From Microsoft/dotnet:latest tells Docker build to use the latest version of the microsoft/dotnet image as our base image
    • COPY. /app Copy all files from the Dockerfile directory on this machine to the/app directory of the container
    • The Workdir/app settings container uses/app as the working directory, so that subsequent operations are performed in this directory
    • Run dotnet Restore and run dotnet build tells the Docker build to execute dotnet Restore and dotnet build two commands while using Nuget.config as a configuration file for restore
    • EXPOSE 5000/TCP Exposed 5000 ports
    • entrypoint ["Dotnet", "Run", "–server.urls", "http://0.0.0.0:5000"], set the container entry to the dotnet Run command, this command will launch our app


2. Build the container image and run the container



Now, we can run the following command to complete the container build


Docker build-t {image name}.


where {image name} You can get up, I use ups216/aspnet-mysql here, this is the name I want to upload to the Docker hub









This step in dotnet restore will be slow because all dependent packages need to be downloaded.



Note: In daily development, you can create your own base image with a common package, replacing the microsoft/dotnet in dockerfile so that you don't have to re-download the package every time.



Now type the docker images command to see our newly created image.






Run


Docker run--name aspnet-msyql-dev-p 5000:5000 ups216/aspnet-msyql





You can see that our container is now properly connected to the external port of the MySQL container. Enter the IP address of the Docker host in the browser: Port 5000, our application is completely running in the container.






The 2 containers you see in Docker PS are like this






3. Production Deployment Packaging



In the above process we have deployed the application to the container and connected to a MySQL service running in another container. However, our connection is connected through the port that the MySQL container exposes to the host, which is easier to do during development, because you can use the container's utilities to connect to MySQL, but it's not a good idea if you want to publish externally.



At the same time, I want to be able to deploy the Web application and the MySQL container together to form a complete application deployment package. At this time, we need to use Docker-compose to complete.



First, we create a configuration file for the production environment, appsettings. Production.json, the contents are as follows:


{
 "ConnectionStrings": {
       "DefaultConnection": "Data Source=aspnetweb01.db",
       "Mysql": "Server=db;database=ef;uid=ef;pwd=P2ssw0rd;"
 },
 "Logging": {
      "IncludeScopes": false,
           "LogLevel": {
           "Default": "Debug",
           "System": "Information",
           "Microsoft": "Information"
           }
      }
 }


Code Link: Https://github.com/ups216/aspnet-mysql/blob/master/src/aspnet-mysql/appsettings.Production.json



Here we mainly modify the MySQL connection string, use DB as the database, and use EF as the connection user.



We then create a docker-compose.yml file with the following content:


version: ‘2‘
 services:
   db:
     image: mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: P2ssw0rd
       MYSQL_DATABASE: ef
       MYSQL_USER: ef
       MYSQL_PASSWORD: P2ssw0rd

   web:
     build: .
     depends_on:
       - db
     links:
       - db
     ports:
       - "5000:5000"
     restart: always
     environment:
     ASPNETCORE_ENVIRONMENT: Production


The contents of the content can basically read from the literal meaning, here the main creation of the DB and web two containers, the Web container relies on the DB container, and through the name of the DB link past, and set the environment environment variable of the ASP. NET core is production.



Corresponding to the above we are in appsettings. Production.json the changes made in the file, you can understand that we configure our app by Production this environment variable to link to a database named EF on a MySQL server called db, and use EF as the user name.



Now, you just need to run the following command to start the two containers.


Docker-compose up





The above code has been posted on my GitHub with the following address:



https://github.com/ups216/aspnet-mysql/



If you have installed all the tools in the first part of this article, then you should be able to start the application directly with line docker-compose up; I've recorded a simple video (3 minutes) to illustrate the process.






Related articles:


    • Docker4dotnet #1 past life & World Hello
    • Docker4dotnet #2 containerized Host
    • docker– 10 things you should know





Please follow the public number "Devopshub" For more information on DevOps integration



Visual Studio Code and Docker develop ASP. NET core and MySQL applications


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.