[英]I can't connect to my MongoDB, which I run in docker compose
Here is my docker compose:这是我的码头工人:
version: "3.9"
services:
app:
container_name: app
build:
context: ./..
dockerfile: deployments/Dockerfile
env_file:
- ../configs/config.env
ports:
- ${APP_PORT:-8080}:8080
networks:
- network
restart: always
db:
image: mongo:latest
container_name: mongodb
restart: always
env_file:
- ../configs/config.env
ports:
- ${MONGODB_PORT:-27017}:27017
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGODB_ROOT_USER:-admin}
MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_ROOT_PASSWORD:-admin}
volumes:
- ../assets/mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
adminer:
image: adminer
container_name: db-adminer
restart: always
ports:
- ${ADMINER_PORT:-17860}:8080
networks:
- network
depends_on:
- db
networks:
network:
driver: bridge
Here is my mongo-init.sh file:这是我的 mongo-init.sh 文件:
use newdb
db.createUser(
{
user: admin,
pwd: admin,
roles: [
{
role: "readWrite",
db: "newdb"
}
]
}
);
Here I am trying to connect to the database, but I get the following error: topology is connected or connecting在这里我尝试连接到数据库,但出现以下错误:拓扑已连接或正在连接
client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%s",
cfg.DbUsername, cfg.DbPassword, cfg.DbHost, cfg.DbPort)))
I don't understand what the error might be, since everything is fine in the env file and all the variables match the authentication parameters in mongo我不明白错误可能是什么,因为 env 文件中一切正常,并且所有变量都与 mongo 中的身份验证参数匹配
check this out:看一下这个:
services:
productinfo:
container_name: product_cntnr
build: ./api-productinfo-service
image: arc1999/api-productinfo-service
ports:
- '8090:8090'
depends_on:
db:
condition: service_healthy
links:
- db
scraping:
build: ./api-scraping-service
image: arc1999/api-scraping-service
ports:
- '8080:8080'
depends_on:
db:
condition: service_healthy
links:
- db
db:
image: mongo:latest
container_name: mongo_db
# environment:
# MONGO_INITDB_ROOT_USERNAME: root
# MONGO_INITDB_ROOT_PASSWORD: rootpassword
ports:
- 27017:27017
volumes:
- mongodb_data_container:/data/db
healthcheck:
test: echo 'db.runCommand("ping").ok'
interval: 10s
timeout: 10s
retries: 5
volumes:
mongodb_data_container:
func InitDb() {
host := "mongodb://mongo_db:27017"
rb := bson.NewRegistryBuilder()
rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.M{}))
clientOptions := options.Client().ApplyURI(host).SetRegistry(rb.Build())
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Panicln(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Panicln(err)
}
db = client.Database(os.Getenv("MONGO_DB_NAME"))
fmt.Println("Connected to MongoDB!")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.