docker-compose scale with sticky sessions

若如初见. 提交于 2019-12-03 16:14:11

Take a look at jwilder/nginx-proxy. This image provides an nginx reverse proxy that listens for containers that define the VIRTUAL_HOST variable and automatically updates its configuration on container creation and removal. tpcwang's fork allows you to use the IP_HASH directive on a container level to enable sticky sessions.

Consider the following Compose file:

nginx:
  image: tpcwang/nginx-proxy
  ports:
    - "80:80"
  volumes:
    - /var/run/docker.sock:/tmp/docker.sock:ro
app:
  image: tutum/hello-world
  environment:
    - VIRTUAL_HOST=<your_ip_or_domain_name>
    - USE_IP_HASH=1

Let's get it up and running and then scale app to three instances:

docker-compose up -d
docker-compose scale app=3

If you check the nginx configuration file you'll see something like this:

docker-compose exec nginx cat /etc/nginx/conf.d/default.conf

...
upstream 172.16.102.132 {
    ip_hash;
            # desktop_app_3
            server 172.17.0.7:80;
            # desktop_app_2
            server 172.17.0.6:80;
            # desktop_app_1
            server 172.17.0.4:80;
}
server {
    server_name 172.16.102.132;
    listen 80 ;
    access_log /var/log/nginx/access.log vhost;
    location / {
        proxy_pass http://172.16.102.132;
    }
}

The nginx container has automatically detected the three instances and has updated its configuration to route requests to all of them using sticky sessions.

If we try to access the app we can see that it always reports the same hostname on each refresh. If we remove the USE_IP_HASH environment variable we'll see that the hostname actually changes, this is, the nginx proxy is using round robin to balance our requests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!