通过nginx部署静态网站
容器的端口映射
要访问容器内部的80端口,就需要在运行容器时设置容器的端口映射
docker run -P -p
-P (--publish-all=true) 将为容器暴露的所有端口进行映射
-p (--publish=[]) 指定映射某些端口
四种映射容器端口的方式:
containerPort
docker run -p 80 -it IMAGE /bin/bash 宿主机端口随机映射
hostPort:containerPort
docker run -p 8080:80 -it IMAGE /bin/bash 宿主机端口8080映射到容器80端口
ip::containerPort
docker run -p 0.0.0.0:80 -it IMAGE /bin/bash 指定宿主机ip
ip:hostPort:containerPort
docker run -p 0.0.0.0:8080:80 -it IMAGE /bin/bash 宿主机ip,端口和容器端口都指定
Nginx部署流程
创建映射80端口的交互式容器
安装Nginx
安装文本编辑器vim
创建静态页面
修改Nginx配置文件
运行Nginx
验证访问
1,创建映射80端口的交互式容器
[root@localhost packages]# docker run -p 80 --name web -it ubuntu /bin/bash
2,安装Nginx
root@fb5cbc0370e4:/# apt-get install -y nginx Reading package lists... Done Building dependency tree Reading state information... Done
3,安装文本编辑器vim
root@fb5cbc0370e4:/# apt-get install -y vim Reading package lists... Done Building dependency tree Reading state information... Done
4,创建静态页面
root@fb5cbc0370e4:/usr/local# mkdir -p /var/www/html root@fb5cbc0370e4:/usr/local# cd /var/www/html/ root@fb5cbc0370e4:/var/www/html# echo "<h1>nginx in docker</h1>" >> index.html
5,修改nginx配置文件
root@fb5cbc0370e4:/var/www/html# whereis nginx nginx: /usr/sbin/nginx /etc/nginx /usr/share/nginx /usr/share/man/man1/nginx.1.gz root@fb5cbc0370e4:/etc/nginx/sites-enabled# vim /etc/nginx/sites-enabled/default ###修改nginx默认发布目录为我们创建的目录 root /var/www/html; ###
6,运行容器中的nginx
root@fb5cbc0370e4:/etc/nginx/sites-enabled# nginx root@fb5cbc0370e4:/etc/nginx/sites-enabled# ps -ax |grep nginx 626 ? Ss 0:00 nginx: master process nginx 627 ? S 0:00 nginx: worker process 628 ? S 0:00 nginx: worker process 629 ? S 0:00 nginx: worker process 630 ? S 0:00 nginx: worker process 633 ? S+ 0:00 grep --color=auto nginx 使用ctrl+p ctrl+q将容器打入后台运行 [root@localhost packages]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fb5cbc0370e4 ubuntu "/bin/bash" 9 minutes ago Up 9 minutes 0.0.0.0:32768->80/tcp web
7,访问验证
[root@localhost packages]# curl localhost:32768 //访问成功 <h1>nginx in docker</h1>
查看容器的ip地址
[root@localhost packages]# docker inspect web ###可以看到如下内容,里面有docker网络的所有信息,包括IP地址 "Networks": { "bridge": { "IPAMConfig": null, "Links": null, "Aliases": null, "NetworkID": "251770d50c72ffe6c5ec08e2b603623658f4251659c44134324d9d7891655f01", "EndpointID": "ce383c2cdba60c5f915d2d3d6e9b3551dcbbf21b84f1c39ea760ec4594bde516", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:02" } [root@localhost packages]# curl 172.17.0.2 //直接访问容器IP,也可以得到结果 <h1>nginx in docker</h1>
**当重新启动容器时,分配的ip地址和宿主机的端口映射(如果映射时只指定了容器端口)都会改变