docker

Dynamically set PATH env in Dockerfile without external script?


I have a Dockerfile creating several toolchains in /opt/x-tools folder.

I need to set $PATH to contain all toolchains' bin:

# ls /opt/x-tools
arm-linux-gnueabihf
aarch64-linux-gnu

Both directories have a bin folder which I need to be added to $PATH.

Best would be to have this done via Dockerfile, however it seem not evaluating subshell in this formula:

ENV PATH="$(find /opt/x-tools -mindepth 2 -maxdepth 2 -type d -name bin | paste -sd: -):${PATH}"

It's also acceptable for me to have the $PATH set when I run the container.

What is not acceptable:

What kind of solutions do I have here?


Solution

  • You can create an entrypoint script that sets up the path and then runs whatever command is passed to it.

    ENTRYPOINT and CMD are concatenated together to a single command, so by specifying the script as the entrypoint and whatever service you want to run as the CMD, this will work intuitively.

    The script can look like this (remember to mark it executable)

    #!/bin/sh
    export PATH=/my/path:$PATH
    exec "$@"
    

    With a Dockerfile like this

    FROM debian
    COPY entrypoint-script.sh .
    ENTRYPOINT ["./entrypoint-script.sh"]
    CMD ["env"]
    

    env will be passed to the script and run at the end of the script. The output of running the container is

    PATH=/my/path:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    

    which shows that the PATH has been set successfully.