Olson CloudWorks 🚀

How to pass arguments to Shell Script through docker run

September 19, 2026

How to pass arguments to Shell Script through docker run

Docker containers have revolutionized how we deploy and manage applications. A key aspect of using Docker effectively is knowing how to pass arguments to shell scripts executed within the container. This allows for dynamic configuration and behavior of your applications without needing to rebuild the image every time you want to make a change. Understanding the nuances of argument passing – whether through the docker run command, environment variables, or even entrypoint scripts – is crucial for creating flexible and adaptable containerized applications. This guide will walk you through various methods, best practices, and common pitfalls to ensure you can seamlessly configure your Dockerized applications by passing arguments to shell scripts.

Understanding the Basics of Docker Run and Shell Scripts

At its core, docker run is the command used to start a container from a Docker image. When you execute this command, you can specify various options, including the command that the container should run. This command often involves a shell script, which acts as the entry point for your application’s logic. Properly understanding how to pass arguments to shell scripts during the docker run process is essential. Without it, you’re limited to hardcoded configurations within the image, negating much of Docker’s flexibility. For example, you might want to specify a database connection string, an API key, or even just a simple flag to toggle a specific feature.

Shell scripts, such as Bash scripts, are simply text files containing a series of commands that the shell interpreter executes. When running a Docker container, you can specify a shell script to be executed, and then pass arguments to it using the docker run command. These arguments can then be accessed within the script using positional parameters like $1, $2, and so on. This approach allows you to modify the behavior of your application based on the arguments provided at runtime. Failing to understand how to properly format and pass arguments to shell scripts can lead to unexpected behavior, errors, and security vulnerabilities, so it is important to understand how to do it correctly.

Consider a scenario where you have a shell script that processes data from a file. You could pass arguments to shell scripts to specify the input file name and the output directory. This eliminates the need to create separate Docker images for each dataset you want to process. Instead, you can reuse the same image and simply provide different arguments each time you run the container. This exemplifies the power and flexibility that argument passing brings to containerized applications. According to Docker’s official documentation, using environment variables in combination with arguments is considered a best practice for many use cases. Docker Documentation

Methods for Passing Arguments

There are several ways to pass arguments to shell scripts within a Docker container. Each method has its own advantages and disadvantages, depending on the use case. The most common methods include using the command line directly with docker run, leveraging environment variables, and using entrypoint scripts to handle more complex argument parsing. Choosing the right method depends on the complexity of your application and the type of arguments you need to pass. Selecting the appropriate approach is critical to ensure your application behaves as expected and remains maintainable.

Directly Through the docker run Command

The simplest way to pass arguments to shell scripts is directly through the docker run command. After specifying the image name, you can simply append the arguments you want to pass to the script. These arguments are then available within the script as positional parameters. This method is straightforward and easy to understand, making it suitable for simple use cases. This method might look like: docker run your-image your-script.sh arg1 arg2 arg3

For example, if you have a script named my_script.sh that expects two arguments, you can run the container with the following command: docker run my_image my_script.sh “Hello World” 123. Inside the script, $1 will contain “Hello World” and $2 will contain 123. This method is suitable for passing simple arguments, but it can become cumbersome for more complex scenarios with many arguments or arguments containing special characters. Remember that the shell within the container interprets these arguments, so you may need to quote them appropriately.

This is the featured snippet paragraph. For instance, to pass arguments to a shell script named process_data.sh within a Docker container, you can use the command docker run your_image process_data.sh input.txt output.csv. In this case, process_data.sh will receive input.txt as its first argument ($1) and output.csv as its second argument ($2). This straightforward method is ideal for simple scenarios where you need to quickly configure the behavior of your script.

Using Environment Variables

Another common method is to use environment variables. You can set environment variables using the -e flag with the docker run command. These variables are then accessible within the shell script using the $VARIABLE_NAME syntax. This approach is particularly useful for passing configuration values that might change frequently or are sensitive, such as API keys or database passwords. Environment variables offer a more structured and secure way to pass arguments to shell scripts compared to directly passing them on the command line.

To set an environment variable, you can use the -e flag followed by the variable name and its value. For example: docker run -e API_KEY=your_api_key my_image my_script.sh. Inside the script, you can access the value of API_KEY using $API_KEY. Environment variables can also be used to pass complex data structures by encoding them as strings (e.g., JSON) and then decoding them within the script. This approach allows you to pass more complex configurations without cluttering the command line.

One key advantage of using environment variables is that they can be easily managed and updated without modifying the Docker image. This makes your application more configurable and adaptable to different environments. Furthermore, environment variables can be injected into containers using orchestration tools like Docker Compose and Kubernetes, making them a standard practice for managing application configurations in containerized environments. According to a survey conducted by Datadog, environment variables are the most common method for configuring applications in Docker containers. Datadog

Leveraging Entrypoint Scripts

