一,在服务器中搭建一个nginx服务器并启动:
$ yum -y install nginx
$ systemctl start nginx
$ netstat -tunlp | grep 80
二,在docker中从源中拉一下nginx的官方镜像,docker pull nginx,留着备用
docker pull nginx
三,在本地目录新建两个文件夹,我这里的新建在/newdata/test1,/newdata/test2/
mkdir -p /newdata/test1 /newdata/test2
四,分别在两个test文件夹中新建index.html来标志,在第一个html中输出nginx1,在第二个html中输出nginx2:
$ cd /newdata/test1/
$ cat >index.html
nginx-1
$ cd /newdata/test2/
$ cat >index.html
nginx-2
五, 通过docker运行两个nginx服务器的容器,并分别将静态目录映射到我们刚刚创建的目录中
$ docker run --name nginx-test1 -d -P -p 8080:80 -v /newdata/test1:/usr/share/nginx/html nginx
运行结果:70ecbd602c1ae299b955a5837c571c71ec426d2a1c58c4a12eec9804207b02
$ docker run --name nginx-test2 -d -P -p 8081:80 -v /newdata/test2:/usr/share/nginx/html nginx
运行结果:4bf093ef0539d6e3db35ff8b9e5e43f0318953f943b4da734a1da6eff05f426e
六,6.修改宿主机中的nginx的配置文件
在http{}中添加如下代码
upstream myweb { #myweb 为自定义名字
#ip_hash; #开启则代表用ip地址的形式来分配,可解决sesson问题
server 170.17.0.4:8080 weight=1; #weight越大,权重越高,被分配的几率越大
server 170.17.0.4:8080:8081 weight=1; #我全部在本机,因此用了本地的ip,只要相应换成对应的ip或者域名即可
}
tail -6 /etc/nginx/nginx.conf
也是打开这个nginx配置文件
vim /etc/nginx/nginx.conf
在http{}的server{}里的location下添加下面内容:
location / {
#如果服务器要获取客户端真实IP,可以用下三句设置主机头和客户端真实地址
#proxy_set_header Host $host;
#proxy_set_header X-Real-IP $remote_addr;
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://myweb; #myweb为之前在nginx.conf中upstream后定义的名字
}
我自己的配置是这样:
location / {
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://myweb;
}
七,保存后退出,重启服务器
systemctl restart nginx
八,通过浏览器输入当前域名,并刷新页面,有时输出nginx1,有时输出nginx2,配置成功:
一定要注意两个容器都是开起来的