1. .NET Core containerized @docker
  2. .net Core containerized multi-container application deployment @docker-compose
  3. .net Core+MySql+Nginx container deployment
  4. GitHub-Demo:Docker.Net Core. MySql

1. The introduction

In the last two sections, we learned the basic operations of Docker through a simple demo. ASP.NET Core + MySql + Nginx container deployment

This article is based on CentOS 7.4 environment for demonstration, sample project can be accessed *Docker.Net core.mysql * download.

2. Hello MySQL

Again, we’re going to do it in a step-by-step way. First let’s try out MySQL based on Docker.

2.1. Create a MySql instance

// pull mysql $docker images$REPOSITORY TAG IMAGE ID CREATED SIZE docker. IO /mysql latest 7d83a47ab2d2 // Create a mysql instance $docker run --name hello.mysql-e MYSQL_ROOT_PASSWORD=123456 -d mysql
$ docker ps 
CONTAINER ID        IMAGE      COMMAND                  CREATED             STATUS              PORTS          NAMES
e21bbd84e0b5        mysql      "docker-entrypoint.sh"   3 minutes ago       Up 3 minutes        3306/tcp        hello.mysql
Copy the code

Here we connect directly to the mysql database we just created in the container:

$ docker exec -it hello.mysql \
> mysql -uroot -p123456
mysql: [Warning] Using a password on the commandline interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 8 Server version: MySQL Community Server (GPL) Copyright (C) 2000, 2017, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type'help; ' or '\h' for help. Type '\c'to clear the current input statement. mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys  | +--------------------+ 4 rowsin set (0.00 sec)

Copy the code

2.2. Mounting data volumes

The mysql instance created above has its data stored inside the container, exposing the problem that if the container is destroyed, the corresponding database data will be lost. So how do you persist the data in the container? We can solve this problem by mounting data volumes.

$docker volume create --name hello.db hello.db $docker volume inspect hello.db [{"Name": "hello.db"."Driver": "local"."Mountpoint": "/var/lib/docker/volumes/hello.db/_data"."Labels": {},
        "Scope": "local"}] $docker run --name hello. MySql \ > -v hello.db:/var/lib/mysql \ >-e MYSQL_ROOT_PASSWORD=123456 -d mysql
Copy the code

Docker volume create docker volume create docker volume create docker volume create docker volume create docker volume create

3. Prepare the.net Core+EFCore+MySql project

For demonstration purposes, I have prepared a sample project for ASP.NET Core+EFCore+MySql. Its structure is as follows:

Product
ProductsController

Product Entity class:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int StockQty { get; set; }}Copy the code

DbContext class:

