docker Nginx(二) 负载均衡配置

获取基础容器的配置

首先用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

测试后会发现80818082端口已经在轮询访问,这样就用nginx简单的实现了一个负载均衡服务

你可能感兴趣的:(docker)