Execute in#
You can use docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
to run some commands in the container. This page focuses on the features of this command.
The following cell runs the container that we’ll use for experiments.
docker run -tid --rm --name exec_tests alpine &> /dev/null
Note don’t forget to stop the container after all.
docker stop exec_tests
test_container
Execute script#
Sometimes it’s useful to run a script—a set of commands—using docker exec
. The specific options depend on the container you’re running, but for bash
and sh
, you can run a shell and specify the -c
option. The text in quotes will be recognized as a command.
The following cell shows execution of the script that creates folder sh_c
and creates some files in this folder in cycle.
docker exec exec_tests sh -c '
mkdir sh_c
for i in $(seq 1 10); do
touch sh_c/file$i
done
'
Let’s check if the files were truly created.
docker exec exec_tests ls sh_c
file1
file10
file2
file3
file4
file5
file6
file7
file8
file9
Heredoc to container#
You can save a file directly to a Docker container from the terminal without using temporary files. To do this, combine Docker’s file writing command with the heredoc
syntax in Bash.
The following example starts such a container and saves a multiline file in it using the heredoc
and cat
commands of the sh
shell available in alpine
.
docker exec -i exec_tests sh -c 'cat > /this_is_file' <<EOF
This is multiline file in the container.
line1
line2
line3
EOF
Let’s see if the file has been added to the container.
docker exec exec_tests cat /this_is_file
This is multiline file in the container.
line1
line2
line3