Many time, you may land into the situations where you need to execute some commands on the docker container which is already running. We normally do so because we don’t want to stop the container ,make changes and start over. Instead we can simply pass the commands we want ,to the running container.
Using the docker EXEC command:
Docker has the special command exec for the task. The syntax for using it is the following:
docker exec -i <container-name> <bash> <<< command>
You are reading this means you must be familiar with docker exec command. Normally we use to get into docker container. But here we have just use -i options as we don’t want to get into the container ,but simply interact to it. The command to execute must be passed after <<<
Example: docker exec -i wordpress_contaner bash <<< ls -al
This command will get into the docker container called wordpress_container and show us all the file locations of the locations where it gets on entering.
Passing the command file to exec command:
Instead of passing the commands after <<< we can also pass the file with the command to execute. The syntax for that ,changes a bit. Instead of <<< we use single less than symbol.
Example of exec with file:
Here, in this example we will try to run the update commands on the mysql running container. We will not pass the update command directly but instead create a file where the sql command will be written and pass the file-source to the command.
SITE_URL="https://staging.com" echo "UPDATE wp_options SET option_value = \"$SITE_URL\" WHERE option_name = \"siteurl\"" > /tmp/updater.sql docker exec -i $container_name mysql -uuser -ppassword dbname < /tmp/updater.sql
why doing so ?
Many time you may land into errors when directly passing the commands over exec so in such scenario, you may trying adding the command to file and pass that after < symbol as in the above example.