In this tutorial, we will dive deeply into OpenShift to understand the custom build and deployment process. We will also learn the command-line tool for logging and troubleshooting when our application is down.
We'll also cover some bonus tips to leverage the SSH features offered by OpenShift. Additionally, we'll look at how to synchronize our local environment with remote environment including database, source file and media files.
The first part of this series gave a quick overview of OpenShift. We discussed how to create the app, get the server URL, our account name, and setup a custom domain.
We did almost all of those tasks using the web interface which is great and very convenient; however, in addition to the dashboard, OpenShift offers a powerful client tool call rhc client. We
can invoke it from command line to perform OpenShift administration and maintenance. Once
you;ve installed the tool, you can create apps, add cartridges, and add gears quickly. It's a Swiss army knife. You may not need it but it's very handy.
Install OpenShift Command Line Client
The OpenShift document is very clear about installing this client library. The library is written in Ruby so make sure that you have Ruby installed. Basically, you only need to install the rhc gem on Mac or Linux. You've got a large chance that Git and Ruby are already installed so you only need to run:
sudo gem install rhc
Then setup it with your username and password. When you are asked to Generate a token now? Type Yes.
rhc setup
# Once it's done, you should see something similar:
Saving configuration to /Users/kureikain/.openshift/express.conf ... done Checking for git ... found git version 1.8.5.2 (Apple Git-48) Checking common problems .. done Checking for a domain ... tutsplus Checking for applications ... found 2 demo2 http://demo2-tutsplus.rhcloud.com/ php http://php-tutsplus.rhcloud.com/ You are using 3 of 3 total gears The following gear sizes are available to you: small Your client tools are now configured.
Now that we have the utility installed, let's play around with it.
The first thing to note is that the rhc
command will give you a list of available commands. You can learn from there with rhc help
. It shows a brief overview of each command. rhc help command_name
will show you how to use a particular command.
$ rhc help
Getting started: setup Connects to OpenShift and sets up your keys and domain create-app Create an application apps List all your applications cartridges List available cartridges add-cartridge Add a cartridge to your application set-env Set one or more environment variable(s) to your application logout End the current session Working with apps: tail Tail the logs of an application port-forward Forward remote ports to the workstation threaddump Trigger a thread dump for JBoss and Ruby apps snapshot Save the current state of your application locally git-clone Clone and configure an application's repository locally Management commands: account Display details about your OpenShift account alias Add or remove a custom domain name for an app app Commands for creating and managing applications authorization Manage your authorization tokens cartridge Manage your application cartridges deployment Commands for deploying and managing deployments of an application domain Add or rename the container for your apps env Manages user-defined environment variables set on a given application member Manage membership on domains server Display information about the status of the OpenShift service ssh SSH into the specified application sshkey Add and remove keys for Git and SSH
$ rhc help app
Usage: rhc app <action>
Creates and controls an OpenShift application. To see the list of all applications use the rhc domain show command. Note that delete
is not reversible and will stop your application and then remove the application and repo from the remote server. No local changes are
made.
List of Actions
configure Configure several properties that apply to an application
create Create an application
delete Delete an application from the server
deploy Deploy a git reference or binary file of an application
force-stop Stops all application processes
reload Reload the application's configuration
restart Restart the application
scale-down Scale down the application's web cartridge
scale-up Scale up the application's web cartridge
show Show information about an application
start Start the application
stop Stop the application
tidy Clean out the application's logs and tmp directories and tidy up the git repo on the server
For the command that interacts with an app, you have to specify the app name with -a appname
or just append app name; however, if you run the commands inside your Git repository that you cloned before, you may omit it. The app name can be see with rhc app
command. Example with my previous demo2 app. Instead of typing whole the account name and server name to SSH into it, I can use this command:
$ rhc ssh demo2 # Output Connecting to [email protected] ...
Sometime, it can be useful to trigger a deployment without any pushing. Say we want to deploy WordPress from a particular Git commit or a special branch.
See the following example:
# Deploy branch master on demo2 app $ rhc app-deploy master -a demo2 # Deploy bracch branch/deploy on demo2 app $ rhc app-deploy branch/deploy -a demo2
Or show app information:
demo2 [master] ⚡ rhc app-show demo2 demo2 @ http://demo2-tutsplus.rhcloud.com/ (uuid: 532bd7655004468bcf0000e1) --------------------------------------------------------------------------- Domain: tutsplus Created: Mar 20 11:08 PM Gears: 1 (defaults to small) Git URL: ssh://[email protected]/~/git/demo2.git/ Initial Git URL: https://github.com/openshift/wordpress-example.git SSH: [email protected] Deployment: auto (on git push) Aliases: openshift.axcoto.com mysql-5.5 (MySQL 5.5) --------------------- Gears: Located with php-5.4, phpmyadmin-4 Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/ Database Name: demo2 Password: DyANqgKAFbTT Username: adminL1GxwjI php-5.4 (PHP 5.4) ----------------- Gears: Located with mysql-5.5, phpmyadmin-4 phpmyadmin-4 (phpMyAdmin 4.0) ----------------------------- Gears: Located with mysql-5.5, php-5.4 Connection URL: https://demo2-tutsplus.rhcloud.com/phpmyadmin/
You can also save a snapshot of current app:
$ rhc snapshot-save demo2 Pulling down a snapshot to demo2.tar.gz... Creating and sending tar.gz RESULT: Success
Or you can add some cartridges:
# add mysql-5.5 cartridge into our app $ rhc cartridge add -a demo2 -c mysql-5.1 # add php5-4 cartridge into our app $ rhc cartridge add -a demo2 -c php-5.4
Of course, feel free to experiment with a number of different commands. It's relatively straight forward and easy to understand, and since everything is under source control, it's easy to rollback your changes.
What Happens When You Push to Your Repository?
In the first article, we saw that whenever a git push
to deploy a branch is triggered, the app will be deployed. According to the OpenShift document, here is a break down of what happen:
- You run a
git push
on your computer, your changes are sent to your OpenShift application - The application is shut down
- Your changes are copied on the server into the correct location
- OpenShift invokes your build hooks - script files you've placed in your Git repository
- Your application is started
Step 4 is handle by script files in your .openshift/action_hooks
. OpenShift will execute those script files checked into your Git repository at
specific points during the deployment process.
If the corresponding
script file does not exist, the deployment process will continue
normally. Again, all hooks must be placed in the .openshift/action_hooks/
directory in your application repository. The individual phases of each build are:
-
Pre-Receive. During your push, OpenShift checks to ensure that your application is in a consistent state. There is no hook for this step.
-
Pre-Build.
This happens after the application is stopped and the new repo dir has been deployed but before the build. Runs the
.openshift/action_hooks/pre_build
script -
Build. This builds your application, downloads required dependency, executes the
.openshift/action_hooks/build
script and preps everything for deployment. In scope of WordPress, we don't use this step much since WordPress just need to drop into document root and run by web server, no any special build requirements. We usually use this hook to Download WordPress and extract it into correct location on OpenShift.
-
Deploy.
This step happens right before the application is issued a start. Any
required prep work to get the application ready to be started should be
done in the
.openshift/action_hooks/deploy
hook. In scope of WordPress, we use this hook to copy the data of the above build into document root, copy plugin and theme (.openshift/themes and .openshift/plugin
) to the correct location.
-
Post-Deploy.
Some applications may need to interact with the running application to
complete the deployment process. After the application starts, the
.openshift/action_hooks/post_deploy
hook will be executed.
You can totally customize these scripts for your own purposes. The build scripts are executed directly, meaning you can write it in any language no matter it's Bash, Ruby or Python as long as you put correct shebang such as if you used bash.
#!/bin/bashOr Ruby
#!/usr/bin/ruby
I prefer to write simple Bash script for build purpose and I will use it in this tutorial. Bash is every where and its syntax is so easy that you don't need to know Bash to understand some scripts actually.
With respect to WordPress, we don't do many tasks in the building process because PHP doesn't requires building; however, we utilize that build process to prepare for some data. The .openshift/action_hooks/build
checks whether WordPress is created on OpenShift, if not it will download the WordPress from WordPress.org, create necessary directory, extract and copy content of the WordPress source files into the correct location. Since the second deployment, that build script does almost nothing because WordPress has been installed. To customize these build script, we have to know the environment variables.
The OpenShift Environment Variables
During our build and document process, we will need to know some OpenShift information such as the document root path, the data path, and the application name. This information is available in environmental variables for which a full list can be access here.
Some variables that we'll use frequently is as follows:
-
OPENSHIFT_HOMEDIR. home directory path. On your local machine, Linux you will have your user home directory in
/home/username
or on Mac OS X it's/Users/username
. Home directory is the folder you will be in right there when you remote access via SSH. It's/var/lib/openshift/user_account_id
. For example, my own is/var/lib/openshift/532bd7655004468bcf0000e1
. -
OPENSHIFT_REPO_DIR.
$OPENSHIFT_HOMEDIR/app-root/runtime/repo/
. Repository containing the currently deployed version (of the application). It's exactly the same with whatever you have inside your repository on your local machine with an exception that php folder now is symbolic link point to document root; therefore,$OPENSHIFT_REPO_DIR/php
can be used in build script to reference to document root.
-
OPENSHIFT_DATA_DIR.
$OPENSHIFT_HOMEDIR/app-root/data/
- OPENSHIFT_APP_UUID. The unique id of your app on OpenShift. UUID can be very handy when you start to generate paths.
We access these variable in our build script with $variable_name.
The Custom Build and Deployment Process
Let's look back our current repository structure:
We'll start with a Hello World action so we have a sense of what will be output, when and how as we customize the build script.
Your Hello World Build
Let append this echo "Hello world. This is invoked before building."
into your ./openshift/pre_build
$ echo "echo \"Hello world. This is invoke before building.\"" >> .openshift/action_hooks/pre_buildPush to the repository and you will see the output like this:
$ git add .openshift/action_hooks/pre_build $ git commit -m "Hello world for pre_build" $ git push Counting objects: 9, done. Delta compression using up to 4 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 411 bytes | 0 bytes/s, done. Total 5 (delta 4), reused 0 (delta 0) remote: Stopping MySQL 5.5 cartridge remote: Stopping PHP 5.4 cartridge (Apache+mod_php) remote: Waiting for stop to finish remote: Stopping PHPMyAdmin cartridge remote: Waiting for stop to finish remote: Building git ref 'master', commit 1f4ef8a remote: Hello world. This is invoke before building remote: Checking .openshift/pear.txt for PEAR dependency.. remote: Do we need to run WordPress install remote: Preparing build for deployment remote: Deployment id is d06b1d4a remote: Activating deployment remote: Starting MySQL 5.5 cartridge remote: Starting PHPMyAdmin cartridge remote: Hello world. This is invoke when deploying remote: Copying WordPress plugins from .openshift/plugins remote: Copying WordPress themes from .openshift/themes remote: Database already configured. remote: Starting PHP 5.4 cartridge (Apache+mod_php) remote: Application directory "php/" selected as DocumentRoot remote: Hello world. This is invoke after deploying remote: ------------------------- remote: Git Post-Receive Result: success remote: Activation status: success remote: Deployment completed with status: success To ssh://[email protected]/~/git/demo2.git/ 1e7ad85..1f4ef8a master -> masterAs you see, our message appears during build process. Now, let's do a real thing to copy files during build process.
Copying File to Document Root
If you recall previous step, the file in .openshift/themes
and .openshift/plugins
is copied to wp-content/themes
and wp-content/plugins
. Let's say we want to do the same for copying file to the document root.
You want to create a sub folder call resume
and put a file resume/my_resume.txt
and make it access via demo2-tutsplus.rhc-cloud.com/resume/my_resume.txt
. Let's create a directory to hold the data that we will copy into document root. We create a folder call docroot
inside .openshift
and whatever inside it will be copied.
Let's open .openshift/action_hooks/deploy
, notice line 49 (I make it bold)
#!/bin/bash # This deploy hook gets executed after dependencies are resolved and the # build hook has been run but before the application has been started back # up again. This script gets executed directly, so it could be python, php, # ruby, etc. echo "Hello world. This is invoke when deploying" dest_dir=${OPENSHIFT_DATA_DIR}current current_version=$(cat ${OPENSHIFT_BUILD_DEPENDENCIES_DIR}.current_version) install_dir=${OPENSHIFT_BUILD_DEPENDENCIES_DIR}${current_version} if [ ! -d "${dest_dir}" ]; then mkdir -p $dest_dir cp -rf ${install_dir}/* ${dest_dir}/ fi # Replace the php/ directory with provided clean Wordpress installation # if [ -d ${OPENSHIFT_REPO_DIR}php ]; then rm -rf ${OPENSHIFT_REPO_DIR}php fi ln -sf ${dest_dir} ${OPENSHIFT_REPO_DIR}php if [ ! -d ${OPENSHIFT_DATA_DIR}uploads ]; then mkdir ${OPENSHIFT_DATA_DIR}uploads fi # If this is initial installation, copy the default themes and plugins # from official Wordpress installation # if [ ! -d ${OPENSHIFT_DATA_DIR}plugins ]; then mv ${dest_dir}/wp-content/plugins ${OPENSHIFT_DATA_DIR}plugins fi if [ ! -d ${OPENSHIFT_DATA_DIR}themes ]; then mv ${dest_dir}/wp-content/themes ${OPENSHIFT_DATA_DIR}themes fi # Users can place their own plugins and themes into .openshift/ directory # inside their GIT repository. # echo "Copying WordPress plugins from .openshift/plugins" cp -rf $OPENSHIFT_REPO_DIR/.openshift/plugins/* ${OPENSHIFT_DATA_DIR}plugins/ 2>/dev/null echo "Copying WordPress themes from .openshift/themes" cp -rf $OPENSHIFT_REPO_DIR/.openshift/themes/* ${OPENSHIFT_DATA_DIR}themes/ 2>/dev/null
# We will copy file here
echo "Copying custom file from .openshift/docroot" cp -rf $OPENSHIFT_REPO_DIR/.openshift/docroot/* ${OPENSHIFT_REPO_DIR}php/
# Add multisite upload dir # if [ ! -d $OPENSHIFT_DATA_DIR/blogs.dir ]; then mkdir $OPENSHIFT_DATA_DIR/blogs.dir fi ln -sf ${OPENSHIFT_DATA_DIR}blogs.dir ${OPENSHIFT_REPO_DIR}php/wp-content/ ln -sf ${OPENSHIFT_DATA_DIR}plugins ${OPENSHIFT_REPO_DIR}php/wp-content/ ln -sf ${OPENSHIFT_DATA_DIR}themes ${OPENSHIFT_REPO_DIR}php/wp-content/ ln -sf ${OPENSHIFT_DATA_DIR}uploads ${OPENSHIFT_REPO_DIR}php/wp-content/ set -e if [ -z "$OPENSHIFT_MYSQL_DB_HOST" ] then echo 1>&2 echo "Could not find mysql database. Please run:" 1>&2 echo "rhc cartridge add -a $OPENSHIFT_APP_NAME -c mysql-5.1" 1>&2 echo "then make a sample commit (add whitespace somewhere) and re-push" 1>&2 echo 1>&2 fi if [ -z "$OPENSHIFT_MYSQL_DB_HOST" ] then exit 5 fi # Confirm database exists, if not create it if ! /usr/bin/mysql -u "$OPENSHIFT_MYSQL_DB_USERNAME" --password="$OPENSHIFT_MYSQL_DB_PASSWORD" -h "$OPENSHIFT_MYSQL_DB_HOST" -P "$OPENSHIFT_MYSQL_DB_PORT" -e "select * from wp_commentmeta;" "$OPENSHIFT_APP_NAME" > /dev/null 2>&1 then echo echo "Database schema not yet added, WordPress is ready for install by visiting the site." else echo "Database already configured." fi
We added this command after that.
# We will copy file here echo "Copying custom file from .openshift/docroot" cp -rf $OPENSHIFT_REPO_DIR/.openshift/docroot/* ${OPENSHIFT_REPO_DIR}php/
The line with # is comment, for our own reference. The echo line is just to show some output. The real command we used is cp to recursively copy all files and folders.
Now, let put something in .openshift/docroot
and deploy.
☁ demo2 [master] ⚡ mkdir -p .openshift/docroot/resume/ ☁ demo2 [master] ⚡ echo "Hi there" > .openshift/docroot/resume/my_resume.txt ☁ demo2 [master] ⚡ git add .openshift/ ☁ demo2 [master] ⚡ git commit -m "Custom hook for file copy" [master 46235a2] Custom hook for file copy 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 .openshift/docroot/hi.txt ☁ demo2 [master] git push Counting objects: 13, done. Delta compression using up to 4 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (8/8), 723 bytes | 0 bytes/s, done. Total 8 (delta 4), reused 0 (delta 0) remote: Stopping MySQL 5.5 cartridge remote: Stopping PHP 5.4 cartridge (Apache+mod_php) remote: Waiting for stop to finish remote: Stopping PHPMyAdmin cartridge remote: Waiting for stop to finish remote: Waiting for stop to finish remote: Waiting for stop to finish remote: Waiting for stop to finish remote: Waiting for stop to finish remote: Waiting for stop to finish remote: Building git ref 'master', commit 46235a2 remote: Hello world. This is invoke before building remote: Checking .openshift/pear.txt for PEAR dependency.. remote: Do we need to run WordPress install remote: Preparing build for deployment remote: Deployment id is fe0803a9 remote: Activating deployment remote: Starting MySQL 5.5 cartridge remote: Starting PHPMyAdmin cartridge remote: Hello world. This is invoke when deploying remote: Copying WordPress plugins from .openshift/plugins remote: Copying WordPress themes from .openshift/themes remote: Copying custom file from .openshift/docroot remote: Database already configured. remote: Starting PHP 5.4 cartridge (Apache+mod_php) remote: Application directory "php/" selected as DocumentRoot remote: Hello world. This is invoke after deploying remote: ------------------------- remote: Git Post-Receive Result: success remote: Activation status: success remote: Deployment completed with status: success To ssh://[email protected]/~/git/demo2.git/ 1f4ef8a..46235a2 master -> master ☁ demo2 [master] curl http://openshift.axcoto.com/resume/my_resume.txt Hi there ☁ demo2 [master]
Your Exercise
Use the php
folder in your repository as a way to store this content, instead of introducing .openshift/docroot
.
Hint
app-deployments/current/repo
holds exactly same copy of your repository. Whatever you have on your local machine will be here.
Troubleshoot and Maintain
In the previous part, you knew how to remote access to your application with SSH. Once you are in, you can use Linux command.
$ ssh [email protected]
However, rhc come with command ssh allow you to connect into an app. Quickly and easy to remember.
$ rhc ssh demo2
From these, you can always use help
to show available commands.
-
tail_all: tail all of your log. You can see real time logging with this command for all gears in system: such as access log of Apache, MySQL error log.
-
mysql drops you into a MySQL shell. Very handy comparing with typing a long mysql command with host name, user string and password.
-
export show all current environment variables. During working with build script, you can use this command to see the list of available environment variables.
- gear to control your gear: start, stop, restart. Like you can restart apache, stop mysql.
-
snapshot snapshot take a full backup of your current WordPress with all file, database dump, and media data. A very good way to have a full back-up of your site.
- quota show your disk quota. Useful when you cannot upload to WordPress anymore, you may run out of space.
Taking a Snapshot
rhc snapshot-save demo2
dump your database, compress the media file, and source code, putting together a tar file and download it for you.
$ rhc snapshot-save demo2 Pulling down a snapshot to demo2.tar.gz... Creating and sending tar.gz $ ls | grep tar.gz demo2.tar.gz
By default, a tar file with same name as your app is created. Store it somewhere for your shake. Once you have the snapshot saved, you can restore as well.
$ rhc snapshot-restore demo2 Restoring from snapshot demo2.tar.gz... Removing old git repo: ~/git/demo2.git/ Removing old data dir: ~/app-root/data/* Restoring ~/git/demo2.git and ~/app-root/data
Checking Gear Status
The gear
command controls cartridge status, start/stop. Like you get a timeout error when visiting your domain, or some 404, 503 error, or a database error. You have to SSH into your app and check gear status:
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear status
Cart to get the status for?
1. mysql-5.5
2. php-5.4
3. phpmyadmin-4
? 2
ATTR: status=ALREADY_STOPPED
ATTR: quota_blocks=1048576
ATTR: quota_files=80000
CLIENT_RESULT: Application is either stopped or inaccessible
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\>
If it's saying CLIENT_RESULT Application is either stopped or inaccessible, I have to start it with:
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear start --cart php-5.4 Starting PHP 5.4 cartridge (Apache+mod_php) Application directory "php/" selected as DocumentRoot [demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\>
The next step is to consult your log file.
# Confirm it's working now
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear status Cart to get the status for? 1. mysql-5.5 2. php-5.4 3. phpmyadmin-4 ? 2 ATTR: quota_blocks=1048576 ATTR: quota_files=80000 CLIENT_RESULT: Application is running CLIENT_RESULT: %
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\>
Logging
tail_all show you completed logs of all cartridge in real time. However, if you want to look at an individual log, here is the list:
-
php/logs
access and error log of Apache and MySQL -
mysql/log
MySQL log
Port Forwarding
The rhc port-forward
command can help you establish a local
connection to your hosted service(Web server, Database server...). OpenShift automatically checks available ports on your local system and forwards one to a remote port of running service. Via port forwarding, you can work on local machine but the connection is forward to remote machine.
Let's try with MySQL.
$ rhc port-forward demo2 Checking available ports ... done Forwarding ports ... Address already in use - bind(2) while forwarding port 8080. Trying local port 8081 Address already in use - bind(2) while forwarding port 3306. Trying local port 3307 To connect to a service running on OpenShift, use the Local address Service Local OpenShift ------- -------------- ---- ---------------- httpd 127.0.0.1:8080 => 127.2.126.1:8080 httpd 127.0.0.1:8081 => 127.2.126.3:8080 mysql 127.0.0.1:3307 => 127.2.126.2:3306 Press CTRL-C to terminate port forwarding
I had port 8080 and 3306 for my different apps. Therefore, OpenShift picked up 3307 for MySQL. Now I can use the MySQL credential to connect to it with Sequel Pro. If you forgot your password, you can get it again on OpenShift dashboard or SSH into server, and issue:
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> export | grep MYSQL declare -x OPENSHIFT_MYSQL_DB_HOST="127.2.126.2" declare -x OPENSHIFT_MYSQL_DB_LOG_DIR="/var/lib/openshift/532bd7655004468bcf0000e1/mysql//log/" declare -x OPENSHIFT_MYSQL_DB_PASSWORD="DyANqgKAFbTT" declare -x OPENSHIFT_MYSQL_DB_PORT="3306" declare -x OPENSHIFT_MYSQL_DB_SOCKET="/var/lib/openshift/532bd7655004468bcf0000e1/mysql//socket/mysql.sock" declare -x OPENSHIFT_MYSQL_DB_URL="mysql://adminL1GxwjI:[email protected]:3306/" declare -x OPENSHIFT_MYSQL_DB_USERNAME="adminL1GxwjI" declare -x OPENSHIFT_MYSQL_DIR="/var/lib/openshift/532bd7655004468bcf0000e1/mysql/" declare -x OPENSHIFT_MYSQL_IDENT="redhat:mysql:5.5:0.2.9" declare -x OPENSHIFT_MYSQL_LD_LIBRARY_PATH_ELEMENT="/opt/rh/mysql55/root/usr/lib64"
Using Sequel Pro to connect to it.
Synchronize Local and Live Environments
Everybody loves to develop on a local machine instead of uploading to server for testing or evaluate a feature. You may export data from live host and import on local machine for that purpose like in this tutorial. However, that exporting process is annoying. The data can be big, take longer and longer to export/import. Fixing bug is harder, too. If a bug only happens on a particular post/page on live site, without re-producing the exactly post/page content, it can be hard to debug on local environment.
Or if you are a remote team, and you have your team created lots of test post on a staging/testing area (hosting on OpenShift), it will be good if you have a good way to just synchronize everything back, specially the pictures data.
Therefore, I propose a method to achieve that with: port forwarding and host file editing. Using port forwarding as we saw above, we can access MySQL easily from local machine. With the help of editing host file, we can point the domain openshift.axcoto.com to local machine, instead of to OpenShift. In our clone repository, we have an empty php
folder. When deploying, that folder is replaced by a symbolic link to document root of Apache. Now, we will use that folder as document root on our local machine. Recall the repository structure again, on my computer.
☁ demo2 [master] ⚡ pwd /Users/kureikain/Sites/demo2 ☁ demo2 [master] ⚡ ls -la total 24 drwxr-xr-x 10 kureikain staff 340 Mar 21 00:39 . drwxr-xr-x@ 57 kureikain staff 1938 Mar 21 00:38 .. drwxr-xr-x 16 kureikain staff 544 Mar 28 01:20 .git -rw-r--r-- 1 kureikain staff 9 Mar 21 00:39 .gitignore drwxr-xr-x 11 kureikain staff 374 Mar 25 23:42 .openshift -rw-r--r-- 1 kureikain staff 2243 Mar 21 00:39 README -rw-r--r-- 1 kureikain staff 2201 Mar 21 00:39 README.md drwxr-xr-x 3 kureikain staff 102 Mar 21 00:39 libs drwxr-xr-x 3 kureikain staff 102 Mar 21 00:39 misc drwxr-xr-x 7 kureikain staff 238 Mar 28 01:05 php
Note that, to succeed at this method, you should add whatever you have in wp-content/plugins(default WordPress 3.8.1 plugins) and wp-content/themes(default WordPress 3.8.1 themes) on OpenShift into your Git repository. You can download it via scp or SFTP as we discuss in the previous article, or you can simply download the default ones from WordPress.
Just make sure your local repository .openshift/themes
and .openshift/plugins
has same thing with the wp-content/themes
and wp-content/plugins
folder of WordPress app on OpenShift.
Step 1: Port Forwarding
Using command rhc port-forward demo2
, with demo2 is my app. Change it to your app name.
Step 2: Virtual Host
Using Apache, we will add one more entry for our domain point to folder hold our WordPress. Depending on your OS, you may have different location for Apache configuration. It can be /etc/apache2
or /etc/httpd
.
For example, on my Mac, it's /etc/apache2
. I will add below code to my /etc/apache2/httpd.conf
, or /etc/apache2/extra/httpd-vhosts.conf
depend your OS, or where you prefer.
<VirtualHost *:80> ServerName openshift.axcoto.com DocumentRoot "/Users/kureikain/Sites/demo2/php" <Directory "/Users/kureikain/Sites/demo2/php"> Order allow,deny Allow from all </Directory> </VirtualHost>If you are not familiar with Apache and Virtual host, some article will helps:
- http://code.tutsplus.com/articles/apache-2-basic-configuration-on-unix-like-systems--net-26607
- http://code.tutsplus.com/articles/how-to-setup-a-wordpress-development-environment-for-windows--wp-2...
- http://code.tutsplus.com/tutorials/wordpress-development-and-deployment-with-mamp-git-and-dropbox--w...
Step 3: Environment Variable
When running on your local machine, you won't have the environment variable available. We have to define in somewhere. For a simple starting, I prefer to put these variable directly in Apache config file with SetEnv direction.
Our virtual host entry become:
<VirtualHost *:80>I grab the environment variable of OpenShift and just put it into our config file. But I change the MySQL host to 127.0.0.1 and MySQL Port to 3307 because we do port forwarding before.
SetEnv OPENSHIFT_SECRET_TOKEN "kCsELz-GJnho4I0M9XemTiZ47Jn4_QCSONFL5We8zw3Tgg572ivNEQQgZeIKQkTo2kE>
SetEnv OPENSHIFT_APP_UUID 532bd7655004468bcf0000e1
SetEnv OPENSHIFT_APP_NAME demo2 SetEnv OPENSHIFT_MYSQL_DB_USERNAME adminL1GxwjI SetEnv OPENSHIFT_MYSQL_DB_PASSWORD DyANqgKAFbTT SetEnv OPENSHIFT_MYSQL_DB_HOST "127.0.0.1" SetEnv OPENSHIFT_MYSQL_DB_PORT 3307 ServerName openshift.axcoto.com ServerAdmin [email protected] DocumentRoot "/Users/kureikain/Sites/demo2/php" <Directory "/Users/kureikain/Sites/demo2/php"> Order allow,deny Allow from all </Directory> ErrorLog "/var/log/apache2/openshift.axcoto.com-error_log" CustomLog "/var/log/apache2/openshift.axcoto.com-access_log" common </VirtualHost>
Step 4: Changing the Host File
openshift.axcoto.com is configured to point to OpenShift. However, we can override it by directly editing /etc/hosts
. Open that file with you favorite editor and append
127.0.0.1 openshift.axcoto.comConfirm that it's pointing to our local machine.
☁ ~ ping openshift.axcoto.com PING openshift.axcoto.com (127.0.0.1): 56 data bytes 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.055 ms 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.165 ms ^C --- openshift.axcoto.com ping statistics --- 2 packets transmitted, 2 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 0.055/0.110/0.165/0.055 ms
If you want to visit the real app on OpenShift, comment out that line in /etc/hosts. Put a "#" to comment out:
# 127.0.0.1 openshift.axcoto.comThen openshift.axcoto.com will point to live site again.
Step 5: Pull WordPress Core File and Sync Media From Live Site
Finally, we have to copy the media and WordPress file into our local environment. We also make the symbolic link to point php/wp-content/themes
to .openshift/theme
. The same concept applies for plugin, php/wp-content/plugins
point to .openshift/plugins
. This way we can working on .openshift/themes and .openshift/plugins
and can refresh browser to see our change.
$ cd php $ rm -rf ./*
# make snapshot to the specified file name.
$ rhc snapshot save demo2 --filepath snap.tar.gz
# extract it
$ tar xzf snap.tar.gz
# we got it now
$ ls 532bd7655004468bcf0000e1 snap.tar.gz
# the 532bd7655004468bcf0000e1 is out extracted snapshot # it can be different on you app. $ cp -rf 532bd7655004468bcf0000e1/app-root/data/current/*
# link the themes folder $ ln -s `pwd`/../.openshift/themes wp-content/themes
#link the plugin folder
$ ln -s `pwd`/../.openshift/plugins wp-content/plugins # Link .openshift folder itself because it has some special thing inside
$ ln -s `pwd`/../.openshift .openshift
# copy upload files $ cp -rf 532bd7655004468bcf0000e1/app-root/data/uploads wp-content # clean up $ rm -rf 532bd7655004468bcf0000e1 snap.tar.gz
The first time you want to sync the data, you run these commands; however, since the second time, we don't want to pull all of file because partial of files were there. A better option is only sync uploads file. We can do that with scp:
$ cd ~/Site/demo2/php $ scp -r [email protected]:app-root/data/uploads wp-content/
Or with rsync. Rsync is much better because it only download the not exist file. Same file won't be downloaded again.
$ cd ~/Site/demo2/php
$ rsync -av --partial --progress --rsh="ssh " [email protected]:app-root/data/uploads wp-content
You may go further, put these commands into a shell script and track it with your Git repository too. I will leave that part for you :)
You may want to ignore file inside php because those file are just for our own testing/running on local computer. No need to track them.
$ echo "php/*" >> .gitignore
Step 6: Administration Over SSL (Optional)
The wp-config.php
, that OpenShift generated, defined to serve administrator over SSL
<?php // wp-config.php //... /** * We prefer to be secure by default */ define('FORCE_SSL_ADMIN', true);On your computer, you usually don't have SSL certificate. You may edit
wp-config.php
and set FORCE_SSL_ADMIN
to false. If you want challenge, and want to give it a try to run a SSL connection then here is the instruction. Generate SSL certificate
This is self-sign certificate meaning that browser won't trust it. It's fine because we are working on local anyway and you can just add an exception when the browser throw an untrusted warning.
$ sudo mkidr -p /etc/apache2/ssl # make sure you type correct domain $ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt
We create the folder /etc/apache2/ssl
, then generate the cert and key into that folder. We will config apache point to these two files later.
Define Virtual Host Entry
Open your /etc/apache/httpd.conf
(again, your Apache config file can be in different folder, such as /etc/httpd
), find the line Listen 80
and append Listen 443
Listen 80 Listen 443
On top of your /etc/apache2/extra/httpd-vhost.conf
, find the line NameVirtualHost *:80
and append
NameVirtualHost *:443
Next, we define one more entry in virtual host for port 443. We just duplicate the previous definition with port 80, but this time, we add some SSL definition.
<VirtualHost *:443> SetEnv OPENSHIFT_SECRET_TOKEN "kCsELz-GJnho4I0M9XemTiZ47Jn4_QCSONFL5We8zw3Tgg572ivNEQQgZeIKQkTo2kEwUHWjpsO7fhy1FeVqDlyRzSsKg6-fWNDWJaj9hO65nwVqE5auj35R2F9RNvEk" SetEnv OPENSHIFT_APP_UUID 532bd7655004468bcf0000e1 SetEnv OPENSHIFT_APP_NAME demo2 SetEnv OPENSHIFT_MYSQL_DB_USERNAME adminL1GxwjI SetEnv OPENSHIFT_MYSQL_DB_PASSWORD DyANqgKAFbTT SetEnv OPENSHIFT_MYSQL_DB_HOST "127.0.0.1" SetEnv OPENSHIFT_MYSQL_DB_PORT 3307 ServerName openshift.axcoto.com ServerAdmin [email protected] DocumentRoot "/Users/kureikain/Sites/demo2/php" <Directory "/Users/kureikain/Sites/demo2/php"> Order allow,deny Allow from all </Directory> ErrorLog "/var/log/apache2/openshift.axcoto.com-error_log" CustomLog "/var/log/apache2/openshift.axcoto.com-access_log" common SSLEngine On SSLCertificateFile /etc/apache2/ssl/apache.crt SSLCertificateKeyFile /etc/apache2/ssl/apache.key <Location /> SSLRequireSSL On SSLVerifyClient optional SSLVerifyDepth 1 SSLOptions +StdEnvVars +StrictRequire </Location> </VirtualHost>
Note the SSL certificate file path. Restart Apache with
sudo apachectl restart
. Now, you can access your dashboard over SSL. Here is my WordPress installation, running totally local with same database from live site, and media data is synced.Conclusion
Throughout this series, we gained a lot of knowledge about OpenShift. You should not be able to easily install and configure WordPress on OpenShift. With the handy of rhc client,
you can quickly config or viewing app information from terminal.
We also covered build and deploy scripts so you can customize your application to your needs like showing a special banner, and a push to HipChat during deployment. You can even sync data between your local computer and OpenShift. I hope you enjoy this tutorial and OpenShift.
Leaving comment to let us know how you are doing. If you run into trouble, let me know in the comment, I would like to help.
Comments