Using Nginx as Load Balancer in Docker

-pull nginx

# docker pull nginx
# docker pull nginxdemos/hello

-run two nginx
because I want to set static ip to www1 and www2.
I need to create my own network

# docker network create –subnet=172.10.0.0/24 vlan10
# docker run –name=www1 –hostname=www1 –net vlan10 –ip 172.10.0.11 -p 81:80 -d nginxdemos/hello

# docker run –name=www2 –hostname=www2 –net vlan10 –ip 172.10.0.12 -p 82:80 -d nginxdemos/hello

-create nginx load balancer
# cat nginx.conf
upstream loadbalance {
    least_conn;
    server 192.168.88.66:81;
    server 192.168.88.66:82;
}
server {
    location / {
        proxy_pass http://loadbalance;
    }

}

# cat Dockerfile
FROM nginx
RUN rm /etc/nginx/conf.d/default.conf

COPY nginx.conf /etc/nginx/conf.d/default.conf

# docker build -t nginxbalancer .

# docker container run -p 80:80 -d nginxbalancer

-test accessing http://192.168.88.66

it should show “Server address:”

-test shutdown both www1 and www2
# docker stop www1

# docker stop www2

test accessing http://192.168.88.66

it should show bad gateway

-test run www1 again
# docker start www1
it should show “Server address:”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s