【Docker】Docker容器实战部署多个Nginx实现负载均衡和高可用

文章目录

前言

Docker下部署多个Nginx进行负载均衡,我这次实操的思路是使用三个Nginx。其中一个Nginx起负载均衡的作用,叫做nginx-lb,单独一个配置文件。另外2个Nginx起真正的转发作用,叫做nginx1nginx2,他们共享同一个配置文件,思路图如下。

接下来我们直接进行实操演示。

下载Nginx
shell 复制代码
docker pull nginx:1.20
复制出配置文件
第一步:启动容器
shell 复制代码
root@735aa48ca36e:/# docker run -d --name test-nginx nginx:1.20

第二步:复制配置到宿主机

shell 复制代码
#复制文件出来到宿主机
docker cp test-nginx:/etc/nginx/ /home/nginx/
docker cp test-nginx:/var/log/nginx /home/nginx/nginx/logs
#专门再复制一份出来给nginx-lb使用
docker cp test-nginx:/etc/nginx/ /home/nginx/lb
修改配置
nginx-lb里的nginx.conf
nginx 复制代码
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}




http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
	
	#重点以下配置
	upstream nginx-lb{
	   server 192.168.40.128:10086; #nginx1
	   server 192.168.40.128:10010; #nginx2
    }
	
	server {
		listen       80;
		listen  [::]:80;
		server_name  localhost;

		#access_log  /var/log/nginx/host.access.log  main;

		location / {
			proxy_pass http://nginx-lb; #负载到nginx1 和 nginx2 上
		}

		error_page   500 502 503 504  /50x.html;
		location = /50x.html {
			root   /usr/share/nginx/html;
		}
	}
	

    #include /etc/nginx/conf.d/*.conf;
}
启动容器
启动nginx1
shell 复制代码
docker run -d --name nginx1 -v /home/nginx/nginx:/etc/nginx -p 10086:80 nginx:1.20
启动nginx2
shell 复制代码
docker run -d --name nginx2 -v /home/nginx/nginx:/etc/nginx -p 10010:80 nginx:1.20
启动nginx-lb
shell 复制代码
docker run -d --name nginx-lb  -v /home/nginx/lb:/etc/nginx -p 10000:80 nginx:1.20
演示效果

停止掉其中一个nginx

shell 复制代码
docker stop nginx1

继续访问http://192.168.40.128:10000,发现还是正常。

继续停掉另一个nginx

shell 复制代码
docker stop nginx2

这时候访问,会发现提示不支持服务了。

我们再重新启动其中一个nginx

shell 复制代码
docker start nginx1

发现服务又正常了!!!

相关推荐
大G哥2 小时前
记一次K8S 环境应用nginx stable-alpine 解析内部域名失败排查思路
运维·nginx·云原生·容器·kubernetes
妍妍的宝贝2 小时前
k8s 中微服务之 MetailLB 搭配 ingress-nginx 实现七层负载
nginx·微服务·kubernetes
大道归简3 小时前
Docker 命令从入门到入门:从 Windows 到容器的完美类比
windows·docker·容器
zeruns8023 小时前
如何搭建自己的域名邮箱服务器?Poste.io邮箱服务器搭建教程,Linux+Docker搭建邮件服务器的教程
linux·运维·服务器·docker·网站
爱跑步的程序员~3 小时前
Docker
docker·容器
疯狂的大狗4 小时前
docker进入正在运行的容器,exit后的比较
运维·docker·容器
长天一色4 小时前
【Docker从入门到进阶】01.介绍 & 02.基础使用
运维·docker·容器
伊玛目的门徒4 小时前
docker 搭建minimalist-web-notepad
运维·docker·notepad
叶北辰CHINA5 小时前
nginx反向代理,负载均衡,HTTP配置简述(说人话)
linux·运维·nginx·http·云原生·https·负载均衡
theo.wu7 小时前
使用Buildpacks构建Docker镜像
运维·docker·容器