skip to Main Content

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?

2

Answers


  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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search