0

I'm trying to run a simple hello world program from a docker container. What I want to do is display a custom message that I pass to the environment variable. If nothing is passed to the environment variable than the program should just display a default message of "Hello World!". I've already created an environment variable in my dockerfile and I'm trying to override that variable in my environment variable file using the --env-file flag. However, I'm not sure what the correct syntax would be for setting the environment variable since I'm getting "invalid syntax".

Below are my files:

Dockerfile

FROM python:3
ADD main.py /
ENV MESSAGE "Hello World!"
CMD ["python3", "./main.py"]

env_file

MESSAGE="Goodbye World!"

main.py

# simple hello world program
print($MESSAGE)

This is how I'm building and running my container

docker build -t example -f Dockerfile .
docker run --env-file=env_file --rm --name example example

3
  • 1
    please post the full traceback. though I suspect it's complaining about $MESSAGE (which, afaik, isn't valid python syntax) . Commented Jul 31, 2020 at 9:41
  • 1
    if you need to get the environment variable, you need to import os and then do print(os.environ.get("MESSAGE")). Commented Jul 31, 2020 at 9:43
  • In addition to the other comments and the accepted answer I can't help but wonder why you didn't try running your program on your local workstation/server. Had you done so you would have realized your Python program was syntactically invalid. Commented Aug 1, 2020 at 4:32

1 Answer 1

6

Change your main.py to:

import os

print(os.environ['MESSAGE'])

Accessing environment variables using $ in Python is not supported and is not valid Python syntax.

Note that this will raise an exception if there's no such environment variable, so you may want to use os.environ.get('MESSAGE') and check for None or do some error handling in that case.

Sign up to request clarification or add additional context in comments.

1 Comment

This is just what I needed. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.