1、部署 Nginx
经过之前的学习,我们已经掌握了 docker 的常用命令,现在就用这些命令完成一个简单的 nginx 环境搭建。
1. 在docker hub上搜索nginx版本
2. 下载 docker pull nginx
3. 运行 docker run -d --name mynginx -p 12345:80 nginx
4. 测试 curl localhost:12345
2、我们是如何访问到容器的?
上面分别使用 curl 命令和外部浏览器访问 nginx 都返回了正确结果,说明部署没有问题。
接下来再讨论一个小问题,我们是如何访问到容器的,中间经过了哪些环节?
请看下图:
从上图中可以看出,首先浏览器先访问虚拟机的 12345 端口,此时虚拟机的防火墙先拦截,看 12345 端口是否开放。然而 12345 被 nginx 容器中的 80 端口映射,所以当我们访问虚拟机 12345 端口就能访问到容器内部。
此时如果再有一个 nginx 容器 2 也要映射 80 端口就只能选择 12345 之外,比如 12346。这样当访问虚拟机 12345 端口时访问的就是 nginx 容器,12346 端口时访问的就是 nginx 容器 2。
如果把两个容器都停止,则无法访问虚拟机 12345 和 12346 端口。
3、Commit 镜像,制作一个属于自己的镜像
之前都是通过官方镜像创建容器,可是有些官方镜像为了简约,缺少了很多东西。
比如 Tomcat 镜像,官方镜像在 webapp 下面没有任何东西,需要从 webapps.dist 文件夹下 copy,那能不能自定义一个 Tomcat 镜像,webapp 下默认就有 webapps.dist 中所有东西呢?
答案是肯定的,这需要使用 commit 命令。
docker commit -m="提交描述信息" -a="作者" 容器id 目标镜像名称:tag
1. 下载tomcat镜像
[root@localhost ~]#docker pull tomcat
1. 启动默认tomcat
[root@localhost ~]# docker run -d --name mytomcat -p 8080:8080 tomcat
2. 进入tomcat拷贝文件
[root@localhost ~]# docker exec -it 92337ba4b1 /bin/bash
3. cp文件
root@92337ba4b12d:/usr/local/tomcat# cp -r webapps.dist/* webapps
4. 提交镜像
[root@localhost ~]# docker commit -a="luojie" -m="add webapps" 92337ba4b12d lj_tomcat:1.0
5. 运行新镜像
[root@localhost ~]# docker run -d --name mylj_tomcat -p 8080:8080 lj_tomcat:1.0