Deploying Laravel with Capistrano 3

Deploying PHP with Ruby?

Alex Rhea
Alex’s Blog
4 min readFeb 27, 2014

--

Step back to the days where you would deploy your application by FTP’ing into your server and copying files over or directly editing on the server. Those days aren’t long gone but, the tools to help you integrate better practices and source control have come a long way.

Github

If Github isn’t part of your team’s or personal workflow seriously consider it our a product like it. At Koofers we have recently made the move to Github for our product development and project management. It makes it easy to coordinate tasks and issues with remote teams. Capistrano allows you to pull in the latest version of your code and deploy it directly to your production servers.

What Does Capistrano Do?

Capistrano deploys your source code and keeps versions locally on the server for easy rollback. It aids in installing all the dependencies and setting up file permissions all via an easy configuration file.

Install

Capistrano

Deploy.rb

We will go step by step through the deploy.rb file and at the end I will post a fully functioning version.

I break the rest of my tasks out into separate files located in the lib/capistrano/tasks.

Compser.cap

This file sets up and runs composer install on the directory for php dependencies.

First we check to see if composer is installed. If it is we run self-update or we download and install it and at to the bin.

Then we run composer install and hide all the output and updates.

This command is just a utility and isn’t used in our deploy script specifically. All of these tasks are wrapped inside of:

Then we register these tasks with Capistrano under the namespace deploy.

Laravel.rb

All of the following tasks are under the “laravel” namespace.

This task sets all the file permissions on the storage files so that we can write to them.

Optimize the class loader so that our application is optimized for production.

Run the Laravel Artisan migrate task so that our database is up to date.

Apache.rb

Finally, this is on that I have struggled with for a long time. I do not want to hard code passwords and other configuration values into my code. So I use the handy .local.env.php that Laravel provides but, this is hard to translate into environment variables on the server. Capistrano provides an API to set session environment variables. What this script does is take those and copy them into an Ubuntu environment. Specifically it places the variables in the /etc/environment.

This copies all the variables from the Capistrano :default_environment variables to the /etc/environment.

Finally the Production.rb file

This file is an environment that you want to deploy to. You can have staging.rb or development.rb.

To run your deployment:

If you have any questions or comments feel free to reach out to me on Twitter @arhea10. I hope this helps you as much as you helped me.

--

--