Modern web-application development heavily relies on frameworks. These sets of readily-prepared libraries make the actual programming a lot easier than it would be, unlike in ye older days. They provide tools varying from authentication to encryption, cookie and session handling to file uploads.
Despite the popularity of the PHP programming language and its many excellent frameworks, there are still time consuming challenges which take the developers away from the fun bits of creating the web-site (or API) they dream of.
In this DigitalOcean article, following on our Capistrano Automation Tool Series, we will see how to introduce another little framework (or tool), this time to help you with pushing your code to your servers without dealing with SFTP file managers – automatically!
Note: Although we will see how to download and set up the necessary dependencies for Capistrano (e.g. Ruby 2.1.0
) to automate the deployment process, this article assumes that you already have your deployment droplet ready with a functioning web-site installation, online on an Ubuntu 13 cloud server.
Capistrano is a Ruby programming language based, open-source server (or deployment) management tool. Using Capistrano, arbitrary functions and procedures can be performed on virtual servers without direct interference by having Capistrano execute a script (i.e. a recipe) with all the instructions listed. In a general sense, this tool can be considered a developer’s very own deployment assistant, helping with almost anything from getting the code on the remote machine to bootstrapping the entire getting-online process.
Originally written to help with Rails framework deployments, with its latest version, Capistrano 3 can now be used with (and for) almost anything, including PHP.
Note: If you would like to learn more about Capistrano and Ruby, check out our article on the subject: How To Use Capistrano to Automate Deployments: Getting Started.
On your PHP development machine, you need to have the latest available Ruby interpreter in order to run Capistrano. The instructions below, explaining how to get Ruby on an Ubuntu VPS, is actually a quick summary of our detailed tutorial: Preparing An Ubuntu 13 Server To Run Ruby 2.1.0.
# Update the software sources list
# And upgrade the dated applications:
aptitude update
aptitude -y upgrade
# Download and install the build-essential package:
aptitude install -y build-essential
# And some additional, commonly used tools:
aptitude install -y cvs subversion git-core libyaml-dev mercurial
# Get the Ruby Version Manager
curl -L get.rvm.io | bash -s stable
# And to create a system environment with RVM:
source /etc/profile.d/rvm.sh
# Download and install Ruby using RVM:
rvm reload
rvm install 2.1.0
Once Ruby is installed, Capistrano can be set up using the default Ruby package manager RubyGems.
Run the following command to download and install Capistrano 3 using gem
:
gem install capistrano --no-ri --no-rdoc
As a mature automation tool, Capistrano is built with stability and security in mind. In order to use it to deploy your PHP web applications, we first need to perform some work on the deployment server, e.g. create a user-group for Capistrano to use to connect to it.
Add a new user group:
# Usage: sudo addgroup [group name]
sudo addgroup www
Create a new user and add it to this group:
# Create a new user:
# Usage: sudo adducer [user name]
sudo adduser deployer
# Follow on-screen instructions to user-related
# information such as the desired password.
# Add the user to an already existing group:
# Usage: sudo adducer [user name] [group name]
sudo adduser deployer www
Edit /etc/sudoers
using the text editor nano
to let the user deployer
sudo
for future deployments:
nano /etc/sudoers
Scroll down the file and find where root
is defined:
..
# User privilege specification
root ALL=(ALL:ALL) ALL
..
Append the following right after root ALL=(ALL) ALL
:
deployer ALL=(ALL:ALL) ALL
This section of the /etc/sudoers
file should now look like this:
..
# User privilege specification
root ALL=(ALL:ALL) ALL
deployer ALL=(ALL:ALL) ALL
..
Press CTRL+X and confirm with Y to save and exit.
Note: To learn more about SSH and sudo, check out DigitalOcean community articles on Linux Basics.
On the deployment server, we also need to define and create the directory where the PHP codebase will be located for the web-server to run the application.
Create the www
web-application directory inside /var
:
sudo mkdir /var/www
And set the permissions to make it access for the web-server (i.e. Nginx):
# Set the ownership of the folder to members of `www` group
sudo chown -R :www /var/www
# Set folder permissions recursively
sudo chmod -R g+rwX /var/www
# Ensure permissions will affect future sub-directories etc.
sudo chmod g+s /var/www
Capistrano’s duty is to automate deployments. We still need to set up PHP and NGinx - or any other web-server & interpreter combination - to get our web-application working.
In order to fully prepare the deployment server to run PHP web-applications, check out the following articles:
How To Install Linux, nginx, MySQL, PHP (LEMP) stack
How To Install phpMyAdmin on a LEMP server
Once we are done installing Ruby and Capistrano on our development server, and adding a deployment user on the deployment machine, we can see how to “initiate” Capistrano to get started with the tool.
Note: In this section, we assume that your web-application source code is located at /home/developer1/my_app
directory. The following commands need to be executed from within.
# cd /path/to/your/app/on/dev/server
cd /home/developer1/my_app
Git is a source-code management system and revisiting tool commonly used by developers. Capistrano controls and manages your application lifecycle and deployment process through Git repositories.
In this section, we will create a centrally-accessible Git repository, initiate Git and upload your project there for Capistrano to use during deployments.
Note: In order to follow this section, you will need a Github account and an empty repository created.
Execute the following, self-explanatory commands inside the directory where your application’s source code is located (e.g. my_app
) to initiate a repository:
# !! These commands are to be executed on
# your development machine, from where you will
# deploy to your server.
# Instructions might vary slightly depending on
# your choice of operating system.
# Initiate the repository
git init
# Add all the files to the repository
git add .
# Commit the changes
git commit -m "first commit"
# Add your Github repository link
# Example: git remote add origin git@github.com:[user name]/[proj. name].git
git remote add origin git@github.com:user123/my_app.git
# Create an RSA/SSH key
# Follow the on-screen instructions
ssh-keygen -t rsa
# View the contents of the key and add it to your Github
# by copy-and-pasting from the current remote session by
# visiting: https://github.com/settings/ssh
# To learn more about the process,
# visit: https://help.github.com/articles/generating-ssh-keys
cat /root/.ssh/id_rsa.pub
# Set your Github information
# Username:
# Usage: git config --global user.name "[your username]"
# Email:
# Usage: git config --global user.email "[your email]"
git config --global user.name "user123"
git config --global user.email "user123@domain.tld"
# Push the project's source code to your Github account
git push -u origin master
Note: To learn more about working with Git, check out the How To Use Git Effectively tutorial at DigitalOcean community pages.
In this step, we will get Capistrano to automatically scaffold its configuration and deployment files inside the project directory.
Run the following to initiate (i.e. install) Capistrano files:
cap install
# mkdir -p config/deploy
# create config/deploy.rb
# create config/deploy/staging.rb
# create config/deploy/production.rb
# mkdir -p lib/capistrano/tasks
# Capified
The file config/deploy.rb
contains arguments and settings relevant to the deployment server(s). Here, we will tell Capistrano to which server(s) we would like to connect and deploy.
Run the following to edit the file using nano
text editor:
nano config/deploy.rb
Add the below block of code, modifying it to suit your own settings:
# !! When editing the file (or defining the configurations),
# you can either comment them out or add the new lines.
# Make sure to **not** to have some example settings
# overriding the ones you are appending.
# Define the name of the application
set :application, 'my_app'
# Define where can Capistrano access the source repository
# set :repo_url, 'https://github.com/[user name]/[application name].git'
set :scm, :git
set :repo_url, 'https://github.com/user123/my_app.git'
# Define where to put your application code
set :deploy_to, "/var/www/my_app"
set :pty, true
set :format, :pretty
# Set your post-deployment settings.
# For example, you can restart your Nginx process
# similar to the below example.
# To learn more about how to work with Capistrano tasks
# check out the official Capistrano documentation at:
# http://capistranorb.com/
# namespace :deploy do
# desc 'Restart application'
# task :restart do
# on roles(:app), in: :sequence, wait: 5 do
# # Your restart mechanism here, for example:
# sudo "service nginx restart"
# end
# end
# end
Press CTRL+X and confirm with Y to save and exit.
Note: Similar to config/deploy.rb
, you will need to make some amendments to the config/production.rb
file. You are better modifying the code instead of appending the below block.
Run the following to edit the file using nano text editor:
nano config/deploy/production.rb
Enter your server’s settings, similar to below:
# Define roles, user and IP address of deployment server
# role :name, %{[user]@[IP adde.]}
role :app, %w{deployer@162.243.74.190}
# Define server(s)
# Example:
# server '[your droplet's IP addr]', user: '[the deployer user]', roles: %w{[role names as defined above]}
# server '162.243.74.190', user: 'deployer', roles: %w{app}
server '162.243.74.190', user: 'deployer', roles: %w{app}
# SSH Options
# See the example commented out section in the file
# for more options.
set :ssh_options, {
forward_agent: false,
auth_methods: %w(password),
password: 'user_deployers_password',
user: 'deployer',
}
Press CTRL+X and confirm with Y to save and exit.
Once we are done with the settings, it is time to deploy.
Run the following code on your development machine to deploy to the production server. As defined in the above files, Capistrano will:
Connect to the deployment server
Download the application source
Perform the deployment actions
Once all settings are done, you can run the following command to get Capistrano deploy your application source from your development server to deployment machine:
cap production deploy
And that’s it! Now, you can watch Capistrano take your code online and keep track of your most recent code base.
Working with Capistrano is not always as straightforward as it might seem. Unfortunately, the tool likes to complain instead of guiding and the documentation, at its current stage, is a little bit limited.
For everything to work smoothly, try to:
Match the directory and the repository names.
Type everything correctly.
Make sure that your development and deployment servers contain all necessary tools (i.e. sqlite3, libraries etc.).
Make sure to test all operations and executions manually before getting Capistrano perform them.
Consider implementing a more secure authentication method following the official Capistrano docs.
To learn more about Capistrano and what it can do, consider reading the Capistrano documentation.
<div class=“author”>Submitted by: <a href=“https://twitter.com/ostezer”>O.S. Tezer</a></div>
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
If you’re looking for an automated way to deploy your PHP app. Check out Amezmo
I’m new to Capistrano. It seems we need to install Git on deployment server but I don’t find that step here. Please correct me if any. Thanks.
I found that SSH key needed to be from the server, not the local machine as implied above. Moreover I had to sudo -u deployer ssh-keygen …
Where do you put these Cap config files? git add these files to repo and deploy to server?
I want to version control my Cap config files, but I don’t want them to be in server.