dockerfile,相当于是一个文档,客户可以基于dockerfile生成新的容器
dockerfile仅仅是用来制作镜像的源码文件,是构建容器过程中的指令,docker能够读取dockerfile的指定进行自动构建容器,基于dockerfile制作镜像,每一个指令都会创建一个镜像层,即镜像都是多层叠加而成,因此,层越多,效率越低,创建镜像,层越少越好。因此能在一个指令完成的动作尽量通过一个指令定义。
例子:
Dockerfile:
FROM centos
RUN yum install -y vim
CMD echo "ok"
docker build -t centos-test .
命令解释:构建镜像 -t:为指定镜像名称 .为指定Dockerfile位置
docker run -it centos-test
ok
命令详解
1.FROM:指定基础镜像,必须是第一条指令
dockerfile:
FROM:centos ##指定一个基础镜像用于构建新镜像
2.RUN:编译镜像时运行的命令
dockerfile:
FROM:centos
RUN:touch 1.txt
docker build -t centos-test .
Sending build context to Docker daemon 5.632kB
Step 1/2 : FROM centos
---> 470671670cac
Step 2/2 : RUN touch 1.txt
---> Running in 252294ebf174
Removing intermediate container 252294ebf174
---> e616ce0dbfaa
Successfully built e616ce0dbfaa
Successfully tagged centos-test:latest
ls
1.txt
3.CMD:容器启动时运行命令
dockerfile:
FROM centos
CMD echo "hello word"
docker run -it centos-test
hello word
4.LABEL:给镜像指定标签
dockerfile:
FROM centos
LABEL author="mrlxxx"
docker build -t centos-test .
docker inspect -f {{.Config.Labels.author}} ce7f
mrlxxx
5.EXPOSE:声明容器运行时端口
dockerfile:
FROM nginx
EXPOSE 80/tcp
6.COPY:复制命令
FROM nginx
copy index.html /usr/share/nginx/html/index.html
##cat index.html
hello word
----------------------------------------------
docker build -t nginx-1 .
curl 192.168.1.10:80
hello word
7.ADD 更高级的复制命令
##用法一样,ADD可以直接使用URL进行复制(下载),复制tar包时会直接解压
FROM centos
ADD http://nginx.org/download/nginx-1.11.3.tar.gz /tmp
--------------------------------------------
ls /tmp
ks-script-_srt3u3c ks-script-gpqu_kuo nginx-1.11.3.tar.gz
8.ENTRYPOINT:容器启动时运行命令
##跟CMD一样,但是当两个命令都存在时,CMD的参数会传入到ENTRYPOINT
dockerfile:
FROM centos
CMD ["/tmp","/root"]
ENTRYPOINT ["ls"]
-----------------------------
docker run -it centos-test
/root:
anaconda-ks.cfg anaconda-post.log original-ks.cfg
/tmp:
ks-script-_srt3u3c ks-script-gpqu_kuo
9.user:设置用户
dockerfile:
FROM centos
RUN useradd t1
USER t1
-----------------------------------
[t1@43e9a681f9ad /]$ id
uid=1000(t1) gid=1000(t1) groups=1000(t1)
10.WORKDIR:设置工作目录
dockerfile:
FROM centos
WORKDIR /a
CMD pwd
##在dockerfile中不能像脚本一样使用CD 移动工作目录
docker run -it centos-test
/a
11.ARG:设置变量(构建时使用)
dockerfile:
FROM centos
ARG test1="ok"
RUN echo $test1
-----------------------------------
docker build -t centos-test .
Sending build context to Docker daemon 5.632kB
Step 1/3 : FROM centos
---> 470671670cac
Step 2/3 : ARG test1="ok"
---> Running in 4c94df379698
Removing intermediate container 4c94df379698
---> 424451e02fcf
Step 3/3 : RUN echo $test1
---> Running in 5a933a8be6c3
ok
Removing intermediate container 5a933a8be6c3
---> 7b4cc81273b3
Successfully built 7b4cc81273b3
Successfully tagged centos-test:latest