Skip to content
SumGuy's Ramblings
Go back

Multiple Actions with a Single docker exec Call

How to Execute Multiple Commands in a Docker Container with a Single Command

Docker provides a powerful and flexible platform for developers to isolate applications in containers, making them portable and easy to manage. A common scenario that developers face is needing to execute multiple commands within a Docker container without initiating multiple separate docker exec calls. In this post, we’ll explore a streamlined approach to achieve this in a single invocation.

The Challenge: Running Multiple Commands Sequentially

Typically, executing commands in a Docker container is done through the docker exec command followed by the container name and the command you wish to execute. The challenge arises when you need to perform several commands that depend on each other. Repeatedly running docker exec for each command can be inefficient and cumbersome, especially in situations involving dependency or order of execution.

The Solution: Single Command Execution

To run multiple commands inside a Docker container with one command, we can employ a shell script technique using a here-document (heredoc). This method involves passing multiple commands all at once to a container’s shell. Here’s how you can do it:

cat <<EOF | docker  exec --interactive alpine sh
cd /opt
wget https://example.com/file.tgz
tar xvf file.tgz
rm file.tgz
EOF

Step-by-Step Explanation:

Benefits:

Using this technique effectively allows Docker developers and system administrators to manage containerized applications with greater flexibility and efficiency. Whether you’re automating deployments, performing maintenance, or scripting routine tasks, combining commands with this approach can save time and reduce complexity. This method is particularly valuable in build scripts or during the development phase, where such tasks are frequent.


Share this post on:

Previous Post
Understanding the regreSSHion Vulnerability in OpenSSH
Next Post
Mastering xargs in Linux