当前使用centos7系统
1、安装nginx
参考https://blog.whsir.com/post-2078.html
2、docker拉取nginx镜像
docker pull nginx
|---|-------------------| | 1 | docker pull nginx |
3、创建两个目录
mkdir -p /data/demo1 mkdir -p /data/demo2
|-----|-------------------------------------------| | 1 2 | mkdir -p /data/demo1 mkdir -p /data/demo2 |
分别在两个目录下创建两个index.html,demo1下index.html内容为this is demo1,demo2下index.html内容为this is demo2
4、通过docker运行两个nginx的容器,并将目录映射到刚刚创建的目录中
容器中80端口映射到8081
docker run --name nginx-demo1 -d -p 8081:80 -v /data/demo1:/usr/share/nginx/html nginx
|---|----------------------------------------------------------------------------------------| | 1 | docker run --name nginx-demo1 -d -p 8081:80 -v /data/demo1:/usr/share/nginx/html nginx |
容器中80端口映射到8082
docker run --name nginx-demo2 -d -p 8082:80 -v /data/demo2:/usr/share/nginx/html nginx
|---|----------------------------------------------------------------------------------------| | 1 | docker run --name nginx-demo2 -d -p 8082:80 -v /data/demo2:/usr/share/nginx/html nginx |
5、修改当前主机nginx配置文件,设置upstream
http { ...... upstream whsirserver { server 192.168.0.80:8081 weight=1; server 192.168.0.80:8082 weight=1; } server { ...... location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://whsirserver; } ...... } ...... }
|----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | http { ...... upstream whsirserver { server 192.168.0.80:8081 weight=1; server 192.168.0.80:8082 weight=1; } server { ...... location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://whsirserver; } ...... } ...... } |
6、保存退出重启nginx
nginx -t systemctl restart nginx
|-----|----------------------------------| | 1 2 | nginx -t systemctl restart nginx |
7、验证
此时浏览器输入当前IP或者域名,刷新页面时,就会看到this is demo1和this is demo2内容是来回切换的,即表示nginx负载均衡配置成功