带有构建参数的ENTRYPOINT和CMD

时间:2018-06-28 23:50:48

标签: docker dockerfile

这不起作用:

FROM alpine:3.7

# build argument with default value
ARG PING_HOST=localhost

# environment variable with same value
ENV PING_HOST=${PING_HOST}

# act as executable
ENTRYPOINT ["/bin/ping"]

# default command
CMD ["${PING_HOST}"]

应该可以使用build-arg构建映像,并可以使用环境变量启动容器来覆盖cmd。

docker build -t ping-image .
docker run -it --rm ping-image

错误:ping:地址错误'$ {PING_HOST}'

更新:

FROM alpine:3.7

# build argument with default value
ARG PING_HOST=localhost

# environment variable with same value
ENV PING_HOST ${PING_HOST}

COPY ./entrypoint.sh /usr/local/bin/

# act as executable
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

# default command
CMD $PING_HOST

entrypoint.sh

#!/bin/sh

/bin/ping $PING_HOST

之所以可行,是因为entrypoint.sh启用了预期的变量替换。

1 个答案:

答案 0 :(得分:1)

要让CMD扩展变量,您需要安排一个shell,因为shell负责扩展环境变量,而不是Docker。您可以这样做:

ENTRYPOINT ["/bin/sh"]
CMD ["-c" , "ping ${PING_HOST}"]

OR

CMD ["sh", "-c", "ping ${PING_HOST}"]