首页 > 解决方案 > Dockerfile 中的 `touch` 有什么作用?

问题描述

标签: dockerdockerfile

解决方案


Because of Docker layer caching, in a lot of common cases the touch command won't do anything. If the jar file has changed then the ADD command will include it in the image with its last-modified time from the host ("it is copied individually along with its metadata"); since that's presumably recently, the touch command will update it to seconds later. If the jar file hasn't changed then Docker will skip both the ADD and RUN commands and use the filesystem output from the previous time you ran it, with the previous run's timestamp.

If the jar file is just being used as an input to java -jar then its last-modified time shouldn't be relevant to anything either.

I'd guess you can safely remove the touch command with no ill effects. There are a couple of unnecessary sh -c invocations that don't matter and just clutter things. I'd guess this Dockerfile to be functionally equivalent:

# Prefer COPY to ADD, unless you explicitly want Docker to fetch
# URLs or unpack archives
COPY dist /dist/
ARG JAR_FILE
COPY target/${JAR_FILE} /target/app.jar
EXPOSE 8080
# Prefer CMD to ENTRYPOINT, if nothing else so `docker run imagename sh` works
# Split simple commands into words yourself
CMD ["java", "-jar", "/target/app.jar"]

推荐阅读