(15)Docker之用Nginx实现SpringBoot应用的负载均衡简单记录

  怎样用Docker部署SpringBoot应用请参考上篇文章,本文假设已经部署了两个SpringBoot应用:

  访问:http://192.168.43.151:8080/user/test 输出“测试1”

  访问:http://192.168.43.151:8081/user/test 输出“测试2”

  下面说一下怎么安装Nginx,以及实现两个应用的负载,本文采用简单轮询。

  1、安装Nginx

  1)安装镜像

  查找镜像

docker search nginx

  拉取镜像

docker pull nginx

  说明:拉取的最新镜像。ps:之前不知道怎么误删了/var/lib/nginx下的tmp目录,导致无法拉取,重建后好了。

  2)根据镜像,启动构建容器

docker run -d -p 80:80 --name nginx_upstream nginx

  2、准备Nginx配置文件

  编写负载均衡文件upstream_test.conf

upstream myLoad {
    server 192.168.43.151:8080;
    server 192.168.43.151:8081;
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    access_log  /var/log/nginx/test_proxy.access.log  main;
    resolver  8.8.8.8;
    
    location / {
        proxy_pass http://myLoad;
    }

    #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   /usr/share/nginx/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;
    #}
}

  修改主配置文件nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
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/upstream_test.conf;
}

  注意:红色字是添加或者修改的部分

  3、将配置文件放到容器中

docker cp /usr/local/mystore/dockerfile/nginx/conf/nginx.conf d3e3f77036d0:/etc/nginx/nginx.conf
docker cp /usr/local/mystore/dockerfile/nginx/conf/conf.d/upstream_test.conf d3e3f77036d0:/etc/nginx/conf.d/upstream_test.conf

  【格式】docker cp 宿主机目录 容器ID:容器目录

  重新启动容器

docker restart nginx_upstream

  4、测试

  浏览器输入:http://192.168.43.151/user/test 不停刷新,发现轮询输出 “测试1”、“测试1”,测试 成功!

  备注

  如果将配置文件cp到容器中,重启容器失败,可以重新cp一个正确的覆盖或者直接重新run一个容器。

  如果不想执行cp命令复制文件,可以考虑容器卷的方式。

 

 

  

上一篇:nginx配置本地服务-如图片服务器


下一篇:nginx负载均衡