public class MySqlDbContext : DbContext
{
    public MySqlDbContext (DbContextOptions<MySqlDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products { get; set; }}Copy the code

Database initialization classes:

public class DbInitializer
{
    public static void Initialize(MySqlDbContext context)
    {
        context.Database.EnsureCreated();

        if (context.Products.Any())
        {
            return;
        }

        var products = new Product[]
        {
            new Product{Name="iphone 6",Price=5000,StockQty=10 },
            new Product{Name="iphone 7",Price=6000,StockQty=10 },
            new Product{Name="iphone 7 plus",Price=7000,StockQty=10 },
            new Product{Name="iphone x",Price=8000,StockQty=10 } }; context.Products.AddRange(products); context.SaveChanges(); }}Copy the code

The database initialization class is run at project startup time. **Docker.Net core.mysql **

4. Conduct practical operation drills based on sample projects

4.1 Installing Git and Clone the sample project

$yum install git $git --version git version 1.8.3.1 $cd ~/demo
$ git clone https://github.com/yanshengjie/Docker.NetCore.MySql.git
Cloning into 'Docker.NetCore.MySql'. remote: Counting objects: 155, done. remote: Compressing objects: 100% (125/125), done. remote: Total 155 (delta 42), reused 123 (delta 25), pack-reused 0 Receiving objects: 100% (155/155) and 534.30 KiB | 333.00 KiB/s, done. Resolving deltas: 100% (42/42), and done.Copy the code

4.2. Build an Image

If you are careful, you will find that Dockerfile is already defined in the project, so we can directly use the Docker build to build the image.

# cd Docker.NetCore.MySql
[root@iZ288a3qazlZ Docker.NetCore.MySql]# lsappsettings.Development.json docker-compose.yml Program.cs Views appsettings.json Dockerfile proxy.conf wwwroot bundleconfig.json Docker.NetCore.MySql.csproj README.md Controllers LICENSE ScaffoldingReadMe.txt Data Models Startup.cs // Build the image# docker build -t docker.netcore.mysql .Sending build context to Docker Daemon 3.045 MB Step 1: Latest FROM Microsoft /dotnet --> 7d4dc5c258eb Step 2: WORKDIR /app ---> Using cache ---> 98d48a4e278c Step 3 : COPY . /app ---> 6b1bf8bb5261 Removing intermediate container b86460477977 Step 4 : RUN dotnet restore ---> Runningin 4e0a46f762bb
  Restoring packages for/app/Docker.NetCore.MySql.csproj... Installing Microsoft. CodeAnalysis. Razor 2.0.0.... Restore completedin 216.83 ms for /app/Docker.NetCore.MySql.csproj.
 ---> 4df70c77916e
Removing intermediate container 4e0a46f762bb
Step 5 : EXPOSE 5000
 ---> Running in 11b421b3bd3e
 ---> 3506253060fe
Removing intermediate container 11b421b3bd3e
Step 6 : ENV ASPNETCORE_URLS http://*:5000
 ---> Running in 201aabbab72c
 ---> 7f29963a8d96
Removing intermediate container 201aabbab72c
Step 7 : ENTRYPOINT dotnet run
 ---> Running in c79f73cba162
 ---> 9d1fb6ee46cb
Removing intermediate container c79f73cba162
Successfully built 9d1fb6ee46cb
[root@iZ288a3qazlZ Docker.NetCore.MySql]# docker images docker.netcore.mysqlREPOSITORY TAG IMAGE ID CREATED SIZE Docker.net core.mysql latest 9d1fb6EE46cb 13 seconds ago 1.756 GBCopy the code

4.3. Start the mirror and connect to the specified database

Docker provides the –link parameter to establish connections between containers. Mysql: hello.netcore.mysql: hello.Net core.mysql: hello.netcore.mysql: hello.netcore.mysql: hello.mysql: hello.mysql: hello.mysql: hello.mysql: hello.mysql: hello.mysql: hello.mysql

# docker run --name hello.netcore.mysql --link hello.mysql:db -d -p 5000:5000 
docker.netcore.mysql
Copy the code

Mysql :db link=hello.mysql:db This allows db to be used in the hello.netcore.mysql container as the server that provides mysql database services. And that’s why we. NET Core project connection string set to server=db; The reason why. “ConnectionStrings”: { “MySql”: “server=db; database=MySqlDbContext; uid=root; pwd=123456;” }

// View a list of running containers# docker ps 
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                    NAMES
5cbfd27ebe2a        docker.netcore.mysql   "dotnet run"2 minutes ago Up 2 minutes 0.0.0.0:5000->5000/ TCP hello.netcore. Mysql 4dfa4159b669"docker-entrypoint.sh"About an hour ago Up About an hour 3306/ TCP hello.mysql // access API /products [root@iZ288a3qazlZ Docker.Net core.mysql]# curl http://localhost:5000/api/products
[{"productId": 1,"name":"iphone 6"."price": 5000.0000000000000000000000000."stockQty": 10}, {"productId": 2."name":"iphone 7"."price": 6000.0000000000000000000000000."stockQty": 10}, {"productId": 3."name":"iphone 7 plus"."price": 7000.0000000000000000000000000."stockQty": 10}, {"productId": 4."name":"iphone x"."price": 8000.000000000000000000000000."stockQty": 10}]Copy the code

As you can see from the figure above, we’re done. NET Core connects to MySql.

5. ASP.NET Core + MySql + Nginx

In conjunction with the previous article. NET Core + mysql + nginx + docker-compose, NET Core + mysql + nginx + docker-compose, NET Core + mysql + nginx + docker-compose, NET Core + mysql + Nginx + docker-compose

5.1. Define the docker – compose. Yml

version: '2'
services:
  db:
    container_name: hello.db
    environment:
      MYSQL_ROOT_PASSWORD: 123456
  volumes:
    - ./mysql:/var/lib/mysql

  web:
    container_name: hello.web
    build: .
    depends_on:
      - db
    links:
      - db
  
  reverse-proxy:
    container_name: hello.proxy
    image: nginx
    depends_on:
      - web
    ports:
      - "9090:8080"
    volumes:
      - ./proxy.conf:/etc/nginx/conf.d/default.conf
Copy the code

Three services are defined:

