Running Shell Scripts In Docker With Arguments

Running Custom Scripts In Docker With Arguments

Use Case:  You need to run a custom shell script as an entrypoint 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.

Dockerfile – Run Shell Script

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 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]>"
RUN apt-get update && apt-get install -y \
    && 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"]

Here the 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 hulkbatman, and superman.

Step 3: Let’s build a docker image from this Dockerfile with the name script-demo.

docker build -t script-demo .

Step 4: Now let’s 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 the 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

Note: If you don’t want to pass arguments to the shell script, you can ignore the CMD arguments and execute the shell script directly using Entrypoint.

8 comments
  1. Great article I even read so many blogs about the difference between entrypoint and cmd, But now with a realtime scenario i can apply and learn. It’s great mahn

Leave a Reply

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

You May Also Like