Advertisement
  1. Code
  2. WordPress

Running WordPress on OpenShift Part 2

Scroll to top
Read Time: 28 min

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:

1
sudo gem install rhc

Then setup it with your username and password. When you are asked to Generate a token now? Type Yes.

1
rhc setup# Once it's done, you should see something similar:Saving configuration to /Users/kureikain/.openshift/express.conf ... done

2


3
Checking for git ... found git version 1.8.5.2 (Apple Git-48)

4


5
Checking common problems .. done

6


7
Checking for a domain ... tutsplus

8


9
Checking for applications ... found 2

10


11
  demo2 https://demo2-tutsplus.rhcloud.com/

12
  php   http://php-tutsplus.rhcloud.com/

13


14
  You are using 3 of 3 total gears

15
  The following gear sizes are available to you: small

16


17
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.

1
$ rhc helpGetting started:
2
  setup              Connects to OpenShift and sets up your keys and domain
3
  create-app         Create an application
4
  apps               List all your applications
5
  cartridges         List available cartridges
6
  add-cartridge      Add a cartridge to your application
7
  set-env            Set one or more environment variable(s) to your application
8
  logout             End the current session
9
10
Working with apps:
11
  tail               Tail the logs of an application
12
  port-forward       Forward remote ports to the workstation
13
  threaddump         Trigger a thread dump for JBoss and Ruby apps
14
  snapshot           Save the current state of your application locally
15
  git-clone          Clone and configure an application's repository locally

16


17
Management commands:

18
  account            Display details about your OpenShift account

19
  alias              Add or remove a custom domain name for an app

20
  app                Commands for creating and managing applications

21
  authorization      Manage your authorization tokens

22
  cartridge          Manage your application cartridges

23
  deployment         Commands for deploying and managing deployments of an

24
                     application

25
  domain             Add or rename the container for your apps

26
  env                Manages user-defined environment variables set on a given

27
                     application

28
  member             Manage membership on domains

29
  server             Display information about the status of the OpenShift

30
                     service

31
  ssh                SSH into the specified application

32
  sshkey             Add and remove keys for Git and SSH$ rhc help appUsage: rhc app <action>Creates and controls an OpenShift application.  To see the list of all applications use the rhc domain show command.  Note that deleteis not reversible and will stop your application and then remove the application and repo from the remote server. No local changes aremade.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:


1
$ rhc ssh demo2
2
# Output 
3
Connecting to 532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com ...

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:

1
# Deploy branch master on demo2 app

2
$ rhc app-deploy master -a demo2
3
4
# Deploy bracch branch/deploy on demo2 app

5
$ rhc app-deploy branch/deploy -a demo2

Or show app information:


1
demo2 [master] ⚡ rhc app-show demo2
2
demo2 @ http://demo2-tutsplus.rhcloud.com/ (uuid: 532bd7655004468bcf0000e1)
3
---------------------------------------------------------------------------
4
  Domain:          tutsplus
5
  Created:         Mar 20 11:08 PM
6
  Gears:           1 (defaults to small)
7
  Git URL:         ssh://532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com/~/git/demo2.git/
8
  Initial Git URL: https://github.com/openshift/wordpress-example.git
9
  SSH:             532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com
10
  Deployment:      auto (on git push)
11
  Aliases:         openshift.axcoto.com
12
13
  mysql-5.5 (MySQL 5.5)
14
  ---------------------
15
    Gears:          Located with php-5.4, phpmyadmin-4
16
    Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
17
    Database Name:  demo2
18
    Password:       DyANqgKAFbTT
19
    Username:       adminL1GxwjI
20
21
  php-5.4 (PHP 5.4)
22
  -----------------
23
    Gears: Located with mysql-5.5, phpmyadmin-4
24
25
  phpmyadmin-4 (phpMyAdmin 4.0)
26
  -----------------------------
27
    Gears:          Located with mysql-5.5, php-5.4
28
    Connection URL: https://demo2-tutsplus.rhcloud.com/phpmyadmin/

You can also save a snapshot of current app:

1
$ rhc snapshot-save demo2
2
Pulling down a snapshot to demo2.tar.gz...
3
Creating and sending tar.gz
4
5
RESULT:
6
Success

Or you can add some cartridges:

1
# add mysql-5.5 cartridge into our app
2
$ rhc cartridge add -a demo2 -c mysql-5.1
3
4
# add php5-4  cartridge into our app
5
$ 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:

  1. You run a git push on your computer, your changes are sent to your OpenShift application
  2. The application is shut down
  3. Your changes are copied on the server into the correct location
  4. OpenShift invokes your build hooks - script files you've placed in your Git repository
  5. 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:

  1. Pre-Receive. During your push, OpenShift checks to ensure that your application is in a consistent state. There is no hook for this step.
  2. 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
  3. 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.
  4. 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.
  5. 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.

1
#!/bin/bash
Or Ruby
1
#!/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:

  1. 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.
  2. 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.
  3. OPENSHIFT_DATA_DIR. $OPENSHIFT_HOMEDIR/app-root/data/
  4. 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

1
$ echo "echo \"Hello world. This is invoke before building.\"" >> .openshift/action_hooks/pre_build
Push to the repository and you will see the output like this:
1
$ git add .openshift/action_hooks/pre_build
2
$ git commit -m "Hello world for pre_build"
3
$ git push
4
5
Counting objects: 9, done.
6
Delta compression using up to 4 threads.
7
Compressing objects: 100% (5/5), done.
8
Writing objects: 100% (5/5), 411 bytes | 0 bytes/s, done.
9
Total 5 (delta 4), reused 0 (delta 0)
10
remote: Stopping MySQL 5.5 cartridge
11
remote: Stopping PHP 5.4 cartridge (Apache+mod_php)
12
remote: Waiting for stop to finish
13
remote: Stopping PHPMyAdmin cartridge
14
remote: Waiting for stop to finish
15
remote: Building git ref 'master', commit 1f4ef8a
16
remote: Hello world. This is invoke before building
17
remote: Checking .openshift/pear.txt for PEAR dependency..
18
remote: Do we need to run WordPress install

19
remote: Preparing build for deployment
20
remote: Deployment id is d06b1d4a
21
remote: Activating deployment
22
remote: Starting MySQL 5.5 cartridge
23
remote: Starting PHPMyAdmin cartridge
24
remote: Hello world. This is invoke when deploying
25
remote: Copying WordPress plugins from .openshift/plugins
26
remote: Copying WordPress themes from .openshift/themes
27
remote: Database already configured.
28
remote: Starting PHP 5.4 cartridge (Apache+mod_php)
29
remote: Application directory "php/" selected as DocumentRoot
30
remote: Hello world. This is invoke after deploying
31
remote: -------------------------
32
remote: Git Post-Receive Result: success
33
remote: Activation status: success
34
remote: Deployment completed with status: success
35
To ssh://532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com/~/git/demo2.git/
36
   1e7ad85..1f4ef8a  master -> master
As 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)

1
#!/bin/bash

2
3
# This deploy hook gets executed after dependencies are resolved and the

4
# build hook has been run but before the application has been started back

5
# up again.  This script gets executed directly, so it could be python, php,

6
# ruby, etc.

7
8
echo "Hello world. This is invoke when deploying"
9
dest_dir=${OPENSHIFT_DATA_DIR}current
10
11
current_version=$(cat ${OPENSHIFT_BUILD_DEPENDENCIES_DIR}.current_version)
12
install_dir=${OPENSHIFT_BUILD_DEPENDENCIES_DIR}${current_version}
13
14
if [ ! -d "${dest_dir}" ]; then

15
  mkdir -p $dest_dir
16
  cp -rf ${install_dir}/* ${dest_dir}/
17
fi
18
19
# Replace the php/ directory with provided clean Wordpress installation

20
#

21
if [ -d ${OPENSHIFT_REPO_DIR}php ]; then

22
  rm -rf ${OPENSHIFT_REPO_DIR}php
23
fi

24
ln -sf ${dest_dir} ${OPENSHIFT_REPO_DIR}php
25
26
if [ ! -d ${OPENSHIFT_DATA_DIR}uploads ]; then

27
    mkdir ${OPENSHIFT_DATA_DIR}uploads
28
fi
29
30
31
# If this is initial installation, copy the default themes and plugins

32
# from official Wordpress installation

33
#

34
if [ ! -d ${OPENSHIFT_DATA_DIR}plugins ]; then

35
  mv ${dest_dir}/wp-content/plugins ${OPENSHIFT_DATA_DIR}plugins
36
fi

37


38
if [ ! -d ${OPENSHIFT_DATA_DIR}themes ]; then

39
  mv ${dest_dir}/wp-content/themes ${OPENSHIFT_DATA_DIR}themes
40
fi
41
42
# Users can place their own plugins and themes into .openshift/ directory

43
# inside their GIT repository.

44
#

45
echo "Copying WordPress plugins from .openshift/plugins"
46
cp -rf $OPENSHIFT_REPO_DIR/.openshift/plugins/* ${OPENSHIFT_DATA_DIR}plugins/ 2>/dev/null
47
48
echo "Copying WordPress themes from .openshift/themes"
49
cp -rf $OPENSHIFT_REPO_DIR/.openshift/themes/* ${OPENSHIFT_DATA_DIR}themes/ 2>/dev/null
50
# We will copy file hereecho "Copying custom file from .openshift/docroot"

51
cp -rf $OPENSHIFT_REPO_DIR/.openshift/docroot/* ${OPENSHIFT_REPO_DIR}php/
52
53
# Add multisite upload dir

54
#

55
if [ ! -d $OPENSHIFT_DATA_DIR/blogs.dir ]; then

56
    mkdir $OPENSHIFT_DATA_DIR/blogs.dir
57
fi

58


59
ln -sf ${OPENSHIFT_DATA_DIR}blogs.dir ${OPENSHIFT_REPO_DIR}php/wp-content/
60
ln -sf ${OPENSHIFT_DATA_DIR}plugins   ${OPENSHIFT_REPO_DIR}php/wp-content/
61
ln -sf ${OPENSHIFT_DATA_DIR}themes    ${OPENSHIFT_REPO_DIR}php/wp-content/
62
ln -sf ${OPENSHIFT_DATA_DIR}uploads   ${OPENSHIFT_REPO_DIR}php/wp-content/
63
64
set -e
65
66
if [ -z "$OPENSHIFT_MYSQL_DB_HOST" ]
67
then

68
    echo 1>&2
69
    echo "Could not find mysql database.  Please run:" 1>&2
70
    echo "rhc cartridge add -a $OPENSHIFT_APP_NAME -c mysql-5.1" 1>&2
71
    echo "then make a sample commit (add whitespace somewhere) and re-push" 1>&2
72
    echo 1>&2
73
fi

74


75
if [ -z "$OPENSHIFT_MYSQL_DB_HOST" ]
76
then

77
    exit 5
78
fi
79
80
# Confirm database exists, if not create it

81
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
82
then

83
    echo

84
    echo "Database schema not yet added, WordPress is ready for install by visiting the site."
85
else

86
    echo "Database already configured."
87
fi

We added this command after that.

1
# We will copy file here

2
echo "Copying custom file from .openshift/docroot"
3
cp -rf $OPENSHIFT_REPO_DIR/.openshift/docroot/* ${OPENSHIFT_REPO_DIR}php/
4

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.

1
☁  demo2 [master] ⚡ mkdir -p .openshift/docroot/resume/
2
☁  demo2 [master] ⚡ echo "Hi there" > .openshift/docroot/resume/my_resume.txt
3
☁  demo2 [master] ⚡ git add .openshift/
4
☁  demo2 [master] ⚡ git commit -m "Custom hook for file copy"
5
[master 46235a2] Custom hook for file copy
6
 3 files changed, 7 insertions(+), 1 deletion(-)
7
 create mode 100644 .openshift/docroot/hi.txt
8
☁  demo2 [master] git push
9
Counting objects: 13, done.
10
Delta compression using up to 4 threads.
11
Compressing objects: 100% (6/6), done.
12
Writing objects: 100% (8/8), 723 bytes | 0 bytes/s, done.
13
Total 8 (delta 4), reused 0 (delta 0)
14
remote: Stopping MySQL 5.5 cartridge
15
remote: Stopping PHP 5.4 cartridge (Apache+mod_php)
16
remote: Waiting for stop to finish
17
remote: Stopping PHPMyAdmin cartridge
18
remote: Waiting for stop to finish
19
remote: Waiting for stop to finish
20
remote: Waiting for stop to finish
21
remote: Waiting for stop to finish
22
remote: Waiting for stop to finish
23
remote: Waiting for stop to finish
24
remote: Building git ref 'master', commit 46235a2
25
remote: Hello world. This is invoke before building
26
remote: Checking .openshift/pear.txt for PEAR dependency..
27
remote: Do we need to run WordPress install

28
remote: Preparing build for deployment
29
remote: Deployment id is fe0803a9
30
remote: Activating deployment
31
remote: Starting MySQL 5.5 cartridge
32
remote: Starting PHPMyAdmin cartridge
33
remote: Hello world. This is invoke when deploying
34
remote: Copying WordPress plugins from .openshift/plugins
35
remote: Copying WordPress themes from .openshift/themes
36
remote: Copying custom file from .openshift/docroot
37
remote: Database already configured.
38
remote: Starting PHP 5.4 cartridge (Apache+mod_php)
39
remote: Application directory "php/" selected as DocumentRoot
40
remote: Hello world. This is invoke after deploying
41
remote: -------------------------
42
remote: Git Post-Receive Result: success
43
remote: Activation status: success
44
remote: Deployment completed with status: success
45
To ssh://532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com/~/git/demo2.git/
46
   1f4ef8a..46235a2  master -> master
47
☁  demo2 [master] curl http://openshift.axcoto.com/resume/my_resume.txt
48
Hi there
49
☁  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.

1
$ ssh 532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com

However, rhc come with command ssh allow you to connect into an app. Quickly and easy to remember.

1
$ rhc ssh demo2

From these, you can always use help to show available commands.

  1. 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.
  2. mysql drops you into a MySQL shell. Very handy comparing with typing a long mysql command with host name, user string and password.
  3. export show all current environment variables. During working with build script, you can use this command to see the list of available environment variables.
  4. gear to control your gear: start, stop, restart. Like you can restart apache, stop mysql.
  5. 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.
  6. 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. 

1
$ rhc snapshot-save demo2
2
Pulling down a snapshot to demo2.tar.gz...
3
Creating and sending tar.gz
4
$ ls | grep tar.gz
5
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.

1
$ rhc snapshot-restore demo2
2
Restoring from snapshot demo2.tar.gz...
3
Removing old git repo: ~/git/demo2.git/
4
Removing old data dir: ~/app-root/data/*
5
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:

1
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear statusCart to get the status for?1. mysql-5.52. php-5.43. phpmyadmin-4?  2ATTR: status=ALREADY_STOPPEDATTR: quota_blocks=1048576ATTR: quota_files=80000CLIENT_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:

1
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear start --cart php-5.4
2
Starting PHP 5.4 cartridge (Apache+mod_php)
3
Application directory "php/" selected as DocumentRoot
4
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\>
1
# Confirm it's working now[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> gear status

2
Cart to get the status for?
3
1. mysql-5.5
4
2. php-5.4
5
3. phpmyadmin-4
6
?  2
7
ATTR: quota_blocks=1048576
8
ATTR: quota_files=80000
9
CLIENT_RESULT: Application is running
10
CLIENT_RESULT: %
11
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\>
The next step is to consult your log file.

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:

  1. php/logs access and error log of Apache and MySQL
  2. 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.

1
$ rhc port-forward demo2
2
Checking available ports ... done

3
Forwarding ports ...
4
Address already in use - bind(2) while forwarding port 8080. Trying local port 8081
5
Address already in use - bind(2) while forwarding port 3306. Trying local port 3307
6
7
To connect to a service running on OpenShift, use the Local address
8
9
Service Local               OpenShift
10
------- -------------- ---- ----------------
11
httpd   127.0.0.1:8080  =>  127.2.126.1:8080
12
httpd   127.0.0.1:8081  =>  127.2.126.3:8080
13
mysql   127.0.0.1:3307  =>  127.2.126.2:3306
14
15
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:

1
[demo2-tutsplus.rhcloud.com 532bd7655004468bcf0000e1]\> export | grep MYSQL
2
declare -x OPENSHIFT_MYSQL_DB_HOST="127.2.126.2"
3
declare -x OPENSHIFT_MYSQL_DB_LOG_DIR="/var/lib/openshift/532bd7655004468bcf0000e1/mysql//log/"
4
declare -x OPENSHIFT_MYSQL_DB_PASSWORD="DyANqgKAFbTT"
5
declare -x OPENSHIFT_MYSQL_DB_PORT="3306"
6
declare -x OPENSHIFT_MYSQL_DB_SOCKET="/var/lib/openshift/532bd7655004468bcf0000e1/mysql//socket/mysql.sock"
7
declare -x OPENSHIFT_MYSQL_DB_URL="mysql://adminL1GxwjI:DyANqgKAFbTT@127.2.126.2:3306/"
8
declare -x OPENSHIFT_MYSQL_DB_USERNAME="adminL1GxwjI"
9
declare -x OPENSHIFT_MYSQL_DIR="/var/lib/openshift/532bd7655004468bcf0000e1/mysql/"
10
declare -x OPENSHIFT_MYSQL_IDENT="redhat:mysql:5.5:0.2.9"
11
declare -x OPENSHIFT_MYSQL_LD_LIBRARY_PATH_ELEMENT="/opt/rh/mysql55/root/usr/lib64"

Using Sequel Pro to connect to it.

With port forwarding, you can connect to the app easily using GUI program

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.

1
☁  demo2 [master] ⚡ pwd
2
/Users/kureikain/Sites/demo2
3
☁  demo2 [master] ⚡ ls -la
4
total 24
5
drwxr-xr-x  10 kureikain  staff   340 Mar 21 00:39 .
6
drwxr-xr-x@ 57 kureikain  staff  1938 Mar 21 00:38 ..
7
drwxr-xr-x  16 kureikain  staff   544 Mar 28 01:20 .git
8
-rw-r--r--   1 kureikain  staff     9 Mar 21 00:39 .gitignore
9
drwxr-xr-x  11 kureikain  staff   374 Mar 25 23:42 .openshift
10
-rw-r--r--   1 kureikain  staff  2243 Mar 21 00:39 README
11
-rw-r--r--   1 kureikain  staff  2201 Mar 21 00:39 README.md
12
drwxr-xr-x   3 kureikain  staff   102 Mar 21 00:39 libs
13
drwxr-xr-x   3 kureikain  staff   102 Mar 21 00:39 misc
14
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.

1
<VirtualHost *:80>
2
    ServerName openshift.axcoto.com
3
    DocumentRoot "/Users/kureikain/Sites/demo2/php"
4
    <Directory "/Users/kureikain/Sites/demo2/php">
5
      Order allow,deny
6
      Allow from all
7
    </Directory>
8
</VirtualHost>
If you are not familiar with Apache and Virtual host, some article will helps:
  1. https://code.tutsplus.com/articles/apache-2-basic-configuration-on-unix-like-systems--net-26607
  2. http://code.tutsplus.com/articles/how-to-setup-a-wordpress-development-environment-for-windows--wp-2...
  3. 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:

1
<VirtualHost *:80>
2
    SetEnv OPENSHIFT_SECRET_TOKEN  "kCsELz-GJnho4I0M9XemTiZ47Jn4_QCSONFL5We8zw3Tgg572ivNEQQgZeIKQkTo2kE>    SetEnv OPENSHIFT_APP_UUID 532bd7655004468bcf0000e1        SetEnv OPENSHIFT_APP_NAME demo2

3
    SetEnv OPENSHIFT_MYSQL_DB_USERNAME adminL1GxwjI

4
    SetEnv OPENSHIFT_MYSQL_DB_PASSWORD DyANqgKAFbTT

5
    SetEnv OPENSHIFT_MYSQL_DB_HOST "127.0.0.1"

6
    SetEnv OPENSHIFT_MYSQL_DB_PORT 3307

7


8
    ServerName openshift.axcoto.com

9
    ServerAdmin webmaster@dummy-host2.example.com

10
    DocumentRoot "/Users/kureikain/Sites/demo2/php"

11
    <Directory "/Users/kureikain/Sites/demo2/php">

12
      Order allow,deny

13
      Allow from all

14
    </Directory>

15
    

16
    ErrorLog "/var/log/apache2/openshift.axcoto.com-error_log"

17
    CustomLog "/var/log/apache2/openshift.axcoto.com-access_log" common

18


19
</VirtualHost>

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.

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

1
127.0.0.1    openshift.axcoto.com
Confirm that it's pointing to our local machine.

1
☁  ~  ping openshift.axcoto.com
2
PING openshift.axcoto.com (127.0.0.1): 56 data bytes
3
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.055 ms
4
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.165 ms
5
^C
6
--- openshift.axcoto.com ping statistics ---
7
2 packets transmitted, 2 packets received, 0.0% packet loss
8
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:

1
# 127.0.0.1     openshift.axcoto.com
Then 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.

1
$ cd php
2
$ 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

3
532bd7655004468bcf0000e1    snap.tar.gz# the 532bd7655004468bcf0000e1 is out extracted snapshot
4
# it can be different on you app.

5
$ cp -rf 532bd7655004468bcf0000e1/app-root/data/current/*
6
# link the themes folder

7
$ ln -s `pwd`/../.openshift/themes wp-content/themes#link the plugin folder$ ln -s `pwd`/../.openshift/plugins wp-content/plugins
8
# Link .openshift folder itself because it has some special thing inside$ ln -s `pwd`/../.openshift .openshift# copy upload files

9
$ cp -rf 532bd7655004468bcf0000e1/app-root/data/uploads wp-content
10
11
# clean up

12
$ 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:

1
$ cd ~/Site/demo2/php
2
$ scp -r 532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com: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.

1
$ cd ~/Site/demo2/php$ rsync -av --partial --progress  --rsh="ssh " 532bd7655004468bcf0000e1@demo2-tutsplus.rhcloud.com: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.

1
$ echo "php/*" >> .gitignore

Step 6: Administration Over SSL (Optional)

The wp-config.php, that OpenShift generated, defined to serve administrator over SSL

1
<?php
2
// wp-config.php

3
//...

4
5
/**

6
 * We prefer to be secure by default

7
 */
8
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.

1
$ sudo mkidr -p /etc/apache2/ssl
2
# make sure you type correct domain
3
$ 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

1
Listen 80
2
Listen 443

On top of your /etc/apache2/extra/httpd-vhost.conf, find the line NameVirtualHost *:80 and append 

1
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.

1
<VirtualHost *:443>
2
3
    SetEnv OPENSHIFT_SECRET_TOKEN  "kCsELz-GJnho4I0M9XemTiZ47Jn4_QCSONFL5We8zw3Tgg572ivNEQQgZeIKQkTo2kEwUHWjpsO7fhy1FeVqDlyRzSsKg6-fWNDWJaj9hO65nwVqE5auj35R2F9RNvEk"
4
    SetEnv OPENSHIFT_APP_UUID 532bd7655004468bcf0000e1
5
    SetEnv OPENSHIFT_APP_NAME demo2
6
    SetEnv OPENSHIFT_MYSQL_DB_USERNAME adminL1GxwjI
7
    SetEnv OPENSHIFT_MYSQL_DB_PASSWORD DyANqgKAFbTT
8
    SetEnv OPENSHIFT_MYSQL_DB_HOST "127.0.0.1"
9
    SetEnv OPENSHIFT_MYSQL_DB_PORT 3307
10
11
    ServerName openshift.axcoto.com
12
    ServerAdmin webmaster@dummy-host2.example.com
13
    DocumentRoot "/Users/kureikain/Sites/demo2/php"
14
    <Directory "/Users/kureikain/Sites/demo2/php">
15
      Order allow,deny
16
      Allow from all
17
    </Directory>
18
    
19
    ErrorLog "/var/log/apache2/openshift.axcoto.com-error_log"
20
    CustomLog "/var/log/apache2/openshift.axcoto.com-access_log" common
21
22
    SSLEngine On
23
    SSLCertificateFile /etc/apache2/ssl/apache.crt
24
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key
25
26
    <Location />
27
        SSLRequireSSL On
28
        SSLVerifyClient optional
29
        SSLVerifyDepth 1
30
        SSLOptions +StdEnvVars +StrictRequire
31
    </Location>
32
33
</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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.