2

I want to pass environment variables in my docker run command and access them in my entrypoint shell script.

This is my super simple Dockerfile for test purposes:

FROM ubuntu:20.04

WORKDIR /

ADD entrypoint.sh .

RUN chmod 755 entrypoint.sh

ENTRYPOINT [ "/entrypoint.sh" ]

And this is the entrypoint.sh:

#!/bin/sh

printf "env var TEST = ${TEST} "

I just build the Dockerfile like this: docker build -t test:1.0 .

And then run it like this: docker run -i test:1.0 -e TEST='Hello world'

Unfortunately the output is not containing the env var.

Laurenz Glück
  • 1,762
  • 3
  • 17
  • 38
  • 3
    Docker options like `-e` need to come _before_ the image name. Things after the image name are interpreted as the command to run. If you `echo "$1"` inside the script you should see the `-e` option come back out. (Should the script have a `exec "$@"` line to actually run that command?) – David Maze Apr 29 '22 at 09:19

2 Answers2

2

For the record: Predefining the variables is not the solution.

The order of the args is important, like David Maze said.

# incorrect
docker run -i test:1.0 -e TEST='Hello world'

# correct
docker run -i -e TEST='Hello world' test:1.0 
akop
  • 5,981
  • 6
  • 24
  • 51
-1

Something like this will work:

entrypoint.sh

#!/bin/sh
echo $MYVAR

Dockerfile

FROM alpine:3.15.4
WORKDIR /home/app
COPY ./entrypoint.sh .
ENV MYVAR=""
ENTRYPOINT ["/bin/sh", "/home/app/entrypoint.sh"]

And then you can build & run the container while setting the environment variable with:

$ docker build -t test . && docker run -e MYVAR="hello world" test
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Simon
  • 397
  • 1
  • 3
  • 24