Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

docker - How can I use a variable inside a Dockerfile CMD?

Inside my Dockerfile:

ENV PROJECTNAME mytestwebsite
CMD ["django-admin", "startproject", "$PROJECTNAME"]

Error:

CommandError: '$PROJECTNAME' is not a valid project name

What is the quickest workaround here? Does Docker have any plan to "fix" or introduce this functionality in later versions of Docker?

NOTE: If I remove the CMD line from the Docker file and then run the Docker container, I am able to manually run Django-admin startproject $PROJECTNAME from inside the container and it will create the project...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use an execution list, as in...

CMD ["django-admin", "startproject", "$PROJECTNAME"]

...then Docker will execute the given command directly, without involving a shell. Since there is no shell involved, that means:

  • No variable expansion
  • No wildcard expansion
  • No i/o redirection with >, <, |, etc
  • No multiple commands via command1; command2
  • And so forth.

If you want your CMD to expand variables, you need to arrange for a shell. You can do that like this:

CMD ["sh", "-c", "django-admin startproject $PROJECTNAME"]

Or you can use a simple string instead of an execution list, which gets you a result largely identical to the previous example:

CMD django-admin startproject $PROJECTNAME

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...