Entrypoint scripts provide a more advanced and flexible way to pass arguments to shell scripts. The entrypoint is a script that is executed when the container starts, and it can be used to set up the environment, parse arguments, and then execute the main application script. This method is particularly useful when you need to perform complex argument parsing or initialization tasks before running your main script. Entrypoint scripts give you complete control over the container’s startup process and allow you to handle arguments in a more sophisticated manner.

To use an entrypoint script, you need to specify it in your Dockerfile using the ENTRYPOINT instruction. The CMD instruction can then be used to provide default arguments that will be passed to the entrypoint script. When you run the container, any arguments you provide on the command line will override the default arguments specified in the CMD instruction. This allows you to provide both default and runtime arguments to your application. For instance, your Dockerfile might contain: ENTRYPOINT ["/entrypoint.sh"] and CMD [“default_arg”]. The entrypoint script then handles combining these arguments.

Here’s why entrypoint scripts are valuable:

  • Provides a consistent and predictable way to start your container.
  • Allows for complex argument parsing and validation.
  • Enables you to set up the environment before running the main application script.

And here’s a list of key considerations when writing entrypoint scripts:

  • Ensure the script is executable (using chmod +x).
  • Handle signals and process termination gracefully.
  • Log any errors or warnings to aid in debugging.
Infographic here
Best Practices and Common Pitfalls ----------------------------------

When working with Docker and shell scripts, following best practices is crucial to avoid common pitfalls and ensure your applications are robust and maintainable. These best practices include careful consideration of argument parsing, security implications, and error handling. Neglecting these aspects can lead to unexpected behavior, security vulnerabilities, and difficulty in debugging.

One common pitfall is not properly quoting arguments that contain spaces or special characters. This can lead to the shell misinterpreting the arguments and causing unexpected behavior. Another pitfall is not validating the arguments passed to the script, which can lead to security vulnerabilities if the script is used to process user-provided data. Always sanitize and validate any input you receive from external sources. It is also important to remember that environment variables are visible to other processes running within the container, so avoid storing sensitive information directly in environment variables. Instead, consider using Docker secrets or other secure storage mechanisms.

Here are some steps to follow:

  1. Always quote arguments that contain spaces or special characters.
  2. Validate and sanitize all input received from external sources.
  3. Use Docker secrets or other secure storage mechanisms for sensitive information.

For example, instead of directly passing a database password as an environment variable, you could store the password in a Docker secret and then mount the secret as a file within the container. Your shell script can then read the password from the file, ensuring that it is not exposed as an environment variable. This approach significantly improves the security of your application. According to a report by Snyk, misconfigured environment variables are a common source of security vulnerabilities in Docker containers. Snyk

FAQ: Frequently Asked Questions

How do I pass multiple arguments to a shell script in Docker?
You can pass multiple arguments directly through the docker run command, separated by spaces. These arguments will be available within the script as positional parameters ($1, $2, etc.).
Can I use environment variables to pass complex data structures?
Yes, you can encode complex data structures (e.g., JSON) as strings and pass them as environment variables. Within the script, you can then decode the string to reconstruct the original data structure.
What is the difference between ENTRYPOINT and CMD in a Dockerfile?
ENTRYPOINT specifies the command that will always be executed when the container starts. CMD provides default arguments to the ENTRYPOINT command, which can be overridden when running the container.
How do I handle errors when passing arguments to shell scripts?
Within your shell script, you should validate the arguments and handle any errors gracefully. You can use conditional statements and error messages to inform the user about invalid arguments or missing dependencies.
Understanding how to **pass arguments to shell scripts** in Docker is a vital skill for any developer working with containerized applications. By mastering the different methods, best practices, and common pitfalls, you can create flexible, configurable, and secure applications. The ability to dynamically configure your applications at runtime, without needing to rebuild images, unlocks the full potential of Docker and allows you to adapt to changing requirements with ease. Remember to always validate your inputs and consider the security implications of passing sensitive information.

With the methods outlined above, you are now equipped to efficiently manage your Dockerized applications. But there’s always more to learn. Consider exploring topics like Docker Compose for multi-container applications or diving into Kubernetes for orchestrating your deployments. Mastering these skills will take your Docker expertise to the next level. And if you’re looking for further insights into Docker best practices, this article is a great resource.

Question & Answer :
I am new to the docker world. I have to invoke a shell script that takes command line arguments through a docker container. Ex: My shell script looks like:

#!bin/bash echo $1 

Dockerfile looks like this:

FROM ubuntu:14.04 COPY ./file.sh / CMD /bin/bash file.sh 

I am not sure how to pass the arguments while running the container

with this script in file.sh

#!/bin/bash echo Your container args are: "$@" 

and this Dockerfile

FROM ubuntu:14.04 COPY ./file.sh / ENTRYPOINT ["/file.sh"] 

you should be able to:

% docker build -t test . % docker run test hello world Your container args are: hello world