zaman sakib
zaman sakib

Reputation: 957

set environment variable in running docker contianer

I need to set environment variable in a running docker container. I am already aware of the way of setting environment variable while creating a container. As far I found there is no available straight forward way to do this with docker and docker is planning to add something with new version 1.13.

But I found that some people able to manage it which is not working for me now. I tried following ways but did not work for me-

docker exec -it -u=root test /bin/bash -c "export port=8090"

echo "export port=8090" to /etc/bash.bashrc using a script and then source it

docker exec -it test /bin/bash -c "source /etc/bash.bashrc"

configuring the whole thing in a script and run it from host also did not work. While running script from host all the other command successfully executes except "export port=8090" or "source /etc/bash.bashrc" or "source /root/.bashrc".

Can anyone explain why sourcing file from host does not work in docker container even when I set user("-u=root")? Can anyone help me to solve this? When I source the file from inside the container it works perfectly. But in my case I have to do it from host machine

NOTE:, I am using docker 1.12 and tried the above in ubuntu:16.04 and ubuntu:14.04

Upvotes: 2

Views: 10425

Answers (2)

zaman sakib
zaman sakib

Reputation: 957

I find a way to provide environment variable to a running container. Fist upgrade your docker-engine. I am using V1.12.5.

create a script with environment variables-

#!/bin/bash

echo "export VAR1=VAL1
export VAR2=VAL2" >> /etc/bash.bashrc
source /etc/bash.bashrc

Now start a container. Here, 'test' is the container name:

docker run -idt --name=test ubuntu

Copy your script to container:

docker cp script.sh test:/

Run the script :

docker exec -it test /bin/bash -c "/script.sh"

Restart your container:

docker restart test 

Go to container shell

docker exec -it test /bin/bash

Check the variable

echo $VAR1

Upvotes: 1

Uri Shalit
Uri Shalit

Reputation: 2308

If you have a running process in the docker and you are attempting to change the environment variable in the docker so the running process will dynamically change - this will not work. The environment variables of a process are set when it starts. You can see here ways to overcome that, but I don't think that is the right way to go.

I would instead, have a configuration file that the file reads (or listens to) periodically. And when you want to change the configuration change the file.

If this isn't your scenario, please describe your scenario so we can better assist you.

Upvotes: 1

Related Questions