0

I am trying to set some environment variable by a script. (Like it is explained here: https://stackoverflow.com/a/55922307)

Dockerfile

   FROM container1:latest
   WORKDIR /etc/test
   RUN ["/bin/bash", "-c", ". env/environment.sh && command2 && command3"]
   COPY entry.sh .
   ENTRYPOINT ["/etc/test/entry.sh"]

entry.sh

#!/bin/bash
. /etc/test/env/environment.sh
exec "$@"

Then build the image:

docker build -t docker-test .

Then run it:

docker run -it -d --name env-test docker-test:latest

But the container stops after some seconds:

COMMAND                 CREATED             STATUS
"/etc/test/entry.sh"   7 seconds ago       Exited (0) 1 second ago

Why is the container not running anymore? I would like to go into it with docker exec. Can I somehow test if the environment variables are correctly set?

I was trying to add CMD [ "sh", "-c", "echo $PATH" ] add the end, but nothing happens...

1 Answers1

2

Your container exits because you don't provide it any command to run. You've set ENTRYPOINT to /etc/test/entry.sh, and that scripts tries to execute any arguments you provide (via exec "$@"), but you're running the image like this:

docker run -it -d --name env-test docker-test:latest

Since you're not providing a command, the container exits as soon as it starts. Adding CMD [ "sh", "-c", "echo $PATH" ] isn't going to change this behavior because that command also exits immediately.

It's not clear what you expect this container to do.

If you just want the container to hang around for a while, you can have it run a sleep command:

docker run -it -d --name env-test docker-test:latest sleep 1800

Or you could bake that into the Dockerfile as the default command:

FROM container1:latest
WORKDIR /etc/test
RUN ["/bin/bash", "-c", ". env/environment.sh && command2 && command3"]
COPY entry.sh .
ENTRYPOINT ["/etc/test/entry.sh"]
CMD ["sleep", "1800"]

But neither of these examples really makes sense; you would typically have a container run some sort of long-lived process like a web server, database, etc, rather than just hanging around as a target for docker exec.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • Thank you, I appreciate your answer. Very helpful. So if I understand it correct, if CMD start a process the container should not stop running? – dangerseeker Oct 14 '20 at 10:46
  • 1
    The container will continue running as long as the last process started by your `ENTRYPOINT` or `CMD` does not exit or go into the background. – larsks Oct 14 '20 at 13:38
  • Thanks. In the mean time I figured out that ENTRYPOINT is only invoked by docker run. Is there a good solution to set env variables when running docker exec? – dangerseeker Oct 14 '20 at 13:55