百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

将.NET Core 微服务和 Kubernetes 、 NGINX、Docker进行部署集成

off999 2025-01-04 22:24 17 浏览 0 评论


概述:在本文中,我们将讨论 Ingress 的基础知识和用例。此外,借助 .NET Core 8 Web API、Docker、Kubernetes 和 Ingress 逐步实现和配置不同的服务。议程·什么是 NGINX Ingress?·NGINX Ingress 的用例·使用 .NET Core 8 Web API 实现服务·服务容器化和 NGINX 入口配置。先决条件·Visual Studio 2022· .NET Core 8 SDK·Docker 和 Kubernetes什么是 NGINX Ingress?·简单来说,Nginx Ingress 是一种管理传入 Web 应用程序或服务的互

在本文中,我们将讨论 Ingress 的基础知识和用例。此外,借助 .NET Core 8 Web API、Docker、Kubernetes 和 Ingress 逐步实现和配置不同的服务。

议程

·什么是 NGINX Ingress?

·NGINX Ingress 的用例

·使用 .NET Core 8 Web API 实现服务

·服务容器化和 NGINX 入口配置。

先决条件

·Visual Studio 2022

· .NET Core 8 SDK

·Docker 和 Kubernetes

什么是 NGINX Ingress?

·简单来说,Nginx Ingress 是一种管理传入 Web 应用程序或服务的互联网流量的方法。把它想象成你的网络服务器的交通警察。它位于应用程序的前面并引导流量,就像 Web 请求的路由器一样。

·Nginx Ingress 会检查传入的请求,并根据您定义的规则决定将请求发送到何处。这可能意味着根据请求的 URL 或其他条件将请求定向到不同的服务。它还可以处理负载平衡、SSL 终止(解密 HTTPS 流量)以及与管理传入 Web 流量相关的其他任务。

·总体而言,Nginx Ingress 可帮助您高效地管理 Web 流量并将其路由到您的应用程序,从而提高性能、安全性和可扩展性。

NGINX Ingress 的用例

以下是 Ingress 的一些用例

负载平衡:将传入的 Web 流量均匀分布在多个服务器上,以防止过载并确保更好的性能。

路由:根据 URL 或域名等因素将 Web 请求定向到应用程序的不同部分。

SSL 终止:集中管理 HTTPS 加密和解密,以保护 Web 流量,而不会给单个服务器带来负担。

虚拟主机:在同一台服务器上托管多个网站或应用程序,每个网站或应用程序都有自己的域名。

身份验证和授权:在请求到达服务器之前,根据用户凭据或权限控制对应用程序的访问。

速率限制:限制来自单个客户端或 IP 地址的请求数量,以防止滥用或过度使用服务。

**Web 应用防火墙 (WAF):**根据预定义的安全规则检查和过滤传入流量,保护应用免受常见的 Web 安全威胁。

使用 .NET Core 8 Web API 实现服务

产品服务

步骤1:

创建新的 Product 类。

Bash
namespace ProductAPI.Models  
{  
    public class Product  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public decimal Price { get; set; }  
    }  
}

步骤2:

添加具有不同终结点的新产品控制器。

Bash
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProductAPI.Models;

namespace ProductAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        private static List<Product> _products = new List<Product>
        {
            new Product { Id = 1, Name = "Product 1", Price = 10.99m },
            new Product { Id = 2, Name = "Product 2", Price = 20.49m }
        };

        private readonly ILogger<ProductsController> _logger;

        public ProductsController(ILogger<ProductsController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return _products;
        }

        [HttpGet("{id}")]
        public ActionResult<Product> Get(int id)
        {
            var product = _products.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return product;
        }

        [HttpPost]
        public ActionResult<Product> Post(Product product)
        {
            product.Id = _products.Count + 1;
            _products.Add(product);
            return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
        }

        [HttpPut("{id}")]
        public IActionResult Put(int id, Product product)
        {
            var existingProduct = _products.FirstOrDefault(p => p.Id == id);
            if (existingProduct == null)
            {
                return NotFound();
            }
            existingProduct.Name = product.Name;
            existingProduct.Price = product.Price;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var product = _products.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            _products.Remove(product);
            return NoContent();
        }
    }
}

步骤3:

在程序类中注册服务和中间件。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

用户服务

步骤1:

创建新的 User 类。

namespace UserAPI.Models  
{  
    public class User  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public string Email { get; set; }  
    }  
}

步骤2:

添加具有不同终结点的新用户控制器。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using UserAPI.Models;

namespace UserAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private static List<User> _users = new List<User>
        {
            new User { Id = 1, Name = "User 1", Email = "user1@example.com" },
            new User { Id = 2, Name = "User 2", Email = "user2@example.com" }
        };

        private readonly ILogger<UsersController> _logger;

        public UsersController(ILogger<UsersController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<User> Get()
        {
            return _users;
        }

        [HttpGet("{id}")]
        public ActionResult<User> Get(int id)
        {
            var user = _users.FirstOrDefault(u => u.Id == id);
            if (user == null)
            {
                return NotFound();
            }
            return user;
        }

        [HttpPost]
        public ActionResult<User> Post(User user)
        {
            user.Id = _users.Count + 1;
            _users.Add(user);
            return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
        }

        [HttpPut("{id}")]
        public IActionResult Put(int id, User user)
        {
            var existingUser = _users.FirstOrDefault(u => u.Id == id);
            if (existingUser == null)
            {
                return NotFound();
            }
            existingUser.Name = user.Name;
            existingUser.Email = user.Email;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var user = _users.FirstOrDefault(u => u.Id == id);
            if (user == null)
            {
                return NotFound();
            }
            _users.Remove(user);
            return NoContent();
        }
    }
}

步骤3:

在程序类中注册服务和中间件。

var builder = WebApplication.CreateBuilder(args);  
  
// Add services to the container.  
  
builder.Services.AddControllers();  
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  
builder.Services.AddEndpointsApiExplorer();  
builder.Services.AddSwaggerGen();  
  
var app = builder.Build();  
  
// Configure the HTTP request pipeline.  
app.UseSwagger();  
app.UseSwaggerUI();  
  
app.UseHttpsRedirection();  
  
app.UseAuthorization();  
  
app.MapControllers();  
  
app.Run();

业务容器化和 NGINX 入口配置

步骤1:

为产品和用户服务添加 docker 映像。

产品服务

# Use the official .NET Core SDK as a parent image
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app

# Copy the project file and restore any dependencies (use .csproj for the project name)
COPY *.csproj ./
RUN dotnet restore

# Copy the rest of the application code
COPY . .

# Publish the application
RUN dotnet publish -c Release -o out

# Build the runtime image
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/out ./

# Expose the port your application will run on
EXPOSE 80

# Start the application
ENTRYPOINT ["dotnet", "ProductAPI.dll"]

用户服务

# Use the official .NET Core SDK as a parent image
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app

# Copy the project file and restore any dependencies (use .csproj for the project name)
COPY *.csproj ./
RUN dotnet restore

# Copy the rest of the application code
COPY . .

# Publish the application
RUN dotnet publish -c Release -o out

# Build the runtime image
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/out ./

# Expose the port your application will run on
EXPOSE 80

# Start the application
ENTRYPOINT ["dotnet", "UserAPI.dll"]

步骤2:

构建 Docker 镜像。

docker build -t product-api 中。

docker build -t user-api 中。

步骤3:

为 Kubernetes 创建部署、服务和入口 YAML 文件。

部署

apiVersion: apps/v1
kind: Deployment
metadata:
  name: product-app-deployment  # Name of the deployment
spec:
  selector:
    matchLabels:
      app: product-app  # Label selector to match pods controlled by this deployment
  template:
    metadata:
      labels:
        app: product-app  # Labels applied to pods created by this deployment
    spec:
      containers:
        - name: product-app  # Name of the container
          image: product-api:latest  # Docker image to use
          imagePullPolicy: Never
          ports:
          - containerPort: 80  # Port to expose within the pod
apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-app-deployment  # Name of the deployment
spec:
  selector:
    matchLabels:
      app: user-app  # Label selector to match pods controlled by this deployment
  template:
    metadata:
      labels:
        app: user-app  # Labels applied to pods created by this deployment
    spec:
      containers:
        - name: user-app  # Name of the container
          image: user-api:latest  # Docker image to use
          imagePullPolicy: Never
          ports:
          - containerPort: 80  # Port to expose within the pod

服务业

apiVersion: v1
kind: Service
metadata:
  name: product-app-service  # Name of the service
spec:
  selector:
    app: product-app  # Label selector to target pods with this label
  ports:
    - protocol: TCP
      port: 8081
      targetPort: 8080
  type: NodePort  # Type of service (other options include ClusterIP, LoadBalancer, etc.)
apiVersion: v1
kind: Service
metadata:
  name: user-app-service  # Name of the service
spec:
  selector:
    app: user-app  # Label selector to target pods with this label
  ports:
    - protocol: TCP
      port: 8082
      targetPort: 8080
  type: NodePort  # Type of service (other options include ClusterIP, LoadBalancer, etc.)

入口

首先,您需要在 Kubernetes 集群上安装 Ingress。

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: demo-ingress
spec:
  ingressClassName: nginx
  rules:
  - host: ingress.demo.com
    http:
      paths:
      - path: /products
        pathType: Prefix
        backend:
          service:
            name: product-app-service
            port:
              number: 8081
      - path: /users
        pathType: Prefix
        backend:
          service:
            name: user-app-service
            port:
              number: 8082

接下来,创建一个具有不同规则的入口文件

此 YAML 文件设置规则,用于将流向特定域 (ingress.demo.com) 的 Web 流量定向到 Kubernetes 集群中的不同服务。

·当有人转到 ingress.demo.com/products 时,他们的请求会转到在端口 8081 上运行的名为 product-app-service 的服务。

·当有人访问 ingress.demo.com/users 时,他们的请求会转到在端口 8082 上运行的名为 user-app-service 的服务。

此配置由 Ingress 资源使用 NGINX Ingress 控制器进行管理。这是一种在 Kubernetes 中管理对服务的外部访问的方法。

