How can I use a variable inside a Dockerfile CMD?

后端 未结 4 529
借酒劲吻你
借酒劲吻你 2020-12-04 11:15

Inside my Dockerfile:

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

Error:

Comma         


        
相关标签:
4条回答
  • 2020-12-04 11:43

    If you want to use the value at runtime, set the ENV value in the Dockerfile. If you want to use it at build-time, then you should use ARG.

    Example :

    ARG value
    ENV envValue=$value
    CMD ["sh", "-c", "java -jar ${envValue}.jar"]
    

    Pass the value in the build command:

    docker build -t tagName --build-arg value="jarName"
    
    0 讨论(0)
  • 2020-12-04 11:43

    Inspired on above, I did this:

    #snapshot by default. 1 is release.
    ENV isTagAndRelease=0
    
    CMD     echo is_tag: ${isTagAndRelease} && \
            if [ ${isTagAndRelease} -eq 1 ]; then echo "release build"; mvn -B release:clean release:prepare release:perform; fi && \
            if [ ${isTagAndRelease} -ne 1 ]; then echo "snapshot build"; mvn clean install; fi && \ 
           .....
    
    0 讨论(0)
  • 2020-12-04 11:55

    Lets say you want to start a java process inside a container:

    Example Dockerfile excerpt:

    ENV JAVA_OPTS -XX +UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XX:MaxRAMFraction=1 -XshowSettings:vm 
    ... 
    ENTRYPOINT ["/sbin/tini", "--", "entrypoint.sh"] 
    CMD ["java", "${JAVA_OPTS}", "-myargument=true"]
    

    Example entrypoint.sh excerpt:

    #!/bin/sh 
    ... 
    echo "*** Startup $0 suceeded now starting service using eval to expand CMD variables ***"
    exec su-exec mytechuser $(eval echo "$@")
    
    0 讨论(0)
  • 2020-12-04 11:56

    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
    
    0 讨论(0)
提交回复
热议问题