  1. Db: Use the mysql image and mount the mysql folder under the current project for persistent storage.
  2. Web: Container services built based on the current project and dependent on db services.
  3. Reverse-proxy: uses nginx to define the reverse proxy service, in which the proxy.conf file of the current project is mounted as the reverse proxy configuration file. Conf is configured as follows (note that the url specified by proxy_pass is http://web:5000) :
server { listen 8080; location / { proxy_pass http://web:5000; }}Copy the code

5.2. Start Compose

Before starting Compose, it is recommended that you empty the container created above. You can also use docker RM $(Docker ps-QA) to clear all containers.

// Start compose [root@iZ288a3qazlZ Docker.Net core.mysql]# docker-compose up -d
Creating network "dockernetcoremysql_default" with the default driver
Building web
Step 1 : FROM microsoft/dotnet:latest
 ---> 7d4dc5c258eb
Step 2 : WORKDIR /app
 ---> Using cache
 ---> 98d48a4e278c
Step 3 : COPY . /app
 ---> d41b32323c0f
Removing intermediate container 1259f5fb82bc
Step 4 : RUN dotnet restore
 ---> Running in d482e355de77
  Restoring packages for/app/Docker.NetCore.MySql.csproj... Installing Microsoft. CodeAnalysis. Razor 2.0.0.... Restore completedin 216.83 ms for /app/Docker.NetCore.MySql.csproj.
 ---> a0658008f161
Removing intermediate container d482e355de77
Step 5 : EXPOSE 5000
 ---> Running in dc6eeb29fd5e
 ---> a419314ece08
Removing intermediate container dc6eeb29fd5e
Step 6 : ENV ASPNETCORE_URLS http://*:5000
 ---> Running in c1d1474b14a0
 ---> 9cc13c549042
Removing intermediate container c1d1474b14a0
Step 7 : ENTRYPOINT dotnet run
 ---> Running in efdf0e857a84
 ---> 830ac11428cf
Removing intermediate container efdf0e857a84
Successfully built 830ac11428cf
Creating hello.db ... done
Creating hello.web ... done
Creating hello.proxy ... done
Creating hello.web ...
Creating hello.proxy ...
[root@iZ288a3qazlZ Docker.NetCore.MySql]# docker ps
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                            NAMES
6253bf85682e        nginx                    "nginx -g 'daemon off"33 seconds ago Up 28 seconds 80/ TCP, 0.0.0.0:9090->8080/ TCP hello.proxy ea553a9e22f2 dockerNetCoremysql_web"dotnet run"             37 seconds ago      Up 32 seconds       5000/tcp                         hello.web
a1f5aa981bfb        mysql                    "docker-entrypoint.sh"   38 seconds ago      Up 36 seconds       3306/tcp                         hello.db
[root@iZ288a3qazlZ Docker.NetCore.MySql]# docker-compose psName Command State Ports ---------------------------------------------------------------------------------- hello.db docker-entrypoint.sh mysqld Up 3306/tcp hello.proxy nginx -g daemon off; Up 80/ TCP, 0.0.0.0:9090->8080/ TCP hello.web dotnet run Up 5000/ TCP [root@iZ288a3qazlZ Docker.Net core.mysql]# curl http://localhost:9090/api/products
[{"productId": 1,"name":"iphone 6"."price": 5000.0000000000000000000000000."stockQty": 10}, {"productId": 2."name":"iphone 7"."price": 6000.0000000000000000000000000."stockQty": 10}, {"productId": 3."name":"iphone 7 plus"."price": 7000.0000000000000000000000000."stockQty": 10}, {"productId": 4."name":"iphone x"."price": 8000.000000000000000000000000."stockQty": 10}]Copy the code

ASP.NET Core+MySql+Nginx multi-container application deployment has been successfully completed. To access our exposed API, visit HTTP :

:9090/ API /products via a browser.

5.3. Database verification

Let’s verify that the database was created successfully:

[root@iZ288a3qazlZ Docker.NetCore.MySql]# ls mysql
auto.cnf         client-key.pem         ib_logfile0  performance_schema  server-key.pem
ca-key.pem       MySqlDbContext  ib_logfile1  private_key.pem     sys
ca.pem           ib_buffer_pool         ibtmp1       public_key.pem
client-cert.pem  ibdata1                mysql        server-cert.pem
[root@iZ288a3qazlZ Docker.NetCore.MySql]# docker exec -it hello.db mysql -uroot -p123456
mysql: [Warning] Using a password on the commandline interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 8 Server version: MySQL Community Server (GPL) Copyright (C) 2000, 2017, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type'help; ' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+-----------------------+
| Database              |
+-----------------------+
| information_schema    |
| MySqlDbContext  |
| mysql                 |
| performance_schema    |
| sys                   |
+-----------------------+
5 rows in set (0.00 sec)

mysql> use MySqlDbContext;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------------------+
| Tables_in_MySqlDbContext |
+---------------------------------+
| Products                        |
+---------------------------------+
1 row in set(0.00 SEC) mysql> select * from Products; +-----------+---------------+-------------------------------------+----------+ | ProductId | Name | Price | StockQty | +-----------+---------------+-------------------------------------+----------+ | 1 | iphone 6 | 5000.000000000000000000000000000000 | | | | 2 iphone 7 6000.000000000000000000000000000000 10 | | | | 3 | iphone 7 Plus 7000.000000000000000000000000000000 | | | | | 4 iphone 8000.000000000000000000000000000000 x | | | 10 +-----------+---------------+-------------------------------------+----------+ 4 rowsin set (0.00 sec)
Copy the code

As can be seen from the above running result, we successfully mount the mysql folder under the project folder to the container for data persistence.

6. The final

This article first introduces how to instantiate MySQL container based on Docker, then introduces how to persist MySQL data by mounting data volume, and how to use –Link parameter between containers, complete. NET Core connects to the MySQL database. Finally, docker-compose integrated ASP.NET Core+MySQL+Nginx to complete the container deployment.

In the next section, we will introduce how to use Docker-swarm for cluster deployment.

7. Reference materials

  1. mysql -Docker Documentation
  2. Hello Docker
  3. .NET Core containerized @docker
  4. .net Core containerized multi-container application deployment @docker-compose