本文共 2951 字,大约阅读时间需要 9 分钟。
介绍Dockerfile常用额语法,从而可以自定义编写Dockerfile。
1.FROM:选择基础image
FROM scratch #制作base imageFROM centos #使用现有base imageFROM ubuntu:14.04ps:尽量使用官方image作为base image
2.LABEL:包含
LABEL maintainer="spark@126.com"LABEL version="1.0"LABEL description="This is a description"ps:这些元数据必不可少
3.RUN:运行程序
RUN yum update && yum install -y vim \ python-dev #反斜杠换行RUN apt-get update && apt-get install -y perl \ pwgen --no-install-recommends && rm -rf \ /var/lib/apt/lists/* #注意清理缓存cache ps:尽量使用"&&"和\把多条命令合并成一条
4.WORKDIR:设定工作目录
WORKDIR /testWORKDIR demoRUN pwd结果:/test/demops:相当于mkdir + cd使用WORKDIR,不要使用RUN cd尽量使用绝对目录
5.ADD 和COPY
(1)ADD
把本地文件添加到当前image里面ADD hello /ADD可以添加并且解压缩ADD test.tar.gz / #添加到根目录并解压
(2)COPY
COPY hello /
(3)两者区别
使用一般COPY优先,但是ADD可以解压功能添加远程文件/目录,应当使用curl或者wget
5.ENV
ENV MYSQL_VERSION 5.7 #设置常量RUN apt-get install -y mysql-server="${MYSQL_VERSION}" \ && rm -rf /var/lib/apt/lists/* #引用常量 ps:尽量使用环境变量,利于维护
7.CMD
(1)特点-》容器启动使默认执行的命令-》如果docker run指定了其他命令,CMD会被忽略docker run -it [image] /bin/bash则CMD会被忽略-》如果定义多个cmd,则只有最后一个会被执行
(2)例子
Dockerfile内容FROM centosENV name DockerCMD echo "hello $name"然后[vagrant@localhost docker-entrypoint-shell]$ docker build -t spark/centos-cmd-shell .Sending build context to Docker daemon 3.072kBStep 1/3 : FROM centos ---> 9f38484d220fStep 2/3 : ENV name Docker ---> Using cache ---> b2c5c3efb231Step 3/3 : CMD echo "hello $name" ---> Running in 13d960536fd8Removing intermediate container 13d960536fd8 ---> 051e163b0309Successfully built 051e163b0309Successfully tagged spark/centos-cmd-shell:latest[vagrant@localhost docker-entrypoint-shell]$ docker image lsREPOSITORY TAG IMAGE ID CREATED SIZEspark/centos-cmd-shell latest 051e163b0309 8 seconds ago 202MBspark/centos-exec latest 148b0c0780b0 2 hours ago 202MBspark/centos-shell latest 863515d94aba 2 hours ago 202MBspark/centos-vim-new latest e3e86df752b6 21 hours ago 357MBspark/hello-world latest d801c21d3e64 40 hours ago 857kBcentos latest 9f38484d220f 3 months ago 202MBhello-world latest fce289e99eb9 5 months ago 1.84kB[vagrant@localhost docker-entrypoint-shell]$ docker run spark/centos-cmd-shellhello Docker添加命令[vagrant@localhost docker-entrypoint-shell]$ docker run spark/centos-cmd-shell /bin/bash则不运行echo
8.ENTRYPOINT
(1)特点-》让容器一应用程序或者服务的形式运行-》不会被忽略,一定会执行
(2)实例
Dockerfile内容FROM centosENV name DockerENTRYPOINT echo "hello $name"[vagrant@localhost docker-entrypoint-shell]$ docker run spark/centos-shellhello Docker[vagrant@localhost docker-entrypoint-shell]$ docker run spark/centos-shell /bin/bashhello Docker
1.gitlib
https://github.com/docker-library2.官方语法
https://docs.docker.com/v17.09/engine/reference/builder/转载地址:http://ggygi.baihongyu.com/