背景:在上篇 docker演示nginx反向代理 基础上继续
一、编写脚本
1. 分别编写load_balancing_8000.py、load_balancing_8001.py脚本(注意脚本对应端口分别为8000、8001)
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from flask import Flask
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def get_msg():
"""
curl -X GET 'http://192.168.1.110:8000/api'
"""
return "The server port is 8000"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
二、运行脚本
E:\Python\Python38\python3.exe F:/IdeaProjects/my-jooq/my-python/load_balancing_8000.py
* Serving Flask app "load_balancing_8000" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 936-026-506
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
E:\Python\Python38\python3.exe F:/IdeaProjects/my-jooq/my-python/load_balancing_8001.py
* Serving Flask app "load_balancing_8001" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 936-026-506
* Running on http://0.0.0.0:8001/ (Press CTRL+C to quit)
三、修改配置
1. 修改nginx.conf配置
# 定义Nginx运行的用户和用户组
user nginx;
# nginx进程数,通常设置成和cpu的数量相等
worker_processes 4;
# 全局错误日志定义类型,[debug | info | notice | warn | error | crit]
error_log /var/log/nginx/error.log warn;
# 进程pid文件
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;
include /etc/nginx/conf.d/*.conf;
upstream api_server {
# 负载均衡,默认使用轮询
server 192.168.1.110:8000;
server 192.168.1.110:8001;
}
server {
# 如果使用docker容器,必须暴露该端口
listen 8088;
server_name 172.20.228.138;
# location / {
# # 如果使用容器,可以使用容器本身的ip,可以使用docker0的ip,也可以使用宿主机ip
# # proxy_pass http://172.18.0.14:9200/;
# proxy_pass http://172.17.0.1:9200;
# # proxy_pass http://172.20.228.138:9200;
# index index.html index.htm index.jsp;
# }
location ~ ^/api {
proxy_pass http://api_server;
}
}
}
四、重启容器或者重新加载配置
五、查看结果
1. 打开浏览器,查看请求http://172.20.228.138:8088/api,多次刷新
2. 或者使用curl命令
从结果可以看出负载均衡成功,到此演示结束