[英]MongoDB ignores authentication when called from inside Kubernetes cluster but not from outside
I have set up in my k8s cluster a MongoDB database with the following configuration:我在我的 k8s 集群中设置了一个 MongoDB 数据库,配置如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongodb-deployment
labels:
app: mongodb
spec:
replicas: 1
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: db-secret
key: mongo-root-username
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: mongo-root-password
---
apiVersion: v1
kind: Service
metadata:
name: mongodb-service
spec:
selector:
app: mongodb
type: LoadBalancer
ports:
- protocol: TCP
port: 27020
targetPort: 27017
nodePort: 30010
(the type of my service is LoadBalancer so that I can debug it from outside my cluster). (我的服务类型是 LoadBalancer,以便我可以从集群外部调试它)。
I have a Node.js app inside the k8s cluster (same namespace) which executes the following code:我在 k8s 集群(相同命名空间)中有一个 Node.js 应用程序,它执行以下代码:
mongoose.connect(
`mongodb://${process.env.MONGODB_USERNAME}:${process.env.PASSWORD}@mongodb-service:27020`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
connectTimeoutMS: 1000,
},
(err) => {
console.log(err);
}
);
When I try authenticating with the previous code, mongoose fails to connect and console.log(err)
prints an AuthenticationFailed MongoError.当我尝试使用前面的代码进行身份验证时,猫鼬无法连接并且
console.log(err)
打印 AuthenticationFailed MongoError。 If however I remove the credentials from the connection string, mongoose manages to connect to the database (which it shouldn't as I have specified credentials as environment variables in my deployment).但是,如果我从连接字符串中删除凭据,mongoose 会设法连接到数据库(这不应该,因为我在部署中已将凭据指定为环境变量)。
The weirdest part is that if I now try connecting using MongoDBCompass on my machine, it's the opposite (or actually it's the expected behavior): the database refuses the connection without credentials but accepts it with the credentials in the connection string.最奇怪的部分是,如果我现在尝试在我的机器上使用 MongoDBCompass 进行连接,则情况正好相反(或者实际上这是预期的行为):数据库拒绝没有凭据的连接,但使用连接字符串中的凭据接受它。
Finally, it didn't have anything to do with Kubernetes.最后,它与 Kubernetes 没有任何关系。 Adding
?authSource=admin
at the end of the connection string solved my problem.在连接字符串的末尾添加
?authSource=admin
解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.