Use Case: You need to run a custom shell script on your Docker container with arguments passed to the script. These arguments decide how the script runs inside the container.
We will look into running custom shell scripts inside a Docker container with command line arguments in this guide.
How To Run Custom Script Inside Docker
In this example, we have a custom shell script that accepts three command-line arguments ($1, $2 & $3).
The while true
loop then runs indefinitely, printing the values of arg1
, arg2
, and arg3
in each iteration with a one-second delay between each iteration.
Step 1: Create a script.sh file and copy the following contents.
#!/bin/bash arg1=${1} arg2=${2} arg3=${3} # Run the script in an infinite loop while true; do echo "Argument 1: $arg1" echo "Argument 2: $arg2" echo "Argument 3: $arg3" sleep 1 done
Step 2: You should have the script.sh
is the same folder where you have the Dockerfile.
Create the Dockerfile with the following contents.
FROM ubuntu:latest LABEL maintainer="Your Name <[email protected]>" # Install any necessary packages RUN apt-get update && apt-get install -y \ # Add any necessary packages here && rm -rf /var/lib/apt/lists/* # Copy the script to the container COPY ./script.sh / RUN chmod +x /script.sh # Set the entrypoint to the script with CMD arguments ENTRYPOINT ["/script.sh"] CMD ["hulk", "batman", "superman"]
These entrypoint of the container is set to /script.sh
, which means that this script will be run whenever the container is started. The CMD
line specifies default arguments for the script if none are provided when the container is started. In this case, the default arguments are hulk
, batman
, and superman
.
Step 3: let’s build a docker image from this Dockerfile with name script-demo.
docker build -t script-demo .
Step 4: Now lets create a container named demo using script-demo image.
docker run --name demo -d script-demo
You can check the container logs using the following command.
docker logs demo -f
Step 4: You can also pass the CMD arguments at the end of docker run command. It will override the arguments passed in the Dockerfile. For example,
docker run --name demo -d script-demo batman spiderman hulk
Here "batman spiderman hulk"
will override "hulk", "batman", "superman"
present in the docker image
6 comments
You cannot override the whole ENTRYPOINT <<
About this, with –entrypoint flag along with docker run makes it possible to override also the entrypoint.
https://docs.docker.com/engine/reference/run/#entrypoint-default-command-to-execute-at-runtime
Thanks, Ganesh for the update. I will add it to the article.
Give another words at Step 4 so it becomes meaningful
Thanks for the Tip Berk. We have made the changes
thank you man, this article was really helpful for me
Is there any tutorials for building a Jenkins Pipeline for Ruby on Rails as a Docker image.