docker run <IMAGE> <MULTIPLE COMMANDS>

女生的网名这么多〃 提交于 2019-11-26 11:47:37

问题


I\'m trying to run MULTIPLE commands like this.

docker run image cd /path/to/somewhere && python a.py

But this gives me \"No such file or directory\" error because it is interpreted as...

\"docker run image cd /path/to/somewhere\" && \"python a.py\"

It seems that some ESCAPE characters like \"\" or () are needed.

So I also tried

docker run image \"cd /path/to/somewhere && python a.py\"
docker run image (cd /path/to/somewhere && python a.py)

but these didn\'t work.

I have searched for Docker Run Reference but have not find any hints about ESCAPE characters.


回答1:


To run multiple commands in docker, use /bin/bash -c and semicolon ;

docker run image_name /bin/bash -c "cd /path/to/somewhere; python a.py"

In case we need command2 (python) will be executed if and only if command1 (cd) returned zero (no error) exit status, use && instead of ;

docker run image_name /bin/bash -c "cd /path/to/somewhere && python a.py"



回答2:


You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    



回答3:


You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.




回答4:


If you want to store the result in one file outside the container, in your local machine, you can do something like this.

RES_FILE=$(readlink -f /tmp/result.txt)

docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"

The result of your commands will be available in /tmp/result.txt in your local machine.




回答5:


For anyone else who came here looking to do the same with docker-compose you just need to prepend bash -c and enclose multiple commands in quotes, joined together with &&.

So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"



来源:https://stackoverflow.com/questions/28490874/docker-run-image-multiple-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!