【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

发现服务又正常了!!!

相关推荐
栗子~~2 分钟前
Milvus docker-compose 部署
docker·容器·milvus
椰汁菠萝1 小时前
ubuntu下免sudo执行docker
ubuntu·docker·免sudo
紫璨月1 小时前
nginx反向代理的bug
运维·nginx·bug
没有名字的小羊1 小时前
2.安装Docker
运维·docker·容器
xiezhr2 小时前
50 个常用 Docker 命令
运维·docker·容器
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
小生云木10 天前
Linux离线编译安装nginx
linux·运维·nginx
API开发10 天前
苹果芯片macOS安装版Homebrew(亲测) ,一键安装node、python、vscode等,比绿色软件还干净、无污染
vscode·python·docker·nodejs·openssl·brew·homebrew
进击的码码码码N10 天前
Docker 镜像加速
运维·docker·容器
Q_w774210 天前
基于 Docker 的服务部署探索(Day 2)
运维·docker·容器