.NET Core+MySql+Nginx 容器化部署

.NET Core容器化@Docker
.NET Core容器化之多容器應用部署@Docker-Compose
.NET Core+MySql+Nginx 容器化部署
GitHub-Demo:Docker.NetCore.MySqlmysql

1. 引言

上兩節咱們經過簡單的demo學習了docker的基本操做。這一節咱們來一個進階學習,完成ASP.NET Core + MySql + Nginx的容器化部署。nginx

本文是基於CentOS 7.4環境進行演示,示例項目能夠訪問Docker.NetCore.MySql進行下載。git

2. Hello MySQL

一樣咱們仍是以按部就班的方式來展開。首先來基於Docker來試玩一下MySQL。github

2.1. 建立MySql實例

//拉取mysql鏡像
 docker pull mysql
$ docker images$
REPOSITORY                           TAG                 IMAGE ID            CREATED             SIZE
docker.io/mysql                      latest              7d83a47ab2d2        13 days ago         408.2 MB
//建立一個mysql實例
$ 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

下面咱們直接在容器中鏈接到咱們剛剛建立的mysql數據庫:web

$ docker exec -it hello.mysql \
> mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.20 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 rows in set (0.00 sec)

2.2. 掛載數據卷

上面建立的mysql實例其數據都在容器內部存儲,這樣就暴露了一個問題,若是容器銷燬,那麼對應的數據庫數據就會丟失。那如何持久化存儲容器內數據呢?咱們能夠經過掛載數據卷的方式來解決這一問題。sql

//建立數據卷
$ 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"
    }
]
// 掛載數據卷啓動MySql實例
$ docker run --name hello.mysql \
> -v hello.db:/var/lib/mysql \
> -e MYSQL_ROOT_PASSWORD=123456 -d mysql

上面是使用使用了docker volume create命令建立了一個數據卷,固然咱們也能夠自行掛載某個目錄做爲數據卷。docker

3. 準備.NET Core+EFCore+MySql項目

爲了演示方便,我準備了一個ASP.NET Core+EFCore+MySql的示例項目。其結構以下所示:
示例項目結構
是基於.NET Core Mvc模板項目,其中定義了一個Product實體,並經過ProductsController暴露WebApi接口。核心代碼以下:數據庫

Product實體類:json

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

DbContext類:api

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

    public DbSet<Product> Products { get; set; }
}

數據庫初始化類:

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();
    }
}

該數據庫初始化類會在項目啓動時運行。詳細代碼可參考Docker.NetCore.MySql

4. 基於示例項目進行實操演練

4.1 安裝Git並Clone示例項目

$ 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), 534.30 KiB | 333.00 KiB/s, done.
Resolving deltas: 100% (42/42), done.

4.2. 構建鏡像

細心的你會發現,項目中已經定義了Dockerfile,因此咱們能夠直接使用docker build構建鏡像。

# cd Docker.NetCore.MySql
[root@iZ288a3qazlZ Docker.NetCore.MySql]# ls
appsettings.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
//構建鏡像
# docker build -t docker.netcore.mysql .
Sending build context to Docker daemon 3.045 MB
Step 1 : FROM microsoft/dotnet:latest
 ---> 7d4dc5c258eb
Step 2 : WORKDIR /app
 ---> Using cache
 ---> 98d48a4e278c
Step 3 : COPY . /app
 ---> 6b1bf8bb5261
Removing intermediate container b86460477977
Step 4 : RUN dotnet restore
 ---> Running in 4e0a46f762bb
  Restoring packages for /app/Docker.NetCore.MySql.csproj...
  Installing Microsoft.CodeAnalysis.Razor 2.0.0.
  .....
  Restore completed in 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.mysql
REPOSITORY             TAG                 IMAGE ID            CREATED             SIZE
docker.netcore.mysql   latest              9d1fb6ee46cb        13 seconds ago      1.756 GB

4.3. 啓動鏡像並鏈接到指定數據庫

docker提供了--link參數用於在容器之間創建鏈接。下面咱們實例化建立的鏡像docker.netcore.mysql並命名容器名爲hello.netcore.mysql,並使用--link參數與咱們文章開頭創建的hello.mysql容器創建鏈接。

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

這裏須要特別注意一下--link=hello.mysql:db,這個參數就是告訴Docker容器須要使用hello.mysql容器,並將其別名命名爲db,這樣在hello.netcore.mysql這個容器中就可使用db來做爲提供mysql數據庫服務的服務器。這也就是爲何咱們.NET Core項目中鏈接字符串設置爲server=db;的緣由。
"ConnectionStrings": { "MySql": "server=db;database=MySqlDbContext;uid=root;pwd=123456;" }

//查看運行中容器列表
# 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        mysql                  "docker-entrypoint.sh"   About an hour ago   Up About an hour    3306/tcp                 hello.mysql
//訪問api/products
[root@iZ288a3qazlZ Docker.NetCore.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}]

從上圖可知,咱們完成了.NET Core與MySql的鏈接。

5. ASP.NET Core + MySql + Nginx

結合上一篇文章.NET Core容器化之多容器應用部署@Docker-Compose,咱們來使用docker-compose完成asp.net core + mysql + nginx的多容器部署。

5.1. 定義 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

其中定義了三個服務:

  1. db:使用mysql鏡像,並掛載當前項目下的mysql文件夾來持久化存儲。
  2. web:基於當前項目構建的容器服務,依賴於db服務。
  3. reverse-proxy:使用nginx定義反向代理服務,其中掛載了當前項目下的proxy.conf文件做爲反向代理配置文件。其中proxy.conf的配置以下(注意proxy_pass指定的url爲http://web:5000):
server {
    listen 8080;

    location / {
        proxy_pass http://web:5000;
    }
}

5.2. 啓動Compose

在啓動Compose以前,建議清空上面建立的容器。也可使用docker rm $(docker ps -qa)清除全部容器。

//啓動compose
[root@iZ288a3qazlZ Docker.NetCore.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 completed in 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 ps
   Name                 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.NetCore.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}]

上面的運行結果顯示,咱們已經成功完成了ASP.NET Core+MySql+Nginx的多容器應用部署。經過瀏覽器訪問http:<ipaddress>:9090/api/products便可訪問咱們暴露的api。

5.3. 數據庫驗證

咱們來驗證一下數據庫是否成功建立:

[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 command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.20 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 |       10 |
|         2 | iphone 7      | 6000.000000000000000000000000000000 |       10 |
|         3 | iphone 7 plus | 7000.000000000000000000000000000000 |       10 |
|         4 | iphone x      | 8000.000000000000000000000000000000 |       10 |
+-----------+---------------+-------------------------------------+----------+
4 rows in set (0.00 sec)

從上面的運行結果可知,咱們成功將項目文件夾下的mysql文件夾掛載到容器內部進行數據持久化。

6. 最後

本文經過先介紹如何基於Docker實例化MySQL容器,再介紹如何經過掛載數據捲來持久化MySQL數據,以及如何使用--Link參數進行容器之間的鏈接,完成了.NET Core鏈接MySQL數據庫。
最後,使用Docker-Compose綜合ASP.NET Core+MySQL+Nginx完成了容器化部署。

下一節咱們來介紹下如何使用Docker-Swarm進行集羣部署。

7. 參考資料

mysql -Docker Documentation
Hello Docker
.NET Core容器化@Docker
.NET Core容器化之多容器應用部署@Docker-Compose

相關文章
相關標籤/搜索