0

I am a docker beginner. I have used this SO post to run a shell script with docker run and this works fine. However, what I am trying to do is to apply my shell script to a file that lives in my current working directory, where Dockerfile and script are.

My shell script - given a file as an argument, return its name and the number of lines:

#!/bin/bash
echo $1
wc -l $1

Dockerfile:

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

then build and run:

docker build -t test .
docker run -ti test /file.sh text_file

This is what I get:

text_file
wc: text_file: No such file or directory

I'm left clueless why the second line doesn't work, why the file can't be found. I don't want to copy my text_file to the container. Ideally, I'd like to run my script from docker container on any file in my current working directory. Any help will be much appreciated. Thanks!!

tomasy
  • 3
  • 3

1 Answers1

1

You're building your Docker image containing the script /file.sh. Still, your Docker container does not contain (or know) about the file text_file which you're passing as an argument.

In order to make it known to your Docker container, you have to mount it when running the container.

docker run --rm -it -v "$PWD"/text_file:/text_file test /file.sh /text_file

In order to check for other files, you just have to swap text_file in both the mount and the argument.

Notes

In addition to Docker volume mounts, I might suggest some more improvements to spice up your image.

  1. In order to run a script, you don't have to use ubuntu as your base image. You might be fine with alpine or even more focused bash. And don't forget to use tags in order to enforce the exact same behavior over time.
  2. You can set your script as an ENTRYPOINT of your Dockerfile. Then, your only specifying the script name (text_file in that case) as your command.
  3. When mounting files, you can change the name of the file in your container. Therefore, you can simplify your script and just mounting the file to test at the exact same place every time you run the container.
FROM alpine:3.10

WORKDIR /tmp

COPY file.sh /usr/local/bin/wordcount

ENTRYPOINT /usr/local/bin/wordcount

CMD file

Then,

docker run --rm -it -v "PWD"/text_file:/tmp/file test 

will do the job.