Loading

做了反向代理和负载均衡的nginx配置文件简单示例(nginx.conf) HTTP负载均衡/TCP负载均衡

在默认配置的基础上,启用http反向代理和负载均衡。同时配置了TCP反向代理和负载均衡。
另外,能够实现每天生成一个日志文件,日志用json格式,日志中的日期重新格式化成 yyyy-MM-ddTHH:mm:ss.ZZZ这样子。
nginx version 1.27.3

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;

    ###### 时间相关的几个变量 ######
    # https://serverfault.com/questions/732395/can-nginx-log-time-in-iso-8601-format-but-include-milliseconds
    # https://thatsamguy.com/nginx-iso8601-time-format/
	#  just the date and time part of $time_iso8601 e.g. 2021-05-21T10:26:19
	map $time_iso8601 $p1_datetime {
		~([^+]+) $1;
    }
	#  just the timezone part of $time_iso8601 e.g. +00:00
	map $time_iso8601 $p2_timezone {
		~\+([0-9:]+)$ $1;
    }
	#  just the millisecond part of $msec e.g. 123 extracted from 1621594635.123
	map $msec $millisec {
		~\.([0-9]+)$ $1;
    }
    ###### 时间相关的几个变量 ######
    
    # 用json格式记录日志
	log_format json_logger escape=json
	'{'
		'"time":"$p1_datetime.$millisec",'
		'"remote_addr":"$remote_addr",'
		'"remote_user":"$remote_user",'
		'"request":"$request",'
		'"status":"$status",'
		'"body_bytes_sent":"$body_bytes_sent",'
		'"http_referer":"$http_referer",'
		'"http_user_agent":"$http_user_agent",'
		'"http_x_forwarded_for":"$http_x_forwarded_for"'
	'}';
    
    # 这个变量给下面access_log日志文件的时候用,确保每天创建一个日志文件
	map $time_iso8601 $logdate {
		'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
		default    'date-not-found';
    }
	
    access_log  logs/http_json_access_$logdate.log  json_logger;
	error_log  logs/http_json_error.log;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
	upstream backend {
		ip_hash;
        server www.example.com:80;
        server www2.example.com:80;
        #server www3.example.com:80 backup;
    }
	
    server {
        listen       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # 默认配置
		#location / {
        #    root   html;
        #    index  index.html index.htm;
        #}
		
		# 改成load balance
		location / {
			proxy_pass http://backend;
		}

		# 在线状态页
		location /nginx_status {
			stub_status on;
			access_log off;
			
			allow 127.0.0.1;
            allow ::1;  # 对于IPv6地址
            deny all;
		}

        #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;
    #    }
    #}

}

stream {
	###### 时间相关的几个变量 ######
    # https://serverfault.com/questions/732395/can-nginx-log-time-in-iso-8601-format-but-include-milliseconds
    # https://thatsamguy.com/nginx-iso8601-time-format/
	#  just the date and time part of $time_iso8601 e.g. 2021-05-21T10:26:19
	map $time_iso8601 $p1_datetime {
		~([^+]+) $1;
    }
	#  just the timezone part of $time_iso8601 e.g. +00:00
	map $time_iso8601 $p2_timezone {
		~\+([0-9:]+)$ $1;
    }
	#  just the millisecond part of $msec e.g. 123 extracted from 1621594635.123
	map $msec $millisec {
		~\.([0-9]+)$ $1;
    }
    ###### 时间相关的几个变量 ######

    # 用json格式记录日志,这里支持的字段,跟http里面的还不完全一致,有些http支持的,这里不支持,反之亦然
	log_format json_logger escape=json
	'{'
		'"time":"$p1_datetime.$millisec",'
		'"remote_addr":"$remote_addr",'
		'"protocol":"$protocol",'
		'"status":"$status",'
		'"bytes_sent":"$bytes_sent",'
		'"bytes_received":"$bytes_received",'
		'"session_time":"$session_time",'
		'"upstream_addr":"$upstream_addr",'
		'"upstream_bytes_sent":"$upstream_bytes_sent",'
		'"upstream_bytes_received":"$upstream_bytes_received",'
		'"upstream_connect_time":"$upstream_connect_time"'
	'}';

    # 这个变量给下面access_log日志文件的时候用,确保每天创建一个日志文件
	map $time_iso8601 $logdate {
		'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
		default    'date-not-found';
    }
	
    access_log logs/tcp_json_access_$logdate.log json_logger; #buffer=32k;
    error_log logs/tcp_json_error.log;
	open_log_file_cache off;	#当设置为off时,Nginx不会在启动时打开所有的日志文件,也不会追踪它们的打开状态。这意味着如果日志文件在运行时被重命名或删除,Nginx可能不会立即检测到这些变化,直到下一次尝试写入日志时。

    upstream backend {
        server 10.12.0.21:5678 weight=1 max_fails=3 fail_timeout=10s;#在单位周期为10s钟内,中达到3次连接失败,那么接将把节点标记为不可用,并等待下一个周期(同样时常为fail_timeout)再一次去请求,判断是否连接是否成功
        server 10.12.0.22:5678 weight=1 max_fails=2 fail_timeout=10s;
        server 10.12.0.23:5678 backup; # 备用服务器
    }

    server {
        listen 5678;
        proxy_pass backend;
        #proxy_protocol on; # 启用 PROXY protocol ,需要后端服务器也支持proxy protocol才行,否则的话,能ping通,但是请求会失败
        #proxy_timeout 3s; # 设置代理超时时间
    }
}


参考资料

posted @ 2024-12-10 17:39  asashadow  阅读(47)  评论(0编辑  收藏  举报