简体   繁体   English

Bash - 连接到 Docker 容器并在 redis-cli 中执行命令

[英]Bash - Connect to Docker container and execute commands in redis-cli

I'm trying to create a simple script which would:我正在尝试创建一个简单的脚本:

  1. Connect to docker container's BASH shell连接到 docker 容器的 BASH shell
  2. Go into redis-cli Go 进入redis-cli
  3. Perform a flushall command in redis-cli在 redis-cli 中执行flushall命令

So far, I have this in my docker_script.sh (this basically copies the manual procedure):到目前为止,我的docker_script.sh中有这个(这基本上复制了手动过程):

docker exec -it redis /bin/bash
redis-cli
flushall

However, when I run it, it only connects to the container's BASH shell and doesn't do anything else.但是,当我运行它时,它只连接到容器的 BASH shell 并且不做任何其他事情。 Then, if I type exit into the container's BASH shell, it outputs this:然后,如果我在容器的 BASH shell 中键入exit ,它会输出:

root@5ce358657ee4:/data# exit
exit
./docker_script.sh: line 2: redis-cli: command not found
./docker_script.sh: line 3: keys: command not found

Why is the command not found if commands redis-cli and flushall exist and are working in the container when I perform the same procedure manually?当我手动执行相同的过程时,如果命令redis-cliflushall存在并且正在容器中工作,为什么command not found命令? How do I "automate" it by creating such a small BASH script?我如何通过创建这么小的 BASH 脚本来“自动化”它?

Thank you谢谢

The above proposed solution with auth still got me an error上面提出的带有 auth 的解决方案仍然给我一个错误

(error) NOAUTH Authentication required

This worked for me:这对我有用:

docker exec -it redis /bin/sh -c 'redis-cli -a MYPASSWORD FLUSHALL'

Seems like you're trying to run /bin/bash inside the redis container, while the redis-cli and flushall commands are scheduled after in your current shell instance.似乎您正在尝试在 redis 容器内运行/bin/bash ,而redis-cliflushall命令则在您当前的 shell 实例中安排在之后。 Try passing in your redis-cli command to bash like this:尝试像这样传入你的redis-cli命令来 bash:

docker exec -it redis /bin/bash -c "redis-cli FLUSHALL"

The -c is used to tell bash to read a command from a string. -c用于告诉 bash 从字符串中读取命令。

Excerpt from the man page:摘自man页:

-c string If the -c option is present, then commands are read from
                 string.   If  there are arguments after the string, they
                 are assigned to the positional parameters, starting with
                 $0.

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

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