(二)搭建dotNetCore项目发布到k8s
阅读之前请先参考博客:发布dotNetCore程序到Kubernetes
流程主要为 创建项目->打包项目->发布项目, 其它的基本都不重要
手动操作验证:
项目为netCore 3.1版本
1.创建一个基本的netCoreApi 项目,能正常跑起来
2.项目右键-> 添加 -> Dockerfile 支持,自动生成Dockerfile 文件
3. Dockerfile 环境修改
mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1903 -> mcr.microsoft.com/dotnet/core/aspnet:3.1
mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 -> mcr.microsoft.com/dotnet/core/sdk:3.1
1 #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 3 #Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed. 4 #For more information, please see https://aka.ms/containercompat 5 6 FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base 7 WORKDIR /app 8 EXPOSE 80 9 10 FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build 11 WORKDIR /src 12 COPY ["k8s-netcore-demo.csproj", ""] 13 RUN dotnet restore "./k8s-netcore-demo.csproj" 14 COPY . . 15 WORKDIR "/src/." 16 #RUN dotnet build "k8s-netcore-demo.csproj" -c Release -o /app/build 17 18 FROM build AS publish 19 #RUN dotnet publish "k8s-netcore-demo.csproj" -c Release -o /app/publish 20 21 FROM base AS final 22 WORKDIR /app 23 #COPY --from=publish /app/publish . 24 ENTRYPOINT ["dotnet", "k8s-netcore-demo.dll"]
4.构建打包项目
准备工作:
4.1 先拉取3.1版本环境镜像,如果没有,后续打包会有各种问题
docker pull mcr.microsoft.com/dotnet/core/aspnet:3.1
docker pull mcr.microsoft.com/dotnet/core/sdk:3.1
4.2 打包项目
4.3 推送到k8s上面
先创建好yaml发布配置文件 deploy.yaml
1 apiVersion: apps/v1 2 kind: Deployment 3 metadata: 4 name: k8s-netcore-demo 5 namespace: k8s-netcore 6 labels: 7 k8s-app: k8s-netcore-demo 8 spec: 9 replicas: 1 10 selector: 11 matchLabels: 12 k8s-app: k8s-netcore-demo 13 template: 14 metadata: 15 labels: 16 k8s-app: k8s-netcore-demo 17 spec: 18 containers: 19 - name: k8s-netcore-demo 20 image: k8s-netcore-demo:v.202011291958 21 ports: 22 - containerPort: 80 23 --- 24 # ------------------- Service ------------------- # 25 kind: Service 26 apiVersion: v1 27 metadata: 28 labels: 29 k8s-app: k8s-netcore-demo 30 name: k8s-netcore-demo 31 namespace: k8s-netcore 32 spec: 33 type: NodePort 34 ports: 35 - port: 80 36 targetPort: 80 37 selector: 38 k8s-app: k8s-netcore-demo
推送到k8s
k8s面板可查看相关信息
最后就是访问项目
端口号可根据 kubectl get svc -n k8s-netcore 查看 CLUSTE-IP (4.3步操作)
常用命令:
1 #创建dotNetCore项目 2 dotnet new webApp -o k8s-netcore-demo --no-https 3 #将dotNetCore程序构建为镜像 4 docker build -t k8s-netcore-demo . 5 #启动代理 6 kubectl proxy 7 #创建namespace 8 kubectl create namespace k8s-netcore 9 #部署Kubernetes 10 kubectl create -f deploy.yaml --validate 11 #删除Kubernetes 12 kubectl delete -f deploy.yaml 13 #迭代Kubernetes 14 kubectl apply -f deploy.yaml --record 15 #查看指定命名空间的部署情况 16 kubectl get deploy -n k8s-netcore 17 #查看指定命名空间的资源情况 18 kubectl get svc -n k8s-netcore