Home > Net >  Bash - Connect to Docker container and execute commands in redis-cli
Bash - Connect to Docker container and execute commands in redis-cli

Time:10-19

I'm trying to create a simple script which would:

  1. Connect to docker container's BASH shell
  2. Go into redis-cli
  3. Perform a flushall command in redis-cli

So far, I have this in my docker_script.sh (this basically copies the manual procedure):

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. Then, if I type exit into the container's BASH shell, it outputs this:

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? How do I "automate" it by creating such a small BASH script?

Thank you

CodePudding user response:

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. Try passing in your redis-cli command to bash like this:

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

The -c is used to tell bash to read a command from a string.

Excerpt from the man page:

-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.
  • Related