17

I am trying to execute a command inside my mongodb docker container. From my linux command prompt it is pretty easy and works when I do this

docker exec -it d886e775dfad mongo --eval 'rs.isMaster()'

The above tells me to go to a container and execute the command

"mongo --eval 'rs.isMaster()' - This tells mongo to take rs.isMaster() as an input and execute it. This works and gives me the output.

Since I am trying to automate this via bash script, I did this

cmd="mongo --eval 'rs.isMaster()"

And then tried executing like this

docker -H $node2 exec d886e775dfad "$cmd"

But I guess somehow docker thinks that now the binary file inside the container is not mongo or sth else and it gives me the following error:

rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"mongo --eval 'rs.isMaster()'\": executable file not found in $PATH"

3 Answers 3

31
docker exec -it d886e775dfad sh -c "mongo --eval 'rs.isMaster()'"

This calls the shell (sh) executing the script in quotation marks. Note that this also fixes things like wildcards (*) which otherwise do not work properly with docker exec.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain why your solution works in order to raise the value of your contribution? Posting only code is often not very helpful.
Why is -c not listed in docker exec --help?
@Caleb it's a parameter to sh
4

You need to run (there's a missing single quote in your example):

cmd="mongo --eval 'rs.isMaster()'"

Followed by (without the quotes around $cmd):

docker -H $node2 exec d886e775dfad $cmd

By including quotes around $cmd you were looking for the executable file mongo --eval 'rs.isMaster()' rather than the executable mongo with args mongo, --eval, and 'rs.isMaster()'.

Comments

0

It looks as though mongo is interpreting the entire contents of $cmd as the command to execute. This makes sense because you are quoting the parameter on the command line. Essentially when you did ... exec "$cmd" the shell will interpret the dollar-sign and expand it to be the contents in-place. Next it will interpret the double-quotes and pass the entire inner contents (now being mongo --eval 'rs.isMaster()' as a single command line argument to the process. This should result in mongo looking for a program with the name mongo --eval 'rs.isMaster() in your path. Which obviously doesn't exist.

2 Comments

how do i fix this?
Oops sorry forgot the solution. Try omitting the quotes around the variable. Then it should expand the variable inline and turn into docker -H $node2 exec d886e775dfad mongo --eval 'rs.isMaster()'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.