docker run <IMAGE> <MULTIPLE COMMANDS>

ID : 10180

viewed : 11

Tags : dockerdocker-imagedocker

Top 5 Answer for docker run <IMAGE> <MULTIPLE COMMANDS>

vote vote

90

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" 
vote vote

87

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" 
vote vote

70

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.

vote vote

68

bash -c works well if the commands you are running are relatively simple. However, if you're trying to run a long series of commands full of control characters, it can get complex.

I successfully got around this by piping my commands into the process from the outside, i.e.

cat script.sh | docker run -i <image> /bin/bash

vote vote

51

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

Top 3 video Explaining docker run <IMAGE> <MULTIPLE COMMANDS>

Related QUESTION?