docker

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > 云和虚拟化 > docker > Dockerfile CMD与ENTRYPOINT

Dockerfile的CMD与ENTRYPOINT的区别

作者:芝麻\n

CMD和ENTRYPOINT的区别在于CMD提供默认的执行指令,而ENTRYPOINT定义容器启动时运行的命令,下面就来详细的介绍一下这两者的区别,具有一定的参考价值,感兴趣的可以了解一下

CMD和ENTRYPOINT

我们先来试一下构建以下这个Dockerfile,并运行

FROM centos

CMD ["ls","-a"]

构建

[root@zhima lizhi]# docker build -t mycentos .
Sending build context to Docker daemon  17.92kB
Step 1/2 : FROM centos
 ---> 5d0da3dc9764
Step 2/2 : CMD ["ls","-a"]
 ---> Running in a1e70a05d8dd
Removing intermediate container a1e70a05d8dd
 ---> 00433fd4c299
Successfully built 00433fd4c299
Successfully tagged mycentos:latest

运行

[root@zhima lizhi]# docker run -it --name "centos1" mycentos
.   .dockerenv	dev  home  lib64       media  opt   root  sbin	sys  usr
..  bin		etc  lib   lost+found  mnt    proc  run   srv	tmp  var

可以发现,进入容器之后,就执行了ls -a命令

我们尝试一下在启动的时候加入一些参数

[root@zhima lizhi]# docker run -it --name "centos2" mycentos -l
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "-l": executable file not found in $PATH: unknown.

我们发现容器并没有执行ls -al,而是直接报错了

其实这就是CMD的特性,当我在启动容器的时候添加了一个CMD后

镜像中定义的CMD就被覆盖掉了

单独的-l当然会报错了

我们来看一下使用ENTRYPOINT会怎么样

修改Dockerfile

FROM centos

ENTRYPOINT ["ls","-a"]

重新构建

[root@zhima lizhi]# docker build -t mycentos .
Sending build context to Docker daemon  17.92kB
Step 1/2 : FROM centos
 ---> 5d0da3dc9764
Step 2/2 : ENTRYPOINT ["ls","-a"]
 ---> Running in 22ef40dea625
Removing intermediate container 22ef40dea625
 ---> 73a3d51b4d84
Successfully built 73a3d51b4d84
Successfully tagged mycentos:latest

运行容器

[root@zhima lizhi]# docker run -it --name "centos1" mycentos -l
total 56
drwxr-xr-x   1 root root 4096 Jul 14 08:52 .
drwxr-xr-x   1 root root 4096 Jul 14 08:52 ..
-rwxr-xr-x   1 root root    0 Jul 14 08:52 .dockerenv
lrwxrwxrwx   1 root root    7 Nov  3  2020 bin -> usr/bin
drwxr-xr-x   5 root root  360 Jul 14 08:52 dev
drwxr-xr-x   1 root root 4096 Jul 14 08:52 etc
drwxr-xr-x   2 root root 4096 Nov  3  2020 home
lrwxrwxrwx   1 root root    7 Nov  3  2020 lib -> usr/lib
lrwxrwxrwx   1 root root    9 Nov  3  2020 lib64 -> usr/lib64
drwx------   2 root root 4096 Sep 15  2021 lost+found
drwxr-xr-x   2 root root 4096 Nov  3  2020 media
drwxr-xr-x   2 root root 4096 Nov  3  2020 mnt
drwxr-xr-x   2 root root 4096 Nov  3  2020 opt
dr-xr-xr-x 191 root root    0 Jul 14 08:52 proc
dr-xr-x---   2 root root 4096 Sep 15  2021 root
drwxr-xr-x  11 root root 4096 Sep 15  2021 run
lrwxrwxrwx   1 root root    8 Nov  3  2020 sbin -> usr/sbin
drwxr-xr-x   2 root root 4096 Nov  3  2020 srv
dr-xr-xr-x  13 root root    0 Jan 29 10:27 sys
drwxrwxrwt   7 root root 4096 Sep 15  2021 tmp
drwxr-xr-x  12 root root 4096 Sep 15  2021 usr
drwxr-xr-x  20 root root 4096 Sep 15  2021 var

可以发现,容器执行的是ls -al-l指令被追加给了ENTRYPOINT定义的语句

到此这篇关于Dockerfile的CMD与ENTRYPOINT的区别的文章就介绍到这了,更多相关Dockerfile CMD与ENTRYPOINT内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文