July 10, 2017

Server Setup

^ Ad space to help offset hosting costs :D

We'll create 4 servers in this series:

  1. One load balancer
  2. Two application servers
  3. One "persistence" server (database + cache)

The Load Balancer will just have Nginx installed, while the application servers will have Nginx, PHP, and a Laravel application installed. On the last server, we'll install MySQL and Redis.

We'll start by dealing with just the Load Balancer and Application servers.


On each server, I generally start by installing a few tools:

sudo apt-get update
sudo apt-get install -y git tmux vim curl wget zip unzip htop


Then we'll install Nginx on all 3 servers. Nginx will serve as:

  1. a load balancer on one - proxying requests to the app servers
  2. a front-end to our apps, sending fastcgi requests to php-fpm

We'll install Nginx the same way on the server.

sudo add-apt-repository -y ppa:nginx/development
sudo apt-get update
sudo apt-get install -y nginx

Note that I install nginx/development, which is Nginx's MAINLINE branch - that's the stable branch + bug fixes. Nginx considers it production-ready.


Next we can install PHP on the 2 application servers. We won't need it on the load balancer.

We'll use the ondrej/php repository, which will allow us to get the latest PHP (7.1 as of this video).

# Install latest available php (7.1)
sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update
sudo apt-get install -y php7.1-fpm php7.1-cli php7.1-mcrypt php7.1-gd php7.1-mysql \
       php7.1-pgsql php7.1-imap php-memcached php7.1-mbstring php7.1-xml php7.1-curl \
       php7.1-bcmath php7.1-sqlite3 php7.1-xdebug

# Install composer
php -r "readfile('http://getcomposer.org/installer');" | sudo php -- --install-dir=/usr/bin/ --filename=composer

Now I don't have a specific application to show, because the details of the application don't matter just yet, so we'll just create a new Laravel app on each server:

# Create a Laravel 5.5 application
cd /var/www
sudo composer create-project laravel/laravel:dev-develop myapp

# This step is important for PHP-FPM to run Laravel
sudo chown -R www-data: myapp

Ensure that the two applications use the same APP_KEY, so they encrypt/decrypt things like cookies and CSRF tokens correctly across servers.


Lastly, we'll setup Nginx to pass requests to PHP-FPM. We can edit the default config file located at /etc/nginx/sites-available/default:

server {
    listen 80 default_server;

    root /var/www/myapp/public;

    index index.html index.htm index.php;

    server_name _;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;

    location ~ \.php$ {
       include snippets/fastcgi-php.conf;
       fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;

Then we can reload Nginx and test it out!

sudo nginx -t
sudo service nginx reload

We should see the default Laravel page on each application server.


Server Setup

All Topics