2

I have the following line in my Dockerfile which is supposed to capture the display number of the host:

RUN      DISPLAY_NUMBER="$(echo $DISPLAY | cut -d. -f1 | cut -d: -f2)" && echo $DISPLAY_NUMBER

When I tried to build the Dockerfile, the DISPLAY_NUMBER is empty. But however when I run the same command directly in the terminal I get the see the result. Is there anything that I'm doing wrong here?

4
  • Is the $DISPLAY variable empty when you run docker build? Commented Nov 13, 2018 at 19:34
  • Yes! The DISPLAY_NUMBER is empty!
    – joesan
    Commented Nov 13, 2018 at 19:41
  • You can’t put that in a Dockerfile. What would happen if you ran the image from a different host, or (given your other questions) from a different ssh session with a different $DISPLAY?
    – David Maze
    Commented Nov 13, 2018 at 19:48
  • What do you want to achieve with this command?
    – mbuechmann
    Commented Nov 13, 2018 at 19:50

2 Answers 2

2

Commands specified with RUN are executed when the image is built. There is no display during build hence the output is empty.

You can exchange RUN with ENTRYPOINT then the command is executed when the docker starts.

But how to forward the hosts display to the container is another matter entirely.

1

Host environment variables cannot be passed during build, only at run-time.

Only build args can be specified by:

first "declaring the arg"

ARG DISPLAY_NUMBER

and then running docker build . --no-cache -t disp --build-arg DISPLAY_NUMBER=$DISPLAY_NUMBER

You can work around this issue using the envsubst trick

RUN      echo $DISPLAY_NUMBER

And on the command line:

envsubst < Dockerfile | docker build . -f -

Which will rewrite the Dockerfile in memory and pass it to Docker with the environment variable changed.

Edit: Note that this solution is pretty useless though, because you probably want to do this during run-time anyways, because this value should depend on not on where the image is built, but rather where it is run.

I would personally move that logic into your ENTRYPOINT or CMD script.

2
  • That will pass the display number of the machine where the image is built and print it out during build. I doubt that this makes any sense. If I wanted to know the display number of my current machine, I would just run the command there.
    – mbuechmann
    Commented Nov 13, 2018 at 19:49
  • I did not really consider the OP's intent, so in that sense your answer is probably more useful from a practical perspective. Although your answer has a small inaccuracy though, regarding as to why the variable is blank.
    – Uku Loskit
    Commented Nov 13, 2018 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.