编写Dockerfiles
指令
docker build
通过Dockerfile制作镜像
docker build [PATH] [-f Dockerfile]
其中PATH不写,默认执行指令的当前目录,不要用 /
,这样将导致整个操作系统复制到镜像中
ENV
定义环境变量
ENV abc=hello
ENV abc=bye def=$abc
ENV ghi=$ab
使用环境变量
WORKDIR ${foo} # WORKDIR /bar
ADD . $foo # ADD . /bar
COPY \$foo /quux # COPY $foo /quux
.dockerignore
# comment
*/temp*
*/*/temp*
temp?
RULE | Behavior |
---|
comment| Ignored.
/temp | Exclude files and directories whose names start with temp in any immediate subdirectory of the root. For example, the plain file /somedir/temporary.txt is excluded, as is the directory /somedir/temp.
//temp* | Exclude files and directories starting with temp from any subdirectory that is two levels below the root. For example, /somedir/subdir/temporary.txt is excluded.
temp? | Exclude files and directories in the root directory whose names are a one-character extension of temp. For example, /tempa and /tempb are excluded.
FROM 母镜像
FROM <image>[:<tag>] [AS <name>]
Dockerfile通过ARG设置编译变量,通过${xxxx}在编译过程中调用
ARG CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD /code/run-app
FROM extras:${CODE_VERSION}
CMD /code/run-extras
RUN 镜像制作指令
用于制作镜像过程之中,执行指令,比如拷贝文件,删除文件。
RUN [/bin/sh -c | cmd /S /C ]
linux下,默认采用 /bin/sh -c
window下,默认采用 cmd /S /C
RUN ["executable", "param1", "param2"]
不像shell form ,exec form 不用直接通过shell命令运行,比如 RUN [ "echo", "$HOME" ]就不会运行,如果希望exce from像shell form那样运行,必须写成RUN [ "sh", "-c", "echo $HOME" ]
CMD 容器启动默认执行脚本
- CMD ["executable","param1","param2"] (exec form, this is the preferred form)
- CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
- CMD command param1 param2 (shell form)
CMD 节点在Dockerfile只能有一个,如果有多个CMD的话,最后出现的CMD生效,其他的忽略
CMD节点目的是给容器提供一个默认的运行指令。
LABEL 镜像标签
示例
LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL version="1.0"
LABEL description="This text illustrates \
that label-values can span multiple lines."
EXPOSE 监听端口
EXPOSE <port> [<port>/<protocol>...]
EXPOSE 80/tcp
EXPOSE 80/udp
容器中定义好监听端口后,在docker run中如果不用 -p
重新指定监听端口,将直接默认端口映射出去
docker run -p 80:80/tcp -p 80:80/udp
ENV 镜像环境变量
ENV <key> <value>
ENV <key>=<value> ...
示例:
ENV myName="John Doe" myDog=Rex\ The\ Dog \
myCat=fluffy
ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy
在docker run中可以通过 --env 重写参数
docker run --env <key>=<value>
ADD
- ADD [--chown=
: ] ... - ADD [--chown=
: ] [" ",... " "] (this form is required for paths containing whitespace)
ADD hom* /mydir/ # adds all files starting with "hom"
ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt"
COPY
- COPY [--chown=
: ] ... - COPY [--chown=
: ] [" ",... " "] (this form is required for paths containing whitespace)
COPY hom* /mydir/ # adds all files starting with "hom"
COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt"
ENTRYPOINT
- ENTRYPOINT ["executable", "param1", "param2"] (exec form, preferred)
- ENTRYPOINT command param1 param2 (shell form)
WORKDIR
ENV DIRPATH /path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd