워드프레스 서버 자동확장 및 로드 밸런싱하기

워드프레스 서버 자동확장 및 로드 밸런싱하기

아마존 서비스를 활용한 워드프레스 서버 자동확장 및 로드 밸런싱

 

효과 :  방문자 수가 많은 워드프레스 사이트를 아마존 웹서비스의 오토스케일링을 통해 자동 확장 – 축소하여 사이트의 접속을 원활하게 한다.

 

추가 자료 :

 

설명 :

1. Ec2 인스턴스에 웹서버 설치 및 AMI 만들기 (생략)

2. RDS 서비스를 이용하여 Mysql 서버 개설 (생략)

3. 워드프레스 설치

4. 미디어 저장을 위한 Amazon S3 버킷을 웹서버에 마운트하기

4-1. s3fs-fuse 설치

https://github.com/s3fs-fuse/s3fs-fuse 참고

s3fs-fuse 설치 후 아래와 같이 설정

/etc/fuse.conf를 열어 #user_allow_other 앞의 주석을 제거 후 저장.

$ sudo nano /etc/passwd-s3fs

AWS security credentials를 아래와 같은 형식으로 저장한다. (AWS security credentials는 IAM에서 설정한다.)

accesskeyId:securityAccessKey

note : s3fs-fuse 패키지 설치

$ sudo chmod 640 /etc/passwd-s3fs
$ sudo mkdir /home/wordpress/htdocs/wp-content/uploads
$ sudo s3fs BUCKETNAME -o allow_other /home/wordpress/htdocs/wp-content/uploads
$ cd /home/wordpress/htdocs/wp-content/uploads
$ touch hello-world.txt

S3 버킷에 hello-world.txt 파일이 있으면 성공.

 

S3버킷을 언마운트 하려면 아래와 같이 한다.

$ cd ..
$ sudo umount uploads/

 

To launch s3fs when the server starts up, create an Upstart script to mount the S3 bucket:

$ sudo vim /etc/init/s3fsmount.conf

Add these contents:

start on startup
start on runlevel [2345]
script
exec s3fs {BUCKETNAME} -o allow_other /home/wordpress/htdocs/wp-content/uploads
end script

Make sure the Upstart script works:

$ sudo start s3fsmount
$ ls uploads

You should see hello-world.txt listed.

Reboot the instance from the AWS console and reconnect via SSH when it’s rebooted. Verify that the S3 bucket has been mounted:

$ ls /home/wordpress/htdocs/wp-content/uploads

You should see the contents of the S3 bucket (currently just hello-world.txt, unless you’ve added anything else).

MIGRATING AN EXISTING WORDPRESS SITE

If you’re migrating an existing WordPress site, now’s the time to move your content. The key parts are:

  • Database (export with mysqldump and import with mysql)
  • .htaccess
  • WordPress theme files
  • Plugins
  • Media files/uploads

CACHING

This setup uses W3 Total Cache, a popular WordPress plugin for caching and CDN distribution.

$ cd /home/wordpress/htdocs/wp-content/plugins/
$ sudo wget http://downloads.wordpress.org/plugin/w3-total-cache.0.9.2.5.zip
$ sudo apt-get install unzip
$ sudo unzip w3-total-cache.0.9.2.5.zip
$ sudo rm w3-total-cache.*
$ sudo vim /home/wordpress/htdocs/wp-config.php
# add define('WP_CACHE', true); before require_once(ABSPATH .  'wp-settings.php');
$ sudo chmod 777 /home/wordpress/htdocs/wp-content/

Create a new S3 bucket.

Activate the plugin via the WordPress dashboard and navigate to the “Performance” tab. Adjust the settings:

  • Enable page caching with Opcode (APC)
  • Enable database caching with Opcode (APC)
  • Enable object cache with Opcode (APC)
  • Enable browser cache
  • Enable CDN with Amazon S3

Click the CDN tab. Enter your S3 credentials and bucket name and save. Click the buttons and follow instructions to upload attachments, theme files, includes, and any others.

Disable preview mode. Restore proper filesystem permissions:

$ sudo chmod 755 /home/wordpress/htdocs/wp-content/

SECURITY PRECAUTIONS

These are initial security precautions. You may want to research WordPress security threats and take extra steps to protect your site. And, always, keep WordPress up to date and keep passwords safe.

Add this line to the end of wp-config.php to disable file editing from the WordPress dashboard:

define('DISALLOW_FILE_EDIT', true);

Install the Login Security Solution plugin:

$ cd /home/wordpress/htdocs/wp-content/plugins
$ sudo wget http://downloads.wordpress.org/plugin/login-security-solution.zip
$ sudo unzip login-security-solution.zip
$ sudo rm login-security-solution.zip

Activate the plugin from the WordPress dashboard.

Add the following line to wp-config.php. This is necessary if you’ll be using a load balancer—more on that below. If not, you can skip ahead.

$_SERVER['REMOTE_ADDR'] = preg_replace('/^([^,]+).*$/', '\1', $_SERVER['HTTP_X_FORWARDED_FOR']);

LOAD BALANCING AND AUTO SCALING

One of the major perks of AWS is auto scaling, which lets you automatically launch new servers to handle bursts of heavy traffic, while scaling down when traffic is low. These steps show how to set up a load balancer to distribute traffic across multiple server instances and how to scale up and down.

In the EC2 console, create a new AMI from the instance you’ve been working on. Leave the instance running and note the instance’s ID. Create a load balancer and note the name. Add the instance to the load balancer group.

Enable load balancer–generated cookie stickiness for 3600 seconds. This allows user sessions to work properly when multiple server instances are running. User session data is stored on the server, and when multiple servers are handling requests, the client has to connect to the same server each time to preserve the session.

