I have file template which has various variables. I would like to constitute these variables with values before I copy this file to
running container. This what I do right now:
export $(grep -v '^#' /home/user/.env | xargs) &&
envsubst < template.yaml > new_connection.yaml &&
docker cp new_connection.yaml docker_container:/app &&
rm new_connection.yaml
This is working, however I’m sure there is a way I can skip file creation/copy/remove steps and do just something like: echo SOME_TEXT > new_connection.yaml
straight to the container. Could you help?
2
Answers
This seems like a good application for an entrypoint wrapper script. If your image has both an
ENTRYPOINT
and aCMD
, then Docker passes theCMD
as additional arguments to theENTRYPOINT
. That makes it possible to write a simple script that rewrites the configuration file, then runs theCMD
:In the Dockerfile,
COPY
the script in and make it theENTRYPOINT
. (If your host system doesn’t correctly preserve executable file permissions or Unix line endings you may need to do some additional fixups in the Dockerfile as well.)When you run the container, you need to pass in the environment file, but there’s a built-in option for this
If you want to see this working, any command you provide after the image name replaces the Dockerfile
CMD
, but it will still be passed to theENTRYPOINT
as arguments. So you can, for example, see the rewritten config file in a new temporary container:Generally, I agree with David Maze and the comment section. You should probably build your image in such a way that it picks up env vars on startup and uses them accordingly.
However, to answer your question, you can pipe the output of
envsubst
to the running container.If you want to write that to a file, using redirection, you need to wrap it in a
sh -c
because otherwise the redirection is treated as redirect the container output to some path on the host.I did it here with
docker run
but you can do the same withexec
.