AWS ELB: Cutting Instances from Load Balancer

by Andrii Kozhokaru

Hello all!

I've recently stumbled upon a small yet unpleasant scaling-related issue - when I stop a host it keeps on accepting requests for about 30-35 seconds. Naturally these requests can't be processed. That is why an idea crossed my mind to cut instances from load balancer before stopping a web server.

For this purpose we need Command Line Tools for ELB.

Let's unpack them to the folder /opt/aws/elb.

Place the pk-** and cert-** certificates to /opt/aws/keys.

The JAVA SDF is /usr/java/latest.

The actual script is as follows:

  • /opt/aws/


export AWS_ELB_HOME="/opt/aws/elb"
export JAVA_HOME=/usr/java/latest
export TOOLS_HOME=/opt/aws
export EC2_PRIVATE_KEY=$TOOLS_HOME/keys/pk-********88ZVWC3FPEOFWRSFJ.pem
export EC2_CERT=$TOOLS_HOME/keys/cert-**********88ZVWC3FPEOFWRSFJ.pem

INSTANCE_ID=`wget -q -O -`
elb-deregister-instances-from-lb $1 --instances $INSTANCE_ID

Next, add the following line to the beginning of the stop function in the Apache/Tomcat/Nginx (or any other) initialization script:

sh /opt/aws/ $elb_name


  • $elb_name - the name of your Elastic Load Balancer.

Done. Now before the web-server stops the instance will be automatically cut from the balancer and will not accept requests.

P.S. Do not forget to introduce all the changes to the AMI.