步骤4:

在位于 /etc/host 下的主机文件中使用 IP 配置 Ingress 主机

注意:每个提供程序的主机文件路径都不同。在这里,我将 Kubernetes 与 Docker Desktop 一起使用。因此,文件路径为 C:\Windows\System32\drivers\etc

步骤5:

将 YAML 文件应用于 Kubernetes 集群。

步骤6:

您可以在入口主机的帮助下访问不同的终端节点,并且根据请求 URL,入口会将您的请求传递到特定服务。

在本文中,我们学习了 ingress 的基础知识及其用例。此外,在 Docker 和 Kubernetes 的帮助下逐步实现服务和容器化。此外,使用 Kubernetes 集群进行入口安装和配置。

相关推荐

用 Pandera 高效验证和清洗 Pandas 数据集——实用分步指南

当我们处理数据时,确保数据不脏、不无效非常重要——比如检查空值、缺失值,或某列类型不允许的数字。这些检查至关重要,因为劣质数据会导致错误分析、模型失败,并浪费大量时间和资源。你可能已经用传统的Pan...

【项目实践】利用Pandas进行数据读取、清洗和分析的全方位指南

目录一、数据读取和写入1.1CSV和txt文件:1.2Excel文件:1.3MYSQL数据库:二、数据清洗2.1清除不需要的行数据2.2清除不需要的列2.3调整列的展示顺序或列标签名2.4...

不用VBA!用Excel自带Python秒杀数据清洗,效率怒涨10倍!

还在为Excel函数不够用发愁?其实微软早偷偷内置了Python引擎!无需安装插件,直接调用pandas/numpy处理百万级数据,职场人最后的救命神器!一、为什么Excel+Python是王炸组合?...

Python 数据清洗中不得不说的事!(用python清洗数据)

在Python中无论爬虫也好,数据分析也好,首先需要数据清洗,Python中有许多库可以帮助我们轻松搞定!正则表达式(RegularExpression)正则表达式是一种强大的字符串匹配工具,可...

数据分析——清洗数据(数据清洗思路)

数据分析中清洗数据是确保数据质量和可靠性的关键步骤,通常包括以下方法步骤:1.数据评估与理解目标:了解数据的基本情况,明确清洗方向。检查数据概况:查看字段名、数据类型、样本分布、缺失值比例等。统计描...

面对复杂数据,Pandas 如何助力数据清洗工作?

在数据分析和机器学习领域,数据清洗是至关重要的前置环节。高质量的数据是得出准确分析结论和构建有效模型的基石,而原始数据往往包含缺失值、重复值、异常值以及错误的数据格式等问题。Pandas作为Pyt...

Python 的 enumerate 函数:遍历中的索引神器

对话实录小白:(苦恼)我在遍历列表时,想知道每个元素的位置,只能用个计数器变量,好繁琐,有没有更简单的办法?专家:(掏出法宝)用enumerate函数,遍历同时获取索引,轻松解决你的困扰!enumer...

python zip函数可以实现同时遍历多列表,以及矩阵转置等

zip函数是Python的内置函数,用于将多个可迭代对象中对应位置的元素打包成元组,并返回一个由这些元组组成的迭代器。概念看不懂没关系,我们来举个简单例子。比如有两个列表x=["a"...

Python快速入门教程7:循环语句(python循环语句怎么用)

一、循环语句简介循环语句用于重复执行一段代码块,直到满足特定条件为止。Python支持两种主要的循环结构:for循环和while循环。二、for循环基本语法for循环用于遍历序列(如列表、元组、字符串...

使用Python 获取多级字典(Json)格式所有Key、Value

在编程数据处理时,经常能碰到多级包含多类型的字典,例如下图:客户要求取到所有根部key,value并写入DataFrame中,下面用我的方法来实现:#新建存放key,value的数组data=[...

Python列表创建操作与遍历指南(列表的创建python)

Python列表全方位解析:创建、操作、删除与遍历的全面指南列表(List)是Python中最灵活且常用的数据结构之一,支持动态增删元素、混合数据类型存储以及高效的遍历操作。以下从创建、操作、...

python入门到脱坑 结构语句—— 循环语句while 循环

以下是Python中while循环的详细入门讲解,包含基础语法、控制方法和实用技巧:一、while循环基础1.基本语法while条件:#条件为True时重复执行的代码#.....

全网最详尽的Python遍历的高级用法,程序员必收藏!

1.内置函数的高阶用法。numbers=[1,2,3,4]squared=list(map(lambdax:x**2,numbers))#[1,4,9,16]```-*...

在Python中遍历列表的方法有哪些(python遍历怎么写)

Python中遍历列表有以下几种方法:一、for循环遍历lists=["m1",1900,"m2",2000]foriteminlists:print(item)lists=...

99% 教程不会讲的技巧,Python 字典推导式终极指南,小白也能秒懂

字典推导式详解:从基础到进阶1.什么是字典推导式?字典推导式是Python中创建字典的一种高效语法,它允许你在一行代码内完成循环、条件判断和字典构建。为什么需要字典推导式?传统方法创建字典需要多...

取消回复欢迎 发表评论: