If you are working on an application inside Docker Container, you might need commands to install packages or access file system inside the Docker Container. Executing commands inside Docker Containers should be easy enough for you since you have to do it multiple times across your development phase. Docker provides you with many ways to execute commands inside the Containers.
In this article, we are going to discuss different ways to execute any type of command inside the Docker Container.
Method 1: Using Bash
You can directly access the bash of the Docker Container and execute commands there. It’s very easy to launch the bash of the Container and you can do so using this command.
sudo docker run -it ubuntu bash
The above command runs an Ubuntu Container and fires up its bash.
Once you have access to the bash, you can start executing any command there. In this example, we will perform an echo command execution.
Method 2: Using the Docker exec Command
In order to run a command inside a Docker Container using the exec command, you have to know the Container Id of the Docker Container. You can get the Container Id using the following Command.
sudo docker container ls
sudo docker ps -a
Once you have the Container ID, you can use the Docker exec command. But you have to confirm that the Container is running before you can execute the exec command. To start the Container, use this command.
sudo docker start d64b00529582
After that, execute the exec command.
sudo docker exec -it d64b00529582 echo "GeeksforGeeks"
Method 3: By using the Dockerfile
When you are creating a large application, it is always advised that you execute your commands by specifying it inside the Dockerfile. However, you should only include those commands inside the Dockerfile which you want to execute while building the Container. For executing commands on the go, you can use any of the two methods above. To execute commands through Dockerfile, you can specify them using the Docker Run Commands.
FROM ubuntu:latest RUN echo "geeksforgeeks"
After you have created the above Dockerfile, you can build the images using the Docker build command.
sudo docker build -t sample-image .
You can see that after step 2, “geeksforgeeks” has been printed.
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.