尽量使用官方的 image作为base image e.g.,
FROM scratch
FROM centos:7
定义了 image 中的 metadata e.g.,
LABEL maintainer=“xiaowu@gmail.com” LABEL version=“1.0.0” LABEL description=“This is xxx”
每次运行一次 RUN 对于 image 都会生成新的一层,为了避免无用分层,合并多条命令成一行。 e.g.,
RUN yum update && yum install -y htop \ iotop
RUN apt-get update && apt-get install -y perl \ pwgen --no-install-recommends && rm -rf \ /var/lib/apt/lists/* #注意清理cache
RUN /bin/bash -c ‘source ~/.bashrc; echo $HOME’
e.g.,
WORKDIR /root
WORKDIR /test #如果目录不存在会自动创建 WORKDIR demo RUN pwd #输出结果应该是 /test/demo
e.g.,
ADD app / ADD archive.tar.gz /
WORKDIR /root ADD app test/ #/root/test/app
WORKDIR /root COPY app /test
尽量使用,增加可维护性 e.g.,
ENV MYSQL_VERSION 5.6 RUN apt-get install -y mysql-server="${MYSQL_VERSION}" \ && rm -rf /var/lib/apt/lists/*
都是设置容器启动后执行的命令
RUN yum install -y htop CMD echo “hello docker” ENTRYPOINT echo “hello docker”
Exec 格式:RUN [“yum”, “install”, “-y”, “htop”] CMD ["/bin/echo", “hello docker”] ENTRYPOINT ["/bin/echo", “hello docker”]
FROM entos ENV name Docker CMD echo “hello $name”
如果执行 dockers run -it xxx /bin/bash,则hello Docker不会输出。
如果定义了多个CMD,只有最后一个CMD会生效一般会一个shell脚本作为entrypoint
… … COPY docker-entrypoint.sh /usr/local/bin/ ENTRYPOINT [“docker-entrypoint.sh”]
EXPOSE 27017 CMD [“mongod”] … …
RUN 运行的时间点不同在 build 阶段,CMD 在 docker run 时运行
区别:
FROM centos ENV name Docker ENTRYPOINT echo “hello $name”
容器build后运行会打印出 hello Docker
FROM centos ENV name Docker ENTRYPOINT ["/bin/echo", “hello $name”]
打印出 hello $name 如果想打印出 hello Docker,需要使用以下方式
ENTRYPOINT ["/bin/bash", “-c”, “echo hello $name”]
官方的 Dockerfile 案例:
https://github.com/docker-library参考文档:
https://docs.docker.com/engine/reference/builder