某些业务场景中我们需要从Docker内部连接宿主机上运行的MongoDB数据库,这时就需要使用一个特殊的host名来进行连接,即 host.docker.internal

host.docker.internal 是一个特殊的主机名,它可以用来访问运行Docker容器的主机的本地网络资源。

package db

import (
	"context"
	"time"

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

func NewClient() (*mongo.Client, error) {

	ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)

	credential := options.Credential{
		AuthSource: "admin",
		Username:   "数据库用户名",
		Password:   "数据库密码",
	}
	clientOpts := options.Client().ApplyURI("host.docker.internal:27017").SetAuth(credential)
	client, err := mongo.Connect(ctx, clientOpts)

	return client, err
}

Docker容器官方LOGO