Read input of shell script in Docker container

Viewed 2952

I have a docker image of simple shell script. The shell script simply contains 1 method. and that method is expecting input from user. and then displaying the result which user has provided into the screen.

#!/bin/bash

executeScript() {
    echo "this is a shel script";
    read -p 'Enter value: ' value;
    echo $value;
}

executeScript

Now I have my docker file like

FROM ubuntu
ADD example.sh /opt/example.sh
RUN /opt/example.sh

Now I have created image using docker build -t example-image .
The image got created. Now I need to execute the container. while executing the container I want the shell script should wait for user input How can I achieve?

If I execute docker run -it --name example-container example-image:latest I am not getting the actual output

The expected output should be like if I execute only shell script without docker

enter image description here

How can I run the container so that I can get the output like image attached

2 Answers

Follow the given steps.

Dockerfile

FROM ubuntu
WORKDIR /opt
COPY example.sh .
CMD ["sh", "example.sh"]

Build

$ docker build -t input .

Run

$ docker run -it input
this is a shel script
Enter value: 3
3

Your problem is using RUN in the Dockerfile - it executes the script at that point, during image creation (which does not accept input - so it returns immediately). Instead, you should use CMD or ENTRYPOINT to change the executable when you start the container:

FROM ubuntu
ADD example.sh /opt/example.sh

CMD /opt/example.sh
Related