目录
1 下载nginx
2 准备一个简单的项目架构
3 idea启动多个服务实例
4 修改nginx的配置文件
5 测试访问
1 下载nginx
官网地址:https://nginx.org/en/download.html
可以选择自己想要的操作系统和版本,小编这里使用的是windows的1.24版本
解压后在文件夹目录下点击nginx.exe,这里应该会一闪而过,不用担心,应该是启动成功了,我们可以鼠标右键打开任务管理器输入nginx
然后输入127.0.0.1出现这个页面,表示nginx已经安装成功
2 准备一个简单的项目架构
这里我们就正常启动我们的项目,源端口8088
3 idea启动多个服务实例
快捷键ctrl + d复制一个实例然后修改端口后启动,这样就可以启动多个实例了。
这里我启动了三个实例,端口分别是8086 8087 8088
4 修改nginx的配置文件
文件路径在nginx:tag/conf/nginx.conf 这里是我的全部配置文件,你们可以自定义修改
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include 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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# 定义负载均衡的后端服务器
upstream backend_servers {
server 127.0.0.1:8086; # 后端服务器1
server 127.0.0.1:8087; # 后端服务器2
server 127.0.0.1:8088; # 后端服务器3
}
server {
listen 8888;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
# location / {
# root html;
# index index.html index.htm;
# }
location / {
proxy_pass http://backend_servers; # 将请求转发到upstream定义的服务器组
proxy_set_header Host $host; # 保持请求头的Host
proxy_set_header X-Real-IP $remote_addr; # 保持客户端真实IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 传递客户端真实IP链
proxy_set_header X-Forwarded-Proto $scheme; # 保持协议(http/https)
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
然后重新启动nginx ,你也可以自定义一些负载均衡策略:轮询、最小连接数这些。
5 测试访问
此时我们通过访问127.0.0.1:8888/路径的一些资源就会代理到127.0.0.1:8086/8087/8088 上
此时我们访问127.0.0.1:8888/captchaImage 注:这里替换成自己的请求路径
返回控制台看见每个服务都有输出