If you’re connecting a domain name to your WordPress instance, it’s best to host your DNSrecords with Amazon’s Route 53 service. The reason is that if you want your site to be available from the root domain (e.g., newsite.com, and not a subdomain like www.newsite.com or hello.newsite.com), you have to use Amazon’s DNS service, because of limitations in the DNSsystem and Amazon’s load balancing system (specifically, because Amazon requires CNAMErecords to point to load balancers, and the DNS system does not allow a CNAME record for the root domain). If you’re happy with sticking to a subdomain, you can host your DNS records elsewhere with no trouble.

Create a Route 53 hosted zone for your domain. For the root domain (domain.com), add a record set with type “A” and select Alias “Yes.” Point it to the load balancer A record name. Second, add a CNAME record for www.newsite.com and point it to the load balancer.

Once your DNS changes have propagated, you should be able to find your WordPress site at newsite.com or www.newsite.com.

There is no web console for Amazon’s auto scaling service, so you have to configure it from the command line. You’ll have to download and configure Amazon’s EC2 command line tools and auto scaling command line tools on your local machine.

After installing the command line tools, make sure your ~/.bash_profile (on your local machine, not the server) includes environment variables for your AWS account:

export EC2_PRIVATE_KEY=`ls ~/.aws/pk-*.pem`
export EC2_CERT=`ls ~/.aws/cert-*.pem`
export AWS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXX
export AWS_SECRET_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The paths may vary depending on where you installed your security files. You may need to reload your configuration by running:

$ source ~/.bash_profile

The first step in configuring auto scaling is defining a “launch configuration,” which describes the instance to launch when scaling. Be sure to substitute your AMI ID and security group name.

$ as-create-launch-config MyLaunchConfig --image-id ami-XXXXXXXX --instance-type t1.micro --group {SECURITY GROUP NAME}

Next, create an auto scaling group, which contains some basic scaling rules for your setup. This configuration makes sure at least one instance runs at all times, but no more than four. You’ll probably want to play with these variables. Run $ as-create-auto-scaling-group --helpfor more.

$ as-create-auto-scaling-group MyScalingGroup --launch-configuration MyLaunchConfig --availability-zones us-east-1a,us-east-1b,us-east-1c,us-east-1d  --desired-capacity 1 --min-size 1 --max-size 4 --load-balancers {LOAD BALANCER NAME} --health-check-type ELB --grace-period 300

You have to define two scaling policies—one up, one down:

$ as-put-scaling-policy ScalingUpPolicy --auto-scaling-group MyScalingGroup --adjustment=1 --type ChangeInCapacity
$ as-put-scaling-policy ScalingDownPolicy --auto-scaling-group MyScalingGroup --adjustment=-1 --type ChangeInCapacity

The last step is to go to the AWS CloudWatch web console and create alarms for events that will trigger your scaling policies. This is where much of the fine tuning happens. As a starting point, try creating two alarms: (1) if the CPU utilization for your scaling group exceeds 70% for 5 minutes, scale up, and (2) if CPU drops under 20% for the same period, scale down.

To test your setup, terminate your running instance. Within a minute or two, you’ll see a new instance boot up from the AMI you defined in your launch config.

You can also test your setup by simulating real life load conditions. Start up a new Ubuntu EC2instance and connect via SSH. Install Siege, a load testing tool that generates a given number of requests for a given duration:

$ sudo apt-get install siege

Now, launch a simulation of 20 concurrent users for 15 minutes:

$ siege -c20 -t15M  www.newsite.com

Use Amazon’s CloudWatch metrics to monitor activity on your servers. If the CPU utilization meets your threshold for the period you defined, you should see new servers deploy soon. When the test is done, they’ll gradually scale down to the minimum number of instances you specified.

Sometimes the load balancer won’t recognize the new instances. The most likely reason is that the load balancer isn’t configured to recognize instances from the instance group (us-east-1a, us-east-1b, etc.) where your new instances have been deployed. You can fix this from the EC2 load balancer web console.

MAKING UPDATES

At some point you’ll need to make changes to the code on your server. If you edit the code on the currently active instance, your changes will not appear when new instances launch, because those instance are based on the earlier AMI you created. To make your changes stick, you have to create a new AMI and reconfigure the launch configuration to use it instead of the old AMI.

Launch a new instance with your current AMI. Connect via SSH and make the changes. When you’re done, navigate to the WordPress dashboard and clear the cache from the W3 Total Cache plugin dashboard. Then, from the AWS web console, create a new AMI from this instance.

Create a new launch config:

$ as-create-launch-config MyLaunchConfig2 --image-id ami-XXXXX --instance-type t1.micro --group {SECURITY GROUP}

Update the auto scaling group to use the new launch config:

$ as-update-auto-scaling-group MyScalingGroup --launch-configuration MyLaunchConfig2

The update is done. Terminate any instances running the old AMI.

WHERE TO GO NEXT

There are a few areas where you might boost security, optimization, and workflow:

  • HTTPS: get an SSL certificate and enable HTTPS support.
  • Extra security: explore other WordPress security plugins and techniques. You may also want to disable SSH access to your live EC2 instances.
  • Enhanced caching: in particular, you might look into a separate caching server with memcached, especially if you plan to frequently run multiple instances. Varnish may also give a significant speed boost.
  • Alternative HTTP servers: many sites, including WordPress.com, have benefited from switching from Apache to NGINX. Others like lighttpd and Cherokee.
  • Development and staging: good web software design means building a workflow with proper development and staging servers. See, for instance, the 12 Factor Appand the Pokayoke Guide to Developing Software.

 

 

원문 : Scalable WordPress on Amazon Web Services | Joe Mornin.