Docker set environment variable from command or fi

2019-05-24 22:47发布

问题:

I need to set an environment variable CLASSPATH. In that variable I need to set the result of a command:

hadoop classpath --glob

This will return a ton of java libraries and they all need to get set into that CLASSPATH variable. The big problem is that I can only run this command after the docker build is complete, meaning I have to do it in the ENTRYPOINT. But I just cant get it working. I tried differen approaches:

ENTRYPOINT ["sh", "-c", "export CLASSPATH=$(hadoop classpath --glob) ...."
ENTRYPOINT ["sh", "-c", "set CLASSPATH=$(hadoop classpath --glob) ...."
ENTRYPOINT ["sh", "-c", "CLASSPATH=$(hadoop classpath --glob) ...."
ENTRYPOINT ["sh", "-c", "/bin/bash && export CLASSPATH=$(hadoop classpath --glob) ...."

But nothing of it is working. The command itself is working, I tested it using:

ENTRYPOINT ["sh", "-c", "echo $(hadoop classpath --glob) >> /tmp/classpath.tmp ...."

This file contains the correct content after startup. So there is just a problem with setting and persisting the environment variable. How am I supposed to set the environment variable? Usually you use something like

ENV CLASSPATH="some classpath"

But here I cant use the ENV statement since it wont process the command $(hadoop classpath --glob)

回答1:

In this case I would prefer to use a bash profile change the SHELL to sh -lc instead of sh -c

Dockerfile

FROM alpine
RUN echo "export NAME=TARUNLALWANI" >> ~/.profile
RUN echo $NAME
SHELL ["sh", "-lc"]
RUN echo $NAME
CMD env

Output of build

$ docker build . --no-cache
Step 1/6 : FROM alpine
Step 2/6 : RUN echo "export NAME=TARUNLALWANI" >> ~/.profile
Step 3/6 : RUN echo $NAME

Step 4/6 : SHELL sh -lc
Removing intermediate container a6a243f24519
Step 5/6 : RUN echo $NAME
TARUNLALWANI
Successfully built 054f35a4d89a

As you can see changing the SHELL from sh -c to sh -lc starts loading our profile. So you will update the .profile to export CLASSPATH based on

Running the container

$ docker run 054f35a4d89a
HOSTNAME=92c4ca32b1f0
SHLVL=1
HOME=/root
PAGER=less
PS1=\h:\w\$
NAME=TARUNLALWANI
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
CHARSET=UTF-8

Edit-1

Try this without the need of a profile

ENTRYPOINT []
CMD ["/bin/sh", "-c", "export CLASSPATH=$(hadoop classpath --glob) && env"]


回答2:

The only working solution for that problem was to not use an ENTRYPOINT in the Dockerfile at all.

  1. Create entrypoint.sh
  2. Add all the stuff you need (exports for example) into that sh file
  3. Copy entrypoint.sh in dockerfile to /
  4. Execut entrypoint.sh in docker run or dockercompose

Attention: you need to execute it by . /entrypoint.sh. Otherwise it wont work.