我想在本地 Kubernetes 上使用 MongoDB 部署一個 ASP.NET 應用程式。目前,該應用程式與docker-compose.
在 Kubernetes YAML 檔案的情況下,我StatefulSet為 MongoDB 創建了一個,為 ASP.NET 應用程式創建了一個部署,而且我還創建了他們受人尊敬的服務和 ConfigMap。我在下面附上了完整的代碼。
當我使用 Mongo-Express 部署時,甚至可以看到所有資料都加載到了 Mongo 資料庫中。所以,我確信 MongoDB StatefulSet 作業正常。現在唯一需要擔心的是 .NET 應用程式拋出了一個名為“資源暫時不可用”的例外。
關于問題:在執行 docker-compose up 時構建作業正常。但是在 Kubernetes 集群部署的情況下,它會拋出這個例外:
失敗:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]執行請求時發生未處理的例外。
System.TimeoutException:使用 CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } } 選擇服務器 30000 毫秒后發生超時。集群狀態的客戶端視圖是 { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/mongo: 27017“}”,端點:“未指定/mongo:27017”,ReasonChanged:“心跳”,狀態:“斷開連接”,ServerVersion:,TopologyVersion:,型別:“未知”,HeartbeatException:“MongoDB.Driver.MongoConnectionException:例外:打開與服務器的連接時發生。
System.Net.Internals.SocketExceptionFactory ExtendedSocketException (00000001, 11):資源暫時不可用
在 System.Net.Dns.InternalGetHostByName(String hostName)
在 System.Net.Dns.ResolveCallback(Object context)
--- 從先前拋出例外的位置結束堆疊跟蹤---
在 System.Runtime.ExceptionServices.ExceptionDispatchInfo。在 System.Net.Dns.<>c.b__25_1(IAsyncResult asyncResult) 的 System.Net.Dns.<>c.b__25_1(IAsyncResult asyncResult)在
System.Net.Dns.EndGetHostAddresses(IAsyncResult asyncResult)
的 System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)拋出(例外源) 。 Tasks.TaskFactory 2 endFunction, Action 1 promise, Boolean requiresSynchronization) --- 從先前拋出例外的位置結束堆疊跟蹤---1.FromAsyncCoreLogic(IAsyncResult iar, Func1 endAction, Task
在 MongoDB.Driver.Core.Connections.TcpStreamFactory.ResolveEndPointsAsync(EndPoint initial)
在 MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStreamAsync(EndPoint endPoint, CancellationToken cancelToken)
在 MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancelToken )
--- 內部例外堆疊跟蹤結束 ---
在 MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancelToken)
在 MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnectionAsync(CancellationToken cancelToken) 在 MongoDB.Driver.Core.Servers.ServerMonitor.HeartbeatAsync(CancellationToken cancelToken)”,LastHeartbeatTimestamp:“2022-06-26T16:04:05.7393346Z”,LastUpdateTimestamp : "2022-06-26T16:04:05.7393356Z" }] }. at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector 選擇器,ClusterDescription 描述) at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask (任務完成任務)在 MongoDB.Driver.Core.Clusters.Cluster 的 MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector 選擇器,ClusterDescription 描述,任務 descriptionChangedTask,TimeSpan 超時,CancellationToken cancelToken)。SelectServer(IServerSelector selector, CancellationToken cancelToken) at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelection(CancellationToken cancelToken) at MongoDB.Driver.MongoClient.AreSessionsSupported(CancellationToken cancelToken) at MongoDB.Driver.MongoClient.StartImplicitSession(CancellationToken cancelToken) at MongoDB.Driver.OperationExecutor .StartImplicitSession(CancellationToken cancelToken) 在 MongoDB.Driver.MongoCollectionImplMongoDB.Driver.MongoCollectionImpl 處的 StartImplicitSession(CancellationToken cancelToken)MongoDB.Driver.MongoCollectionImpl 處的 StartImplicitSession(CancellationToken cancelToken)1.UsingImplicitSession[TResult](FuncMongoDB.Driver.MongoCollectionImpl 上的 2 func,CancellationToken cancelToken)1.FindSync[TProjection](FilterDefinition1 過濾器,2 options, CancellationToken cancellationToken) at MongoDB.Driver.FindFluentMongoDB.Driver.IAsyncCursorSourceExtensions.FirstOrDefault[TDocument](IAsyncCursorSource 上的 FindOptions 2.ToCursor(CancellationToken cancelToken)1 source, CancellationToken cancellationToken) at MongoDB.Driver.IFindFluentExtensions.FirstOrDefault[TDocument,TProjection](IFindFluent2 在 Microsoft.Extensions.Internal.ObjectMethodExecutor 的 /src/HostSimNetwork/Controllers/ConcordController.cs:第 48 行的 lambda_method(Closure, Object, Object[]) 中的 HostSimNetwork.Controllers.ConcordController.Index() 中找到 CancellationToken cancelToken)。在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker 的 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 執行器,物件控制器,Object[] 引數)中執行(物件目標,物件 [] 引數)。 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker 的 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 的 InvokeActionMethodAsync()。InvokeNextActionFilterAsync() --- 從先前引發例外的位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&接下來,Scope& 范圍,Object& 狀態,Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- 堆疊跟蹤從上一個引發例外的位置結束---在 Microsoft.AspNetCore.Mvc.Infrastructure .ResourceInvoker.g__Awaited|24_0(ResourceInvoker 呼叫程式,Task lastTask,State next,Scope 范圍,Object state,Boolean isCompleted)在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) 在 Microsoft.AspNetCore.Mvc。Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- 堆疊跟蹤從上一個引發例外的位置結束---在Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端點端點,任務 requestTask,ILogger 記錄器)在 Microsoft.AspNetCore 的 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)。 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 背景關系)的 Authorization.AuthorizationMiddleware.Invoke(HttpContext 背景關系)Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- 從先前引發例外的位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)在 Microsoft .AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- 從先前引發例外的位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)在 Microsoft .AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 的 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) 的 AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 的 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) 的 AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
YAML 檔案:
apiVersion: v1
kind: ConfigMap
metadata:
name: mongodb-configmap
data:
database_url: mongodb-service
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb-statefulset
spec:
serviceName: "mongodb-service"
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
value: "admin"
- name: MONGO_INITDB_ROOT_PASSWORD
value: "password"
volumeMounts:
- name: mongo-initdb
mountPath: /docker-entrypoint-initdb.d
restartPolicy: Always
volumes:
- name: mongo-initdb
configMap:
name: mongo-initdb
---
apiVersion: v1
kind: Service
metadata:
name: mongodb-service
spec:
clusterIP: None
selector:
app: mongodb
ports:
- port: 27017
targetPort: 27017
protocol: TCP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: networksim
labels:
app: networksim
spec:
replicas: 1
selector:
matchLabels:
app: networksim
template:
metadata:
labels:
app: networksim
spec:
containers:
- name: networksim-web
image: srideepkar/sim:lotus
ports:
- containerPort: 80
- containerPort: 8085
env:
- name: ConnectionStrings__MongoDB
value: "mongodb://admin:password@mongo:27017"
- name: MongoDbSettings__User
value: "admin"
- name: MongoDbSettings__Password
value: "password"
- name: MongoDbSettings__Host
valueFrom:
configMapKeyRef:
name: mongodb-configmap
key: database_url
---
apiVersion: v1
kind: Service
metadata:
name: networksim-service
spec:
selector:
app: networksim
type: LoadBalancer
ports:
- port: 5000
targetPort: 80
protocol: TCP
name: port2
- port: 8085
targetPort: 8085
protocol: TCP
name: port3
AppSetting.JSON 檔案
{
"ConnectionStrings": {
"MongoDB": "mongodb://mongo:27017",
"DatabaseName": "NetworkSim",
"CardtypesCollectionName": "cardtypes"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"MongoDbSettings":{
"Host": "localhost",
"Port": "27017",
"User": "admin"
}
}
Docker-Compose 檔案供參考:
version: '3.8'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
volumes:
- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
depends_on:
- mongo
web:
build: .
ports:
- 5000:80
- 8085:8085
uj5u.com熱心網友回復:
很確定您需要更改 mongo db 連接字串的名稱。查看服務的 DNS 部分:https ://kubernetes.io/docs/concepts/services-networking/dns-pod-service/
在您的情況下,mongodb-service.default.svc.cluster.local如果您已將所有內容部署到默認命名空間中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496129.html
標籤:C# 网 mongodb 码头工人 Kubernetes
