如何通过Shell脚本在Podman容器内执行mongosh命令?
在Podman容器中通过Shell脚本执行mongosh命令的方案
1. 执行单条命令(如show dbs;)
你当前用podman exec -it是交互式模式,脚本里不需要终端交互,去掉-t参数后,配合mongosh的--eval参数就能直接执行语句:
podman exec my-app-mongo mongosh --eval "show dbs;"
或者通过管道传递命令(用-i保持标准输入):
echo "show dbs;" | podman exec -i my-app-mongo mongosh
2. 自动化创建并配置测试表
如果要执行多条命令完成初始化,推荐以下两种方式:
方式一:通过JS脚本文件执行
- 编写MongoDB初始化脚本(比如
init-test-db.js):
// 切换到目标数据库 use test_db; // 创建测试表 db.createCollection("user_test"); // 插入测试数据 db.user_test.insertMany([ {username: "test_user1", email: "test1@example.com"}, {username: "test_user2", email: "test2@example.com"} ]); // 验证表创建结果 db.user_test.find();
- 在Shell脚本中把文件传到容器并执行:
# 复制脚本到容器内 podman cp init-test-db.js my-app-mongo:/tmp/ # 执行脚本 podman exec my-app-mongo mongosh /tmp/init-test-db.js
方式二:通过Here-doc直接传递命令
不需要额外文件,直接在Shell脚本中嵌入多条MongoDB命令:
podman exec -i my-app-mongo mongosh <<EOF use test_db; db.createCollection("product_test"); db.product_test.insertOne({name: "test_product", price: 99.9}); db.product_test.find(); EOF
注意事项
- 如果MongoDB开启了认证,需要在mongosh命令中添加用户名和密码参数,比如:
podman exec my-app-mongo mongosh -u admin -p your_password --eval "show dbs;"
- 确保容器
my-app-mongo处于运行状态,否则podman exec会失败。
内容的提问来源于stack exchange,提问作者dafna
相关产品推荐
相关产品推荐

