0

I have a simple docker container that runs a script on startup which exports some variables.

So the final line in my Dockerfile is CMD ./startup.sh

And startup.sh has

#!/usr/bin/env bash

export testvar="test"
echo $testvar
node app.js

The output in terminal when running container shows "test" as I would expect.

However if I then run docker exec -it *containerid* bash and run echo $testvar inside the container it's empty.

Has the environment var not persisted? Or does the terminal from running docker exec bash not have permission to see it or something?

Omiron
  • 341
  • 3
  • 15

2 Answers2

1

docker exec starts a new shell in the container. It's not a child of the the initial process, so it won't inherit any environment variables from that process.

If you want to set environment variables that will be visible in docker exec, then set them on the container itself, either in your Dockerfile:

FROM docker.io/node:18

ENV testvar=test
CMD node app.js

Or on the docker run command line:

docker run -e testvar=test myimagename
larsks
  • 277,717
  • 41
  • 399
  • 399
  • Hmm I don't actually need them visible in `docker exec`, I was just doing that to verify they'd been set. They are needed for an app I have running in the container. Would node in this case have access to testvar? I'm not able to change the dockerfile or docker run but I am able to customise the start script so i thought this might be a good way to do it – Omiron Sep 15 '22 at 14:34
  • Yes, your node application should have access to `testvar`. That's not really anything specific to Docker: you're setting an environment variable in a process and then spawning a child process; that means it inherits the parent environment. – larsks Sep 15 '22 at 14:39
  • Yeah it seems I just have confusion over which processes would inherit the environment variables, are you saying ones set in the Dockerfile itself would be visible in docker exec because they aren't owned by a process in that case? – Omiron Sep 15 '22 at 14:43
  • 1
    Effectively, yes (I would phrase it has "they would be visible in docker exec because Docker ensures they are set on any processes spawned inside the container"). – larsks Sep 15 '22 at 14:45
0

If you do not explicitly need the testvar in your script, you should add ENV testvar=test to your Dockerfile.

You should then be able to use testvar in your Dockerfile.

If you need it in your Dockerfile you can also declare it as ENV testvar=test in your Dockerfile and then provide it to your script as parameter, like CMD ./startup.sh $testvar.

In your script you would need to change the export testvar="test" to testvar=$1 and then you can simply use it with the echo command as before.

Sources:
How do I set environment variables during the build in docker
https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script