Running Custom Scripts In Docker With Arguments

Running Custom Scripts In Docker With Arguments

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 arg1arg2, and arg3 in each iteration with a one-second delay between each iteration.

Step 1: Create a file and copy the following contents.

# Run the script in an infinite loop
while true; do
    echo "Argument 1: $arg1"
    echo "Argument 2: $arg2"
    echo "Argument 3: $arg3"
    sleep 1

Step 2: You should have the 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 ./ /
RUN chmod +x /
# Set the entrypoint to the script with CMD arguments
CMD ["hulk", "batman", "superman"]

These entrypoint of the container is set to /, 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 hulkbatman, 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

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like