Wednesday, 21 December 2016

Docker - Setting Environment Variables within the Container

Something on Slack prompted me to look into this today …

The requirement is to have the value of an environment variable passed from the host to the container, which I've POC'd below ( using WebSphere Liberty Profile ) on my Mac.

Set an environment variable

export FOOBAR="Hello World"

Validate the value of the environment variable

echo $FOOBAR

Hello World

Start a container from an existing image, passing in the environment variable

handle=`docker run -d -t -p 80:9080 -p 443:9443 -e FOOBAR --name WLP websphere-liberty:latest`

Check that the container is running

docker ps -a

CONTAINER ID        IMAGE                      COMMAND                  CREATED             STATUS              PORTS                                         NAMES
58fa4ffd7893        websphere-liberty:latest   "/opt/ibm/docker/dock"   4 seconds ago       Up 2 seconds        0.0.0.0:80->9080/tcp, 0.0.0.0:443->9443/tcp   WLP


Validate the variable created as a handle to the container ( makes subsequent commands easier )

echo $handle

58fa4ffd789332526e6f66b39c233a654cc4ae3e76b689721f41d0b11863be1e

Open a command prompt against the container

docker exec -i -t $handle /bin/bash

root@58fa4ffd7893:/#

Validate the value of the environment variable

echo $FOOBAR

Hello World


*UPDATE*

It transpires that I can also do this: -

handle=`docker run -d -t -p 80:9080 -p 443:9443 -e SNAFU="$FOOBAR" --name WLP websphere-liberty:latest`

where I'm setting a variable called SNAFU ( visible inside the container ) to the value of the external variable FOOBAR.

Job done :-)

With thanks to this: -


and this: -

No comments: