nginx通过获取环境变量实现动态IP代理配置

方案一(推荐):

转:https://blog.csdn.net/jiangqian6481/article/details/78310247

方案二:

下载nginx镜像

使用官方带perl模块(ngx_http_perl_module)的nginx镜像

docker pull nginx:perl

修改配置

nginx.conf配置

user root;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
 
//环境变量
env PROXY_HOST;
env PROXY_IP;

load_module modules/ngx_http_perl_module.so;
events {
 	use epoll;
 	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;
 
	#运用perl获取环境变量赋值
	perl_set $PROXY_HOST 'sub { return $ENV{"PROXY_HOST"}; }';
	perl_set $PROXY_IP 'sub { return $ENV{"PROXY_IP"}; }';

	include /etc/nginx/conf.d/*.conf;
}

重点:

env PROXY_HOST;
env PROXY_IP;

perl_set $PROXY_HOST 'sub { return $ENV{"PROXY_HOST"}; }';
perl_set $PROXY_IP 'sub { return $ENV{"PROXY_IP"}; }';

default.conf配置

server {
    listen       80;
    server_name  localhost;
    charset utf-8;
    #access_log  /var/log/nginx/host.access.log  main;
    location /{
        proxy_pass   http://$PROXY_IP:$PROXY_HOST/;
    }
}

重点:

proxy_pass   http://$PROXY_IP:$PROXY_HOST/;

修改官方镜像配置或基于重新制作

重做的Dockerfile文件

FROM nginx:perl
COPY nginx.conf /etc/nginx/
COPY default.conf /etc/nginx/conf.d/

使用

指定容器的 PROXY_HOST 与 PROXY_IP 等环境变量即可

你可能感兴趣的:(nginx)