(15)Docker之用Nginx實現SpringBoot應用的負載均衡簡單記錄
阿新 • • 發佈:2020-07-21
怎樣用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; resolver8.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 on127.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命令複製檔案,可以考慮容器卷的方式。