简体   繁体   English

通过bash文件中的SSH通过SSH输入文本

[英]Entering text into a docker container via ssh from bash file

What I am trying to do is setup a local development database and to prevent everyone having to go through all the steps I thought it would be useful to create a script. 我要做的是建立一个本地开发数据库,​​以防止每个人都要经历所有我认为对创建脚本有用的步骤。

What I have below stop once it is in the terminal, which looks like: 一旦进入终端,我下面的内容就会停止:

output 输出

./dbSetup.sh 
hash of container 0d1b182aa6f1
/ #

At which point I have to manually enter exit . 在这一点上,我必须手动输入exit

script 脚本

#!/bin/bash
command=$(docker ps | grep personal)
set $command
echo "hash of container ${1}"
docker exec -it ${1} sh

Is there a way I can inject a command via a script into a dockers container terminal? 有什么方法可以通过脚本将命令注入dockers容器终端吗?

In order to execute command inside a container, you can use something like this: 为了在容器内执行命令,您可以使用如下代码:

docker exec -ti my_container sh -c "echo a && echo b"

More information available at: https://docs.docker.com/engine/reference/commandline/exec/ 有关更多信息,请访问: https//docs.docker.com/engine/reference/commandline/exec/

Your script finds a running Docker container and opens a shell to it. 您的脚本会找到一个正在运行的Docker容器并为其打开一个外壳。 The "-it" makes it interactive and allocates a tty which is why it continues to wait for input, eg "exit". “ -it”使其具有交互性并分配一个tty,这就是为什么它继续等待输入的原因,例如“ exit”。 If the plan is to execute some commands to initialize a local development database, I'd recommend looking at building an image with a Dockerfile instead. 如果计划执行一些命令来初始化本地开发数据库,​​则建议改用Dockerfile构建映像。 ie Once you figure out the commands to run, they would become RUN commands and the container after docker run would expose a local development database. 即,一旦您确定要运行的命令,它们将成为RUN命令,并且在docker run之后的容器将公开本地开发数据库。

If you really want some commands to run within the shell after it is started and maintain the session, depending on the base image, you might be able to mount a bash profile that has the required commands, eg -v db_profile:/etc/profile.d where db_profile is a folder with the shell scripts you want to run. 如果您确实希望启动外壳后在外壳中运行某些命令并维护会话(取决于基础映像),则可以挂载具有所需命令的bash配置文件,例如-v db_profile:/ etc / profile .d,其中db_profile是包含要运行的Shell脚本的文件夹。 To get them to run you'd exec sh -l to have the login startup scripts to run. 要使它们运行,您可以执行sh -l使登录启动脚本运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM