docker nginx容器的均衡负载
创建三个docker容器以实现nginx的负载均衡
编写nginx的dockfile
[root@docker nginx]# cat Dockerfile
FROM nginx
RUN echo 'i am container 1' > /usr/share/nginx/html/index.html
EXPOSE 80
CMD ["nginx","-g","daemon off;"]
[root@docker nginx]#
创建自定义网络
docker network create --driver bridge --subnet 192.168.13.0/24 --gateway 192.168.13.1 mqynet
启动两个容器
docker run -d --name docker01 -v modify:/usr/share/nginx/html --net mqynet -p 801:80 mqynginx
docker run -d --name docker02 -v modify2:/usr/share/nginx/html --net mqynet -p 802:80 mqynginx
--net 指定为自定义网络
修改容器2的内容
[root@docker _data]# pwd
/var/lib/docker/volumes/modify2/_data
[root@docker _data]# cat index.html
i am container 2
[root@docker _data]#
balancer dockerfile
[root@docker nginx]# cat balancer
FROM nginx
RUN echo 'i am container 1' > /usr/share/nginx/html/index.html
EXPOSE 80
RUN apt update && apt install -y vim && apt install net-tools -y
CMD ["nginx","-g","daemon off;"]
进入balancer并安装ping命令
apt-get install inetutils-ping
尝试ping通容器名
ping docker02
修改balancer配置文件
upstream web{
server docker01;
server docker02;
}
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
proxy_pass http://web; #添加此location
}
重读配置文件
docker restart balancer
ctrl + q + p
暂停镜像
提交镜像
docker commit balancer balancer:2.0
再次生成balancer容器
docker run -d --name balancer -p 803:80 --net mqynet balancer:2.0
验证负载均衡
[root@docker docker]#
[root@docker docker]# curl localhost:803
i am container 2
[root@docker docker]# curl localhost:803
i am container 1
[root@docker docker]# curl localhost:803
i am container 2
[root@docker docker]# curl localhost:803
i am container 1
上传balancer镜像到云
登录云
docker login --username=sux registry.cn-sxy/balancer:2.0
给镜像打标签
docker tag f6e2cefb3ef0 registry.cn-sxy/balancer:2.0
docker push registry.cn-sxy/balancer:2.0
使用其他用户拿到镜像
docker pull registry.cn-sxy/balancer:2.0
关于挂载
modify:/usr/share/nginx/html 具名挂载
/xxx:/usr/share/nginx/html 路径挂载 (容器路径里的东西会被外面的文件直接覆盖)