If you have multiple load balanced webservers all serving the same site, sessions should be shared among thosememcache logo servers, and not reside on each server individually. Because we don’t know where user gets load-balanced to which backend server. A common way solving this problems are by using custom class that overrides default behavior and stores sessions in a MySQL database. All webservers in clusters connect to the same database. However, the main problem that must be taken into consideration when using a database is the bottleneck.

Example loadbalancing backend using nginx

http {
  upstream backend {
    server 192.168.1.1:8000 weight=3;
    server 192.168.1.2:8001;
    server 192.168.1.3:8002;
    server 192.168.1.4:8003;
  }

  server {
    listen 80;
    server_name www.example.com;
    location / {
      proxy_pass http://backend;
    }
  }
}


Another alternative solution is using Memcached. Memcached can be used for caching almost everything, function results, html blocks, database query results. But now we’re going to use it to store sessions for our website clusters. In the php configuration, session handler can be overridden using the following way.

session.save_handler = memcache
session.save_path = 'tcp://192.168.1.5:11211'

And don’t forget to restart apache backends. how do we make memcache listen on a specific ip address?
InĀ /etc/sysconfig/memcached

PORT='11211'
USER='nobody'
MAXCONN='1024'
CACHESIZE='512'
OPTIONS='-l 192.168.1.5'

PHP will now know not use the default files handler to save session files in /var/lib/php/session/ php will use memcache running at 192.168.1.5 instead. But other people can access our memcached servers? alter or damage the contents. you might ask.

That is easy. we can use iptables to restrict source ip address which is allowed to access our memcached servers.
In Memcached server:

iptables -N MEMC
iptables -A INPUT -p tcp -m tcp --dport 11211 -j MEMC

iptables -A MEMC -s 127.0.0.1 -j RETURN
iptables -A MEMC -s 192.168.1.1 -j RETURN
iptables -A MEMC -s 192.168.1.2 -j RETURN
iptables -A MEMC -s 192.168.1.3 -j RETURN
iptables -A MEMC -s 192.168.1.4 -j RETURN
iptables -A MEMC -j REJECT --reject-with icmp-host-prohibited

Now we have a session storage that can be used from any backend servers.

Reference:

Share