Sticky Session With Docker Swarm (CE) on Debian 9

Introduction

Docker Swarm turns your individual servers into a cluster of computers; facilitating scaling, high-availability and load-balancing. The Swarm load-balancer implements a round-robin load-balancing strategy, and this might interfere the correct functioning of (legacy) stateful applications which require some form of sticky sessions to allow a high-available setup with multiple instances. Docker Enterprise Edition supports Layer-7 sticky session, but in this guide we will focus on the free (CE) version of Docker. To implement sticky sessions we'll use Traefik.

Prerequisites

  • At least two freshly deployed and updated Debian 9 instances in the same subnet with private networking enabled
  • Docker CE installed on these instances
  • The instances should be part of the same Swarm and should be able to communicate with each other over the private network
  • Prior knowledge of Docker and Docker Swarm
  • A non-root user with sudo rights (optional but it's strongly advised to not use the root user)

In this tutorial we'll be using two Vultr instances with private IP addresses 192.168.0.100 and 192.168.0.101. Both of them are Docker Swarm manager nodes (which is not ideal for production but enough for this tutorial).

Whoami

This tutorial uses the jwilder/whoami docker image as a demo application. This simple container will respond to a REST call with the name of the responding container, making it very easy to test if the sticky sessions are working. This image is obviously only used for demo purposes and needs to be replaced by your own application's image.

The whoami-service is configured as follows:

sudo docker network create whoaminet -d overlay
sudo docker service create --name whoami-service --mode global --network whoaminet --publish "80:8000"  jwilder/whoami
sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

If we subsequently curl the whoami REST endpoint at http://192.168.0.100/, we can see the round-robin load-balancing of Docker Swarm at work:

curl http://192.168.0.100
I'm a6a8c9294fc3
curl http://192.168.0.100
I'm ae9d1763b4ad
curl http://192.168.0.100
I'm a6a8c9294fc3
curl http://192.168.0.100
I'm ae9d1763b4ad
curl http://192.168.0.100
I'm a6a8c9294fc3

There is no use testing this with modern browsers like Chrome or Firefox because they are designed to keep connections alive, and the Docker Swarm load-balancer will only switch to the other container upon each new connection. If you want to test this with a browser you would have to wait at least 30 seconds for the connection to close before refreshing again.

Setting up Traefik

Traefik natively supports Docker Swarm, it can detect and register or de-register containers on-the-fly and it communicates with your application over the internal overlay network. Traefik needs some information about your application before it can start handling requests for it. This information is provided to Traefik by adding labels to your Swarm service:

sudo docker service update --label-add "traefik.docker.network=whoaminet" --label-add "traefik.port=8000" --label-add "traefik.frontend.rule=PathPrefix:/" --label-add "traefik.backend.loadbalancer.stickiness=true" whoami-service

The following list describes what each labels means:

  • traefik.docker.network : The Docker overlay network, over which Traefik will communicate with your service
  • traefik.port : The port on which your service is listening (this is the internally exposed port, not the published port)
  • traefik.frontend.rule : PathPrefix:/ binds the context root '/' to this service
  • traefik.backend.loadbalancer.stickiness : Enables sticky sessions for this service

Now that the whoami-service has been configured with the required labels, we can add the Traefik service to the swarm:

sudo docker service create --name traefik -p8080:80 -p9090:8080 --mount type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock --mode=global --constraint 'node.role == manager' --network whoaminet traefik --docker --docker.swarmmode --docker.watch --web --loglevel=DEBUG

This command does quite a lot of things at once, as shown in the following list:

  • --name traefik : Our new Docker service's name is Traefik
  • -p8080:80 : We publish Traefik's port 80 to port 8080 because port 80 is already in use by our whoami-service
  • -p9090:8080 : We publish Traefik's own web interface to port 9090
  • --mount ... : We mount the Docker Socket into the container so that Traefik can access the host's Docker runtime
  • --global : We want Traefik containers on each manager node for high availability reasons
  • --constraint 'node.role == manager' : We only want Traefik to run on manager nodes because worker nodes can't provide Traefik with the info it needs. For example, docker service ls on a worker node doesn't work, so Traefik wouldn't even be able to discover what services are running
  • --network whoaminet : Connect Traefik to the same network as our whoami-service, otherwise it can't connect to it. We previously told Traefik to connect to our service over this network with the traefik.docker.network label
  • traefik : Tell docker to use the latest Traefik docker image for this service
  • --docker --docker.swarmmode --docker.watch --web --loglevel=DEBUG : Command line arguments passed directly to Traefik to allow it to run in Docker swarm mode. DEBUG is optional here, but interesting during setup, and for this tutorial

All that is left to do is open up the necessary ports in the Debian firewall:

sudo iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 9090 -j ACCEPT

How it works

As soon as Traefik starts up, you can see in the logs that Traefik discovers the two whoami containers. It's also outputting the cookie name which it'll use to handle the sticky session:

time="2018-11-25T13:17:30Z" level=debug msg="Configuration received from provider docker: {\"backends\":{\"backend-whoami-service\":{\"servers\":{\"server-whoami-service-1-a179b2e38a607b1127e5537c2e614b05\":{\"url\":\"http://10.0.0.5:8000\",\"weight\":1},\"server-whoami-service-2-df8a622478a5a709fcb23c50e689b5b6\":{\"url\":\"http://10.0.0.4:8000\",\"weight\":1}},\"loadBalancer\":{\"method\":\"wrr\",\"stickiness\":{}}}},\"frontends\":{\"frontend-PathPrefix-0\":{\"entryPoints\":[\"http\"],\"backend\":\"backend-whoami-service\",\"routes\":{\"route-frontend-PathPrefix-0\":{\"rule\":\"PathPrefix:/\"}},\"passHostHeader\":true,\"priority\":0,\"basicAuth\":null}}}"
time="2018-11-25T13:17:30Z" level=debug msg="Wiring frontend frontend-PathPrefix-0 to entryPoint http"
time="2018-11-25T13:17:30Z" level=debug msg="Creating backend backend-whoami-service"
time="2018-11-25T13:17:30Z" level=debug msg="Adding TLSClientHeaders middleware for frontend frontend-PathPrefix-0"
time="2018-11-25T13:17:30Z" level=debug msg="Creating load-balancer wrr"
time="2018-11-25T13:17:30Z" level=debug msg="Sticky session with cookie _a49bc"
time="2018-11-25T13:17:30Z" level=debug msg="Creating server server-whoami-service-1-a179b2e38a607b1127e5537c2e614b05 at http://10.0.0.5:8000 with weight 1"
time="2018-11-25T13:17:30Z" level=debug msg="Creating server server-whoami-service-2-df8a622478a5a709fcb23c50e689b5b6 at http://10.0.0.4:8000 with weight 1"
time="2018-11-25T13:17:30Z" level=debug msg="Creating route route-frontend-PathPrefix-0 PathPrefix:/"
time="2018-11-25T13:17:30Z" level=info msg="Server configuration reloaded on :80"
time="2018-11-25T13:17:30Z" level=info msg="Server configuration reloaded on :8080"

If we curl to http://192.168.0.100:8080 we can see that a new cookie, _a49bc, has been set:

curl -v http://192.168.0.100:8080
* About to connect() to 192.168.0.100 port 8080 (#0)
*   Trying 192.168.0.100...
* Connected to 192.168.0.100 (192.168.0.100) port 8080 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.0.100:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 17
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 25 Nov 2018 13:18:40 GMT
< Set-Cookie: _a49bc=http://10.0.0.5:8000; Path=/
<
I'm a6a8c9294fc3
* Connection #0 to host 192.168.0.100 left intact

If, on subsequent calls, we send this cookie to Traefik, we will always be forwarded to the same container:

curl http://192.168.0.100:8080 --cookie "_a49bc=http://10.0.0.5:8000"
I'm a6a8c9294fc3
curl http://192.168.0.100:8080 --cookie "_a49bc=http://10.0.0.5:8000"
I'm a6a8c9294fc3
curl http://192.168.0.100:8080 --cookie "_a49bc=http://10.0.0.5:8000"
I'm a6a8c9294fc3
curl http://192.168.0.100:8080 --cookie "_a49bc=http://10.0.0.5:8000"
I'm a6a8c9294fc3

The cookie contains nothing but the internal IP address of the container to which Traefik should send to request. If you change to cookie value to http://10.0.0.4:8000, then the request would effectively be forwarded to the other container. If the cookie were never to be re-sent to Traefik, then the sticky session will not work and requests will be balanced between the application's containers and the Traefik containers.

That's all that is needed to set up Layer 7 Sticky Sessions in Docker CE on Debian 9.



Instalación de Docker en Ubuntu 14.04

Instalación de Docker en Ubuntu 14.04

¿Usando un sistema diferente? Docker es una aplicación que permite implementar programas que se ejecutan como contenedores. Fue escrito en el popular programa Go

Setup Sentry via Docker on Ubuntu 16.04

Setup Sentry via Docker on Ubuntu 16.04

Using a Different System? Introduction Sentry is an open source solution for error tracking. Sentry tracks exceptions and other useful messages fro

Instalar el servidor Rancher en RancherOS

Instalar el servidor Rancher en RancherOS

Descripción general RancherOS es un sistema operativo increíblemente liviano (solo unos 60 MB) que ejecuta un demonio Docker del sistema como PID 0 para ejecutar servicios del sistema

Cómo usar Docker: Creando tu primer contenedor Docker

Cómo usar Docker: Creando tu primer contenedor Docker

Este tutorial explica los conceptos básicos para comenzar a usar Docker. Supongo que ya tienes instalado Docker. Los pasos de este tutorial funcionarán en un

Balance de carga con Docker

Balance de carga con Docker

Al ejecutar una aplicación web, normalmente desea aprovechar al máximo sus recursos sin tener que convertir su software para usar subprocesos múltiples o

En CoreOS, configure su propio registro de Docker

En CoreOS, configure su propio registro de Docker

Todos conocemos y amamos Docker, una plataforma para crear, administrar y distribuir contenedores de aplicaciones en múltiples máquinas. Docker Inc. proporciona un servicio t

Create a Docker Swarm on Alpine Linux 3.9.0

Create a Docker Swarm on Alpine Linux 3.9.0

Introduction This guide will show you how to create and configure a Docker swarm using multiple Alpine Linux 3.9.0 servers and Portainer. Please be aware tha

Implemente una aplicación Node.js con Docker

Implemente una aplicación Node.js con Docker

Este artículo le mostrará cómo implementar su aplicación Node dentro de un contenedor Docker. Nota: Este tutorial asume que tienes Docker instalado y leído

Instalar Rancher OS a través de iPXE

Instalar Rancher OS a través de iPXE

Rancher OS es una distribución de Linux muy ligera construida alrededor de Docker. El sistema operativo en sí pesa alrededor de 20 MB. Este tutorial lo pondrá en funcionamiento con

Deploy Kubernetes With Kubeadm on CentOS 7

Deploy Kubernetes With Kubeadm on CentOS 7

Overview This article is meant to help you get a Kubernetes cluster up and running with kubeadm in no time. This guide will be deploying two servers, on

Instalación de docker-compose en CoreOS

Instalación de docker-compose en CoreOS

Este artículo explica cómo instalar docker-compose en CoreOS. En CoreOS, la carpeta / usr / es inmutable, por lo que la ruta estándar / usr / local / bin no está disponible para

Cómo instalar Harbor en CentOS 7

Cómo instalar Harbor en CentOS 7

Harbor es un servidor de registro de clase empresarial de código abierto que almacena y distribuye imágenes de Docker. Harbor extiende el código abierto Docker Distribution b

Install Docker CE on Ubuntu 18.04

Install Docker CE on Ubuntu 18.04

Introduction Docker is an application that allows us to deploy programs that are run as containers. It was written in the popular Go programming language

Comience con SQL Server 2017 (MS-SQL) en CentOS 7 con Docker

Comience con SQL Server 2017 (MS-SQL) en CentOS 7 con Docker

Requisitos previos Docker engine 1.8+. Mínimo de 4 GB de espacio en disco. Mínimo de 4 GB de RAM. Paso 1. Instalar Docker Para instalar SQL-Server, Docker mus

Comenzando con Kubernetes en CentOS 7

Comenzando con Kubernetes en CentOS 7

Kubernetes es una plataforma de código abierto desarrollada por Google para administrar aplicaciones en contenedores en un grupo de servidores. Se basa en una década y

Implemente una aplicación PHP usando Docker-compose

Implemente una aplicación PHP usando Docker-compose

Las aplicaciones PHP generalmente están compuestas por un servidor web, un sistema de base de datos relacional y el propio intérprete de idiomas. En este tutorial estaremos apalancando

Instalar Rancher en Ubuntu 16.04

Instalar Rancher en Ubuntu 16.04

¿Usando un sistema diferente? Introducción Rancher es una plataforma de código abierto para ejecutar contenedores y crear un servicio de contenedor privado. Ranchero es base

Instalación de Docker CE en CentOS 7

Instalación de Docker CE en CentOS 7

La tecnología de contenedores Docker le permite ejecutar aplicaciones en un entorno específico y aislado. Docker Community Edition (CE) es el nuevo nombre para el fre

Instalación de Docker CE en Debian 9

Instalación de Docker CE en Debian 9

¿Usando un sistema diferente? Introducción Docker es una aplicación que permite la implementación de software en contenedores virtuales. Fue escrito en el G

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

Los ataques de ransomware van en aumento, pero ¿puede la IA ayudar a lidiar con el último virus informático? ¿Es la IA la respuesta? Lea aquí, sepa que la IA es una bendición o una perdición

ReactOS: ¿Es este el futuro de Windows?

ReactOS: ¿Es este el futuro de Windows?

ReactOS, un sistema operativo de código abierto y gratuito, está aquí con la última versión. ¿Puede satisfacer las necesidades de los usuarios de Windows de hoy en día y acabar con Microsoft? Averigüemos más sobre este estilo antiguo, pero una experiencia de sistema operativo más nueva.

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Whatsapp finalmente lanzó la aplicación de escritorio para usuarios de Mac y Windows. Ahora puede acceder a Whatsapp desde Windows o Mac fácilmente. Disponible para Windows 8+ y Mac OS 10.9+

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

Lea esto para saber cómo la Inteligencia Artificial se está volviendo popular entre las empresas de pequeña escala y cómo está aumentando las probabilidades de hacerlas crecer y dar ventaja a sus competidores.

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

Recientemente, Apple lanzó macOS Catalina 10.15.4, una actualización complementaria para solucionar problemas, pero parece que la actualización está causando más problemas que conducen al bloqueo de las máquinas Mac. Lee este artículo para obtener más información

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

¿Qué es un sistema de archivos de diario y cómo funciona?

¿Qué es un sistema de archivos de diario y cómo funciona?

Nuestra computadora almacena todos los datos de una manera organizada conocida como sistema de archivos de diario. Es un método eficiente que permite a la computadora buscar y mostrar archivos tan pronto como presiona buscar.

Singularidad tecnológica: ¿un futuro lejano de la civilización humana?

Singularidad tecnológica: ¿un futuro lejano de la civilización humana?

A medida que la ciencia evoluciona a un ritmo rápido, asumiendo muchos de nuestros esfuerzos, también aumentan los riesgos de someternos a una singularidad inexplicable. Lea, lo que la singularidad podría significar para nosotros.

Una mirada a 26 técnicas analíticas de Big Data: Parte 1

Una mirada a 26 técnicas analíticas de Big Data: Parte 1

Una mirada a 26 técnicas analíticas de Big Data: Parte 1

El impacto de la inteligencia artificial en la atención médica 2021

El impacto de la inteligencia artificial en la atención médica 2021

La IA en la salud ha dado grandes pasos desde las últimas décadas. Por tanto, el futuro de la IA en el sector sanitario sigue creciendo día a día.