0

I'm trying to set a enviroment variable of a docker container through bash script.

CMD ["/bin/bash", "-c","source runservice.sh"]

runservice.sh

#!/usr/bin/env bash

export "foo"="bar"

Now after pushing it when I go inside the container and do printenv, it is not setting up enviroment variable. But if I run the same command inside the container, env variable is getting set up. What's the correct way I can export using bash script?

  • How are you actually starting the container? (I'd expect a container with that `CMD` to exit immediately.) I'd prefer the Dockerfile `ENV` directive if you can (also see [In a Dockerfile, How to update PATH environment variable?](https://stackoverflow.com/questions/27093612/in-a-dockerfile-how-to-update-path-environment-variable)) , or else an entrypoint wrapper script. – David Maze Jan 15 '22 at 11:53
  • Since there are some constraints , I can not use ENV directive. docker stack deploy to start the container. – Rishav Raj Jan 15 '22 at 11:58
  • I also tried using Entrypoint but that too doesn't sets the env variable. What am I missing? – Rishav Raj Jan 15 '22 at 12:04
  • That runs a shell, changes the environment of *that* shell, and then that shell exits. You can't modify your environment by running some other command. – chepner Jan 15 '22 at 15:32
  • Thanks for explaination. Actually I'm trying to implement this: https://medium.com/@adrian.gheorghe.dev/using-docker-secrets-in-your-environment-variables-7a0609659aab and if you read the last point 'in your container entrypoint, call the following function for each environment variable you have set up.' . Then what is the container entrypoint if we can not modify the env variable? Is there anything that I am missing? – Rishav Raj Jan 15 '22 at 16:15
  • `what is the container entrypoint` I'm sorry, did you try googling that? – KamilCuk Jan 16 '22 at 11:19

1 Answers1

0

it is not setting up enviroment variable

It's setting the environment for the duration of CMD build stage. Sure, it has no effect on anything else - the shell run at CMD stage is then exiting. See dockerfile documentation.

What's the correct way I can export using bash script?

There is no correct way. The correct way to affect the environment, is to use ENV.

There is a workaround in contexts that use entrypoint - you can set entrypoint to a shell (or a custom process) that will first source the variables.

ENTRYPOINT ["bash", "-c", "source runservice.sh && \"$@\"", "--"]
KamilCuk
  • 120,984
  • 8
  • 59
  • 111