獲取基礎容器的配置
首先用docker cp 65ed8999c4d3:/etc/nginx/nginx.conf ~/nginx_temp/conf
命令,把容器中/etc/nginx/nginx.conf
文件和/etc/nginx/conf.d/default.conf
文件,複製到本機~/nginx_temp
(ps:可以根據情況改變配置)中
修改配置
爲達到負載均衡目的,需要修改本機~/nginx_temp/conf/conf.d/default.conf
文件並保存
server外部增加
upstream web {
server 192.168.1.6:8081 weight=5;
server 192.168.1.6:8082 weight=1;
}
server裏邊增加
location = / {
proxy_pass http://web;
}
default.conf
源碼
upstream web {
server 192.168.1.6:8081 weight=2;
server 192.168.1.6:8082 weight=1;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
#location / {
# root /usr/share/nginx/html;
# index index.html index.htm;
#}
location = / {
proxy_pass http://web;
}
#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;
#}
}
執行容器
docker run -d -p 81:80 --name nginx-server-1 \
-v ~/nginx_temp/www:/usr/share/nginx/html \
-v ~/nginx_temp/conf/conf.d/default.conf:/etc/nginx/conf.d/default.conf \
-v ~/nginx_temp/conf/nginx.conf:/etc/nginx/nginx.conf \
-v ~/nginx_temp/logs:/var/log/nginx nginx
測試
瀏覽器執行
192.168.1.6
是試驗機ip,不同主機替換ip即可,瀏覽器中執行以下命令
http://192.168.1.6:81
測試後會發現8081
和8082
端口已經在輪詢訪問,這樣就用nginx簡單的實現了一個負載均衡服務