资讯专栏INFORMATION COLUMN

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

ybak / 1278人阅读

摘要:容器化容器化之多容器应用部署容器化部署引言上两节我们通过简单的学习了的基本操作。基于当前项目构建的容器服务,依赖于服务。最后,使用综合完成了容器化部署。参考资料容器化容器化之多容器应用部署

</>复制代码

  1. .NET Core容器化@Docker
    .NET Core容器化之多容器应用部署@Docker-Compose
    .NET Core+MySql+Nginx 容器化部署
    GitHub-Demo:Docker.NetCore.MySql
1. 引言

上两节我们通过简单的demo学习了docker的基本操作。这一节我们来一个进阶学习,完成ASP.NET Core + MySql + Nginx的容器化部署。

本文是基于CentOS 7.4环境进行演示,示例项目可以访问Docker.NetCore.MySql进行下载。

2. Hello MySQL

同样我们还是以循序渐进的方式来展开。首先来基于Docker来试玩一下MySQL。

2.1. 创建MySql实例

</>复制代码

  1. //拉取mysql镜像
  2. docker pull mysql
  3. $ docker images$
  4. REPOSITORY TAG IMAGE ID CREATED SIZE
  5. docker.io/mysql latest 7d83a47ab2d2 13 days ago 408.2 MB
  6. //创建一个mysql实例
  7. $ docker run --name hello.mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql
  8. $ docker ps
  9. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  10. e21bbd84e0b5 mysql "docker-entrypoint.sh" 3 minutes ago Up 3 minutes 3306/tcp hello.mysql

下面我们直接在容器中连接到我们刚刚创建的mysql数据库:

</>复制代码

  1. $ docker exec -it hello.mysql
  2. > mysql -uroot -p123456
  3. mysql: [Warning] Using a password on the command line interface can be insecure.
  4. Welcome to the MySQL monitor. Commands end with ; or g.
  5. Your MySQL connection id is 8
  6. Server version: 5.7.20 MySQL Community Server (GPL)
  7. Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  8. Oracle is a registered trademark of Oracle Corporation and/or its
  9. affiliates. Other names may be trademarks of their respective
  10. owners.
  11. Type "help;" or "h" for help. Type "c" to clear the current input statement.
  12. mysql> show databases;
  13. +--------------------+
  14. | Database |
  15. +--------------------+
  16. | information_schema |
  17. | mysql |
  18. | performance_schema |
  19. | sys |
  20. +--------------------+
  21. 4 rows in set (0.00 sec)
2.2. 挂载数据卷

上面创建的mysql实例其数据都在容器内部存储,这样就暴露了一个问题,如果容器销毁,那么对应的数据库数据就会丢失。那如何持久化存储容器内数据呢?我们可以通过挂载数据卷的方式来解决这一问题。

</>复制代码

  1. //创建数据卷
  2. $ docker volume create --name hello.db
  3. hello.db
  4. //查看数据卷信息
  5. $ docker volume inspect hello.db
  6. [
  7. {
  8. "Name": "hello.db",
  9. "Driver": "local",
  10. "Mountpoint": "/var/lib/docker/volumes/hello.db/_data",
  11. "Labels": {},
  12. "Scope": "local"
  13. }
  14. ]
  15. // 挂载数据卷启动MySql实例
  16. $ docker run --name hello.mysql
  17. > -v hello.db:/var/lib/mysql
  18. > -e MYSQL_ROOT_PASSWORD=123456 -d mysql

上面是使用使用了docker volume create命令创建了一个数据卷,当然我们也可以自行挂载某个目录作为数据卷。

3. 准备.NET Core+EFCore+MySql项目

为了演示方便,我准备了一个ASP.NET Core+EFCore+MySql的示例项目。其结构如下所示:

是基于.NET Core Mvc模板项目,其中定义了一个Product实体,并通过ProductsController暴露WebApi接口。核心代码如下:

Product实体类:

</>复制代码

  1. public class Product
  2. {
  3. public int ProductId { get; set; }
  4. public string Name { get; set; }
  5. public decimal Price { get; set; }
  6. public int StockQty { get; set; }
  7. }

DbContext类:

</>复制代码

  1. public class MySqlDbContext : DbContext
  2. {
  3. public MySqlDbContext (DbContextOptions options)
  4. : base(options)
  5. {
  6. }
  7. public DbSet Products { get; set; }
  8. }

数据库初始化类:

</>复制代码

  1. public class DbInitializer
  2. {
  3. public static void Initialize(MySqlDbContext context)
  4. {
  5. context.Database.EnsureCreated();
  6. if (context.Products.Any())
  7. {
  8. return;
  9. }
  10. var products = new Product[]
  11. {
  12. new Product{Name="iphone 6",Price=5000,StockQty=10 },
  13. new Product{Name="iphone 7",Price=6000,StockQty=10 },
  14. new Product{Name="iphone 7 plus",Price=7000,StockQty=10 },
  15. new Product{Name="iphone x",Price=8000,StockQty=10 }
  16. };
  17. context.Products.AddRange(products);
  18. context.SaveChanges();
  19. }
  20. }

该数据库初始化类会在项目启动时运行。详细代码可参考Docker.NetCore.MySql

4. 基于示例项目进行实操演练 4.1 安装Git并Clone示例项目

</>复制代码

  1. $ yum install git
  2. $ git --version
  3. git version 1.8.3.1
  4. $ cd ~/demo
  5. $ git clone https://github.com/yanshengjie/Docker.NetCore.MySql.git
  6. Cloning into "Docker.NetCore.MySql"...
  7. remote: Counting objects: 155, done.
  8. remote: Compressing objects: 100% (125/125), done.
  9. remote: Total 155 (delta 42), reused 123 (delta 25), pack-reused 0
  10. Receiving objects: 100% (155/155), 534.30 KiB | 333.00 KiB/s, done.
  11. Resolving deltas: 100% (42/42), done.
4.2. 构建镜像

细心的你会发现,项目中已经定义了Dockerfile,所以我们可以直接使用docker build构建镜像。

</>复制代码

  1. # cd Docker.NetCore.MySql
  2. [root@iZ288a3qazlZ Docker.NetCore.MySql]# ls
  3. appsettings.Development.json docker-compose.yml Program.cs Views
  4. appsettings.json Dockerfile proxy.conf wwwroot
  5. bundleconfig.json Docker.NetCore.MySql.csproj README.md
  6. Controllers LICENSE ScaffoldingReadMe.txt
  7. Data Models Startup.cs
  8. //构建镜像
  9. # docker build -t docker.netcore.mysql .
  10. Sending build context to Docker daemon 3.045 MB
  11. Step 1 : FROM microsoft/dotnet:latest
  12. ---> 7d4dc5c258eb
  13. Step 2 : WORKDIR /app
  14. ---> Using cache
  15. ---> 98d48a4e278c
  16. Step 3 : COPY . /app
  17. ---> 6b1bf8bb5261
  18. Removing intermediate container b86460477977
  19. Step 4 : RUN dotnet restore
  20. ---> Running in 4e0a46f762bb
  21. Restoring packages for /app/Docker.NetCore.MySql.csproj...
  22. Installing Microsoft.CodeAnalysis.Razor 2.0.0.
  23. .....
  24. Restore completed in 216.83 ms for /app/Docker.NetCore.MySql.csproj.
  25. ---> 4df70c77916e
  26. Removing intermediate container 4e0a46f762bb
  27. Step 5 : EXPOSE 5000
  28. ---> Running in 11b421b3bd3e
  29. ---> 3506253060fe
  30. Removing intermediate container 11b421b3bd3e
  31. Step 6 : ENV ASPNETCORE_URLS http://*:5000
  32. ---> Running in 201aabbab72c
  33. ---> 7f29963a8d96
  34. Removing intermediate container 201aabbab72c
  35. Step 7 : ENTRYPOINT dotnet run
  36. ---> Running in c79f73cba162
  37. ---> 9d1fb6ee46cb
  38. Removing intermediate container c79f73cba162
  39. Successfully built 9d1fb6ee46cb
  40. [root@iZ288a3qazlZ Docker.NetCore.MySql]# docker images docker.netcore.mysql
  41. REPOSITORY TAG IMAGE ID CREATED SIZE
  42. docker.netcore.mysql latest 9d1fb6ee46cb 13 seconds ago 1.756 GB
4.3. 启动镜像并连接到指定数据库

docker提供了--link参数用于在容器之间建立连接。下面我们实例化创建的镜像docker.netcore.mysql并命名容器名为hello.netcore.mysql,并使用--link参数与我们文章开头建立的hello.mysql容器建立连接。

</>复制代码

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

</>复制代码

  1. 这里需要特别注意一下--link=hello.mysql:db,这个参数就是告诉Docker容器需要使用hello.mysql容器,并将其别名命名为db,这样在hello.netcore.mysql这个容器中就可以使用db来作为提供mysql数据库服务的服务器。这也就是为什么我们.NET Core项目中连接字符串设置为server=db;的原因。
    ` "ConnectionStrings": {

</>复制代码

  1. "MySql": "server=db;database=MySqlDbContext;uid=root;pwd=123456;"

}`

</>复制代码

  1. //查看运行中容器列表
  2. # docker ps
  3. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  4. 5cbfd27ebe2a docker.netcore.mysql "dotnet run" 2 minutes ago Up 2 minutes 0.0.0.0:5000->5000/tcp hello.netcore.mysql
  5. 4dfa4159b669 mysql "docker-entrypoint.sh" About an hour ago Up About an hour 3306/tcp hello.mysql
  6. //访问api/products
  7. [root@iZ288a3qazlZ Docker.NetCore.MySql]# curl http://localhost:5000/api/products
  8. [{"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

</>复制代码

  1. version: "2"
  2. services:
  3. db:
  4. container_name: hello.db
  5. environment:
  6. MYSQL_ROOT_PASSWORD: 123456
  7. volumes:
  8. - ./mysql:/var/lib/mysql
  9. web:
  10. container_name: hello.web
  11. build: .
  12. depends_on:
  13. - db
  14. links:
  15. - db
  16. reverse-proxy:
  17. container_name: hello.proxy
  18. image: nginx
  19. depends_on:
  20. - web
  21. ports:
  22. - "9090:8080"
  23. volumes:
  24. - ./proxy.conf:/etc/nginx/conf.d/default.conf

其中定义了三个服务:

db:使用mysql镜像,并挂载当前项目下的mysql文件夹来持久化存储。

web:基于当前项目构建的容器服务,依赖于db服务。

reverse-proxy:使用nginx定义反向代理服务,其中挂载了当前项目下的proxy.conf文件作为反向代理配置文件。其中proxy.conf的配置如下(注意proxy_pass指定的url为http://web:5000):

</>复制代码

  1. server {
  2. listen 8080;
  3. location / {
  4. proxy_pass http://web:5000;
  5. }
  6. }
5.2. 启动Compose

在启动Compose之前,建议清空上面创建的容器。也可以使用docker rm $(docker ps -qa)清除所有容器。

</>复制代码

  1. //启动compose
  2. [root@iZ288a3qazlZ Docker.NetCore.MySql]# docker-compose up -d
  3. Creating network "dockernetcoremysql_default" with the default driver
  4. Building web
  5. Step 1 : FROM microsoft/dotnet:latest
  6. ---> 7d4dc5c258eb
  7. Step 2 : WORKDIR /app
  8. ---> Using cache
  9. ---> 98d48a4e278c
  10. Step 3 : COPY . /app
  11. ---> d41b32323c0f
  12. Removing intermediate container 1259f5fb82bc
  13. Step 4 : RUN dotnet restore
  14. ---> Running in d482e355de77
  15. Restoring packages for /app/Docker.NetCore.MySql.csproj...
  16. Installing Microsoft.CodeAnalysis.Razor 2.0.0.
  17. .....
  18. Restore completed in 216.83 ms for /app/Docker.NetCore.MySql.csproj.
  19. ---> a0658008f161
  20. Removing intermediate container d482e355de77
  21. Step 5 : EXPOSE 5000
  22. ---> Running in dc6eeb29fd5e
  23. ---> a419314ece08
  24. Removing intermediate container dc6eeb29fd5e
  25. Step 6 : ENV ASPNETCORE_URLS http://*:5000
  26. ---> Running in c1d1474b14a0
  27. ---> 9cc13c549042
  28. Removing intermediate container c1d1474b14a0
  29. Step 7 : ENTRYPOINT dotnet run
  30. ---> Running in efdf0e857a84
  31. ---> 830ac11428cf
  32. Removing intermediate container efdf0e857a84
  33. Successfully built 830ac11428cf
  34. Creating hello.db ... done
  35. Creating hello.web ... done
  36. Creating hello.proxy ... done
  37. Creating hello.web ...
  38. Creating hello.proxy ...
  39. [root@iZ288a3qazlZ Docker.NetCore.MySql]# docker ps
  40. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  41. 6253bf85682e nginx "nginx -g "daemon off" 33 seconds ago Up 28 seconds 80/tcp, 0.0.0.0:9090->8080/tcp hello.proxy
  42. ea553a9e22f2 dockernetcoremysql_web "dotnet run" 37 seconds ago Up 32 seconds 5000/tcp hello.web
  43. a1f5aa981bfb mysql "docker-entrypoint.sh" 38 seconds ago Up 36 seconds 3306/tcp hello.db
  44. [root@iZ288a3qazlZ Docker.NetCore.MySql]# docker-compose ps
  45. Name Command State Ports
  46. ----------------------------------------------------------------------------------
  47. hello.db docker-entrypoint.sh mysqld Up 3306/tcp
  48. hello.proxy nginx -g daemon off; Up 80/tcp, 0.0.0.0:9090->8080/tcp
  49. hello.web dotnet run Up 5000/tcp
  50. [root@iZ288a3qazlZ Docker.NetCore.MySql]# curl http://localhost:9090/api/products
  51. [{"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::9090/api/products即可访问我们暴露的api。

5.3. 数据库验证

我们来验证一下数据库是否成功创建:

</>复制代码

  1. [root@iZ288a3qazlZ Docker.NetCore.MySql]# ls mysql
  2. auto.cnf client-key.pem ib_logfile0 performance_schema server-key.pem
  3. ca-key.pem MySqlDbContext ib_logfile1 private_key.pem sys
  4. ca.pem ib_buffer_pool ibtmp1 public_key.pem
  5. client-cert.pem ibdata1 mysql server-cert.pem
  6. [root@iZ288a3qazlZ Docker.NetCore.MySql]# docker exec -it hello.db mysql -uroot -p123456
  7. mysql: [Warning] Using a password on the command line interface can be insecure.
  8. Welcome to the MySQL monitor. Commands end with ; or g.
  9. Your MySQL connection id is 8
  10. Server version: 5.7.20 MySQL Community Server (GPL)
  11. Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  12. Oracle is a registered trademark of Oracle Corporation and/or its
  13. affiliates. Other names may be trademarks of their respective
  14. owners.
  15. Type "help;" or "h" for help. Type "c" to clear the current input statement.
  16. mysql> show databases;
  17. +-----------------------+
  18. | Database |
  19. +-----------------------+
  20. | information_schema |
  21. | MySqlDbContext |
  22. | mysql |
  23. | performance_schema |
  24. | sys |
  25. +-----------------------+
  26. 5 rows in set (0.00 sec)
  27. mysql> use MySqlDbContext;
  28. Reading table information for completion of table and column names
  29. You can turn off this feature to get a quicker startup with -A
  30. Database changed
  31. mysql> show tables;
  32. +---------------------------------+
  33. | Tables_in_MySqlDbContext |
  34. +---------------------------------+
  35. | Products |
  36. +---------------------------------+
  37. 1 row in set (0.00 sec)
  38. mysql> select * from Products;
  39. +-----------+---------------+-------------------------------------+----------+
  40. | ProductId | Name | Price | StockQty |
  41. +-----------+---------------+-------------------------------------+----------+
  42. | 1 | iphone 6 | 5000.000000000000000000000000000000 | 10 |
  43. | 2 | iphone 7 | 6000.000000000000000000000000000000 | 10 |
  44. | 3 | iphone 7 plus | 7000.000000000000000000000000000000 | 10 |
  45. | 4 | iphone x | 8000.000000000000000000000000000000 | 10 |
  46. +-----------+---------------+-------------------------------------+----------+
  47. 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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/39772.html

相关文章

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

    摘要:容器化容器化之多容器应用部署容器化部署引言上两节我们通过简单的学习了的基本操作。基于当前项目构建的容器服务,依赖于服务。最后,使用综合完成了容器化部署。参考资料容器化容器化之多容器应用部署 showImg(https://segmentfault.com/img/remote/1460000012801559); .NET Core容器化@Docker.NET Core容器化之多容器...

    jerry 评论0 收藏0
  • Nginx+Docker部署模式下 asp.net core 获取真实的客户端ip

    摘要:结论使用获取客户端不会自动取中的值需求单独处理。参考资料负载均衡的场景下如何获取客户端地址 [toc] 场景 线上环境使用Nginx(安装在宿主机)+Docker进行部署,应用获取客户端ip地址不正确,获取客户端IP的代码为Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4() 过程还原 搭建一个webapi示例环境 创建一...

    ermaoL 评论0 收藏0
  • Nginx+Docker部署模式下 asp.net core 获取真实的客户端ip

    摘要:结论使用获取客户端不会自动取中的值需求单独处理。参考资料负载均衡的场景下如何获取客户端地址 [toc] 场景 线上环境使用Nginx(安装在宿主机)+Docker进行部署,应用获取客户端ip地址不正确,获取客户端IP的代码为Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4() 过程还原 搭建一个webapi示例环境 创建一...

    Kyxy 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<