How to connect MongoDB , golang in Kubernetes

huangapple go评论83阅读模式
英文:

How to connect MongoDB , golang in Kubernetes

问题

数据库和服务器未连接。
尝试在Kubernetes环境中部署。

这是关于MongoDB和Golang HTTP服务器的部署和服务的代码:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  labels:
    app: backend
spec:
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
    spec:
      containers:
      - image: royroyee/backend:0.8
        name: backend
        ports:
        - containerPort: 9001

---
apiVersion: v1
kind: Service
metadata:
  name: backend-service
  labels:
    run: backend-service
spec:
  ports:
    - port: 9001
      targetPort: 9001
      protocol: TCP
  selector:
    app: backend
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  selector:
    matchLabels:
      app: mongo
  template:
    metadata:
      labels:
        app: mongo
    spec:
      containers:
      - image: mongo
        name: mongo-db
        ports:
        - containerPort: 27017
---
apiVersion: v1
kind: Service
metadata:
  name: mongo-service
  labels:
    run: mongo-service
spec:
  ports:
    - port: 27017
      targetPort: 27017
      protocol: TCP
  selector:
    app: mongo

这是我的Golang代码中关于MongoDB会话的部分:

func getSession() *mgo.Session {
	s, err := mgo.Dial("mongodb://mongo-service:27017/mongo-db")

请告诉我你的问题是什么。

另外,我尝试了以下几种连接方式:

  • mongodb://mongo-service:27017/backend
  • mongodb://mongo-service:27017/mongo-db
  • mongodb://mongo-service:27017
英文:

The database and the server are not connected.
Attempting to deploy in Kubernetes environment.

this is deployment, sevice of mongodb , golang http server

apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  labels:
    app: backend
spec:
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
    spec:
      containers:
      - image: royroyee/backend:0.8
        name: backend
        ports:
        - containerPort: 9001

---
apiVersion: v1
kind: Service
metadata:
  name: backend-service
  labels:
    run: backend-service
spec:
  ports:
    - port: 9001
      targetPort: 9001
      protocol: TCP
  selector:
    app: backend
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  selector:
    matchLabels:
      app: mongo
  template:
    metadata:
      labels:
        app: mongo
    spec:
      containers:
      - image: mongo
        name: mongo-db
        ports:
        - containerPort: 27017
---
apiVersion: v1
kind: Service
metadata:
  name: mongo-service
  labels:
    run: mongo-service
spec:
  ports:
    - port: 27017
      targetPort: 27017
      protocol: TCP
  selector:
    app: mongo

and my golang code ...
mongodb session

func getSession() *mgo.Session {
	s, err := mgo.Dial("mongodb://mongo-service:27017/mongo-db")

pls let me know ..

also I tried something like this.

// mongodb://mongo-service:27017/backend
// mongodb://mongo-service:27017/mongo-db
// mongodb://mongo-service:27017

答案1

得分: 1

要在Kubernetes环境中使用Golang连接MongoDB,您需要按照以下步骤进行操作:

  1. 在Kubernetes集群中部署MongoDB,可以选择使用statefulset或deployment。

  2. 为MongoDB创建一个Service,以便从您的Golang应用程序访问已部署的pods。

  3. 在您的Golang应用程序中,使用官方的MongoDB Go驱动程序通过指定服务名称和端口来建立与MongoDB服务的连接。

  4. 运行一个简单的测试来验证连接,测试可以插入和检索MongoDB数据库中的数据。

  5. 最后,将Golang应用程序打包为Docker镜像,并在同一Kubernetes集群中部署为deployment。

以下是一个连接MongoDB的示例Go代码:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	// 设置客户端选项
	clientOptions := options.Client().ApplyURI("mongodb://mongodb-service:27017")

	// 连接MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connected to MongoDB!")
}

以下是一个将MongoDB部署为StatefulSet和将Go应用程序部署为Deployment的示例YAML文件:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongodb
spec:
  serviceName: mongodb-service
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
        - name: mongodb
          image: mongo:4.4
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: mongodb-data
              mountPath: /data/db
  volumeClaimTemplates:
    - metadata:
      name: mongodb-data
      annotations:
        volume.beta.kubernetes.io/storage-class: standard
      spec:
        accessModes: [ "ReadWriteOnce" ]
        resources:
          requests:
            storage: 1Gi

---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  selector:
    app: mongodb
  ports:
    - name: mongodb
      port: 27017
      targetPort: 27017
  clusterIP: None

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-app
  template:
    metadata:
      labels:
        app: go-app
    spec:
      containers:
        - name: go-app
          image: <your-go-app-image>
          ports:
            - containerPort: 8080

注意:您需要将your-go-app-image替换为实际的Go应用程序的Docker镜像。

英文:

To connect MongoDB with Golang in a Kubernetes environment, you need to follow these steps:

Deploy MongoDB as a statefulset or a deployment in your Kubernetes cluster.

Create a Service for MongoDB to access the deployed pods from your Golang application.

In your Golang application, use the official MongoDB Go driver to establish a connection to the MongoDB service by specifying the service name and port.

Verify the connection by running a simple test that inserts and retrieves data from the MongoDB database.

Finally, package the Golang application as a Docker image and deploy it as a deployment in the same Kubernetes cluster.

Here is a sample Go code to connect to MongoDB:

package main

import (
	&quot;context&quot;
	&quot;fmt&quot;
	&quot;log&quot;

	&quot;go.mongodb.org/mongo-driver/mongo&quot;
	&quot;go.mongodb.org/mongo-driver/mongo/options&quot;
)

func main() {
	// Set client options
	clientOptions := options.Client().ApplyURI(&quot;mongodb://mongodb-service:27017&quot;)

	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// Check the connection
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(&quot;Connected to MongoDB!&quot;)
}

Here's a sample YAML file for deploying MongoDB as a StatefulSet and a Go application as a Deployment:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongodb
spec:
  serviceName: mongodb-service
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
        - name: mongodb
          image: mongo:4.4
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: mongodb-data
              mountPath: /data/db
  volumeClaimTemplates:
    - metadata:
      name: mongodb-data
      annotations:
        volume.beta.kubernetes.io/storage-class: standard
      spec:
        accessModes: [ &quot;ReadWriteOnce&quot; ]
        resources:
          requests:
            storage: 1Gi

---
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
spec:
  selector:
    app: mongodb
  ports:
    - name: mongodb
      port: 27017
      targetPort: 27017
  clusterIP: None

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-app
  template:
    metadata:
      labels:
        app: go-app
    spec:
      containers:
        - name: go-app
          image: &lt;your-go-app-image&gt;
          ports:
            - containerPort: 8080

Note: You will need to replace your-go-app-image with the actual Docker image of your Go application.

huangapple
  • 本文由 发表于 2023年1月31日 16:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75294389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定