Docker中EXPOSE参数的一点思考
前言
在Dockerfile中有EXPOSE关键字;
在docker run命令中有--expose参数;
究竟这个有什么作用呢?
探究
docker -v
# Docker version 20.10.0
# 启动一个http服务容器
docker run -d python:3.9.4-slim-buster python -m http.server
# 启动一个带有curl的容器
docker run -it yauritux/busybox-curl /bin/sh
# 在busybox容器中 curl 172.17.x.x:8000 能访问http服务
# 宿主机中亦是如此
说明在没有使用EXPOSE,也没有使用--expose,但依然可以在宿主机或其他镜像中访问到http服务器;
开始对这个"端口暴露"产生疑问,通过查阅资料,大概是因为Docker在发展过程中,曾经把这个参数作为服务暴露的端口,如果不写,则在镜像之外无法访问到服务,具体可以看这个帖子,stackoverflow上讨论expose在被采纳的回答中,有人评论这已经是过时的用法,下面的回答才是真正的答案;同样也有人做了实验得出是否能访问服务和"端口暴露"没有关系。
在官方文档中有这样一段话
The docker network command supports creating networks for communication among containers without the need to expose or publish specific ports, because the containers connected to the network can communicate with each other over any port. For detailed information, see the overview of this feature.
总结
- 在Dockerfile中写上EXPOSE有一定的提示作用,可以让人明白该服务大致是什么服务;
- 在docker run中使用-P参数,可以将暴露的端口随机映射到宿主机中,实现端口映射。
- 总之老版本和新版本的不同也不再深究,保证新版本中的服务正常运转即可,关于Docker中网络知识还有太多需要学习的,道阻且长啊!
浙公网安备 33010602011771号