skip to Main Content

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

2

Answers


  1. 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.
    

    To answer your further question in the comments, you want to run a single script, redis_flushall.sh to run that command. The contents of that file are:

    docker exec -it redis /bin/bash -c redis-cli auth MyRedisPass; flushall
    

    Breaking that down, you are calling redis-cli auth MyRedisPass as a bash command, and flushall as another bash command. The issue is, flushall is not a valid command, you’d want to call redis-cli flushall instead. Command chaining is something that has to be implemented in a CLI application deliberately, not something that falls out of the cracks.

    If you replace the contents of your script with the following, it should work, i.e., after ; add a redis-cli call before specifying the flushall command.

    docker exec -it redis /bin/bash -c redis-cli auth MYSTRONGPASSWORD; redis-cli FLUSHALL
    
    Login or Signup to reply.
  2. The above proposed solution with auth still got me an error

    (error) NOAUTH Authentication required

    This worked for me:

    docker exec -it redis /bin/sh -c 'redis-cli -a MYPASSWORD FLUSHALL'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search