docker(7):实战--安装nginx并实现反向代理
基本概念
反向代理:客户端向反向代理的命名空间中的内容发送普通请求,接着反向代理将推断向何处(原始服务器)转交请求,并将获得的内容返回给客户端。
负载均衡:当请求过多,单个服务器难以负荷时,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上。
- 拉取镜像
docker pull nginx
- 创建要挂载的配置文件
vim nginx.conf
内容如下:
user nginx;
worker_processes auto;error_log /var/log/nginx/error.log notice;
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;
}
-
设置反向代理和负载均衡
假设我们有个spring服务,启动了两个实例,端口分别为10010和10086。现在想让nginx对我们两个实例进行反向代理,并能够做简单的负载均衡。
修改配置文件增加反向代理配置:
user nginx;
worker_processes auto;error_log /var/log/nginx/error.log notice;
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;# 注意这里默认的配置注释掉,否则80端口会使用默认的配置# include /etc/nginx/conf.d/*.conf;# 代理负载均衡,默认是轮询upstream proxytest {server localhost:10010;server localhost:10086;}server {listen 80;server_name localhost;# 使用代理location / {# proxytest是上面我们配置的upstream的名字proxy_pass http://proxytest;}}}
- 启动nginx
docker run --name nginx-proxy -p 80:80 -v /docker/nginx/nginx.conf:/etc/nginx/nginx.conf -d nginx
这样就实现了使用nginx代理localhost:10010和localhost:10086两个服务了。这两个属于同一个spring服务的不同端口。