我目前正在远程虚拟机上工作。 我通过 docker-compose.yml 文件设置了一个容器。 一切看起来都很好。我编写了一个脚本,在 Docker 启动时使用初始密码(除了管理员密码)为数据库设置一个用户。 我可以通过 MongoCompass 从本地桌面连接到数据库(使用“非管理员”用户的凭据),但我无法从 Docker 运行的 VW 直接连接到数据库。
也许你们中的一些人知道为什么。
docker-compose.yaml:
version: '3.6'
services:
mongo:
image: mongo:latest
restart: always
container_name: email-mongo
ports:
- 27017:27017
environment:
MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
MONGODB_DB: ${MONGODB_DB}
MONGODB_USER: ${MONGODB_USER}
MONGODB_PASSWORD: ${MONGODB_PASSWORD}
volumes:
- ./init.sh:/docker-entrypoint-initdb.d/init.sh:ro
.env :
MONGODB_DB=someDatabase
MONGODB_USER=someUsername
MONGODB_PASSWORD=someInitialPassword
init.sh:
set -e
mongosh <<EOF
use admin
db.createUser({
user: '$MONGODB_USER',
pwd: '$MONGODB_PASSWORD',
roles: [{
role: 'readWrite',
db: '$MONGODB_DB'
}]
})
EOF
Compass(本地 PC)的工作连接字符串:
mongodb://someUsername:someInitialPassword@vmaddress:27017/?authMechanism=DEFAULT&directConnection=true
python代码:
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
# MongoDB-Connectiondetails
mongo_host = "vmaddress"
mongo_port = 27017
mongo_username = "someUsername"
mongo_password = "someInitialPassword"
try:
# Create a MongoDB-Client
client = MongoClient(f"mongodb://{mongo_username}:{mongo_password}@{mongo_host}:27017/?authMechanism=DEFAULT&directConnection=true")
# Get List of DB
db_list = client.list_database_names()
print("MongoDB connection successfull.")
print("Datenbases on Server:", db_list)
except ConnectionFailure as e:
print("Connection to MongoDB failed:", e)
except Exception as e:
print("An Error occurred:", e)
执行python时出错:
Connection to MongoDB failed: vmaddress:27017: timed out (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 667d0c03c495fd3d26fab99c, topology_type: Single, servers: [<ServerDescription ('vmaddress', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('vmaddress:27017: timed out (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]>
docker 容器 ls:
6c834ed695a4 mongo:latest "docker-entrypoint.s…" 2 days ago Up 2 days 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp email-mongo
我没有任何想法。 也许我错过了一个打字错误或者我确实忘记了一些事情。 我希望你能帮忙, 最大
据我了解,您直接从虚拟机的终端运行 python 脚本,而不是在容器内运行。在这种情况下,请尝试使用 localhost 或 127.0.0.1 作为 mongo_host