Tutorials

Tutorials about HTML, CSS, PHP, Javascript, and Photoshop

  • Home
    Home This is where you can find all the blog posts throughout the site.
  • Categories
    Categories Displays a list of categories from this blog.
  • Tags
    Tags Displays a list of tags that has been used in the blog.
  • Archives
    Archives Contains a list of blog posts that were created previously.
  • Login

Running WordPress on OpenShift Part2

by in Photoshop
  • Font size: Larger Smaller
  • Hits: 7300
  • 0 Comments
  • Subscribe to this entry
  • Print
7300

We will dive deeply into OpenShift to understand the custom build and deployment process, In this tutorial. 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. Source file and media files, we'll look at how to synchronize our local environment with remote environment including database, Additionally

The first part of this series gave a quick overview of OpenShift. And setup a custom domain, our account name, We discussed how to create the app, get the server URL.  

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 callRhc clientWe can invoke it from command line to perform OpenShift administration and maintenance. You can create apps, Once you;ve installed the tool, 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 aboutinstalling this client libraryThe library is written in Ruby so make sure that you have Ruby installed. Basically, you only need to installthe 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 nowTypeYes

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 RhcCommand will give you a list of available commands. You can learn from there withRhc helpIt shows a brief overview of each commandRhc help command_nameWill 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

You have to specify the app name with, For the command that interacts with an app-a appnameIf you run the commands inside your Git repository that you cloned before, or just append app name; however, you may omit it. The app name can be see withRhc appCommand. Example with my previousDemo2App. 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 532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com

It can be useful to trigger a deployment without any pushing, Sometime. 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://532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com/~/git/demo2. Git/
  Initial Git URL: https://github. Com/openshift/wordpress-example. Git
  SSH:             532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com
  Deployment:      auto (on git push)
  Aliases:         openshift. Axcoto. Com

  mysql-5. 5 (MySQL 5. 5)
  ---------------------
    Gears:          Located with php-5. Phpmyadmin-4
    Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
    Database Name:  demo2
    Password:       DyANqgKAFbTT
    Username:       adminL1GxwjI

  php-5, 4. 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 easy to rollback your changes, and since everything is under source control, It's relatively straight forward and easy to understand

What Happens When You Push to Your Repository?

We saw that whenever a, In the first articleGit pushThe app will be deployed, to deploy a branch is triggered. According to the OpenShift documentHere is a break down of what happen:

  1. You run aGit pushOn 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 yourOpenshift/action_hooksOpenShift will execute those script files checked into your Git repository at specific points during the deployment process.  

The deployment process will continue normally,  If the corresponding script file does not exist. Again, all hooks must be placed in theOpenshift/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-BuildThis happens after the application is stopped and the new repo dir has been deployed but before the build. Runs theOpenshift/action_hooks/pre_buildScript
  3. Build This builds your application, executes the, downloads required dependencyOpenshift/action_hooks/buildScript and preps everything for deployment. No any special build requirements, we don't use this step much since WordPress just need to drop into document root and run by web server, In scope of WordPress. We usually use this hook to Download WordPress and extract it into correct location on OpenShift
  4. DeployThis 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 theOpenshift/action_hooks/deployHook. Copy plugin and theme (, we use this hook to copy the data of the above build into document root, In scope of WordPressOpenshift/themes and. Openshift/plugin) to the correct location
  5. Post-DeploySome applications may need to interact with the running application to complete the deployment process. After the application starts, theOpenshift/action_hooks/post_deployHook will be executed

You can totally customize these scripts for your own purposes. Meaning you can write it in any language no matter it's Bash, The build scripts are executed directly, Ruby or Python as long as you put correctshebangSuch as if you used bash

#. /bin/bash
Or 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

We utilize that build process to prepare for some data, With respect to WordPress, we don't do many tasks in the building process because PHP doesn't requires building; however. TheOpenshift/action_hooks/buildIf not it will download the WordPress from WordPress, checks whether WordPress is created on OpenShift. Org, extract and copy content of the WordPress source files into the correct location, create necessary directory. That build script does almost nothing because WordPress has been installed, Since the second deployment. We have to know the environment variables, To customize these build script

The OpenShift Environment Variables

We will need to know some OpenShift information such as the document root path, and the application name, the data path, During our build and document process. This information is available in environmental variables for which a full list can be accesshere

Some variables that we'll use frequently is as follows:

  1. OPENSHIFT_HOMEDIRHome directory path. Linux you will have your user home directory in, On your local machine/home/usernameOr on Mac OS X it's/Users/usernameHome directory is the folder you will be in right there when you remote access via SSH. It's/var/lib/openshift/user_account_idFor 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 thatPhpFolder now is symbolic link point to document root; therefore$OPENSHIFT_REPO_DIR/phpCan 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 aHello World When and how as we customize the build script, action so we have a sense of what will be output

Your Hello World Build 

Let append thisEcho "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_build
Push 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. Done, Compressing objects: 100% (5/5). 411 bytes, Writing objects: 100% (5/5). 0 bytes/s, done. Reused 0 (delta 0)
remote: Stopping MySQL 5, Total 5 (delta 4). 5 cartridge
remote: Stopping PHP 5. Commit 1f4ef8a, 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'Remote: Hello world. This is invoke before buildingRemote: 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://532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com/~/git/demo2. Git/
   1e7ad85. 1f4ef8a  master -> master
Our message appears during build process, As you see. Let's do a real thing to copy files during build process,   Now

Copying File to Document Root

If you recall previous step, the file inOpenshift/themesAndOpenshift/pluginsIs copied toWp-content/themesAndWp-content/pluginsLet's say we want to do the same for copying file to the document root.  

You want to create a sub folder callResumeAnd put a fileResume/my_resume. TxtAnd make it access viaDemo2-tutsplus. Rhc-cloud. Com/resume/my_resume. TxtLet's create a directory to hold the data that we will copy into document root. We create a folder callDocrootInsideOpenshiftAnd whatever inside it will be copied.  

Let's openOpenshift/action_hooks/deployNotice 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. Etc, so it could be python, php, This script gets executed directly, # ruby. 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}Copy the default themes and plugins
# from official Wordpress installation
#, uploads
fi


# If this is initial 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/nullEcho "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}If not create it if, 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. /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 iscpTo recursively copy all files and folders

Now, let put something inOpenshift/docrootAnd deploy

☁  demo2 [master] ⚡ mkdir -p. Openshift/docroot/resume/
☁  demo2 [master] ⚡ echo "Hi there" >. Openshift/docroot/resume/my_resume. Txt
☁  demo2 [master] ⚡ git add. 7 insertions(+), openshift/
☁  demo2 [master] ⚡ git commit -m "Custom hook for file copy"
[master 46235a2] Custom hook for file copy
 3 files changed, 1 deletion(-)
 create mode 100644. Openshift/docroot/hi. Done, txt
☁  demo2 [master] git push
Counting objects: 13. Delta compression using up to 4 threads. Compressing objects: 100% (6/6), done. 723 bytes, Writing objects: 100% (8/8). 0 bytes/s, done. Reused 0 (delta 0)
remote: Stopping MySQL 5, Total 8 (delta 4). 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://532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com/~/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 PhpInstead of introducing, folder in  your repository as a way to store this contentOpenshift/docroot

Hint

App-deployments/current/repoHolds exactly same copy of your repository. Whatever you have on your local machine will be here

Troubleshoot and Maintain

You knew how to remote access to your application with SSH, In the previous part. You can use Linux command, Once you are in

$ ssh 532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com

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

$ rhc ssh demo2

From these, you can always useHelpTo show available commands

  1. Tail_all:Tail all of your log. MySQL error log, You can see real time logging with this command for all gears in system: such as access log of Apache
  2. MysqlDrops you into a MySQL shell. User string and password, Very handy comparing with typing a long mysql command with host name
  3. ExportShow all current environment variables. You can use this command to see the list of available environment variables, During working with build script
  4. GearRestart, to control your gear: start, stop. Stop mysql, Like you can restart apache
  5. SnapshotSnapshot take a full backup of your current WordPress with all file, and media data, database dump. A very good way to have a full back-up of your site
  6. QuotaShow your disk quota. You may run out of space, Useful when you cannot upload to WordPress anymore

Taking a Snapshot

Rhc snapshot-save demo2Compress the media file, and source code, putting together a tar file and download it for you, dump your database.  

$ 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

TheGearCommand controls cartridge status, start/stop. Or a database error, 503 error, or some 404, Like you get a timeout error when visiting your domain. 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_RESULTApplication is either stopped or inaccessibleI 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]\>


# 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]\>
The next step is to consult your log file

Logging

Tail_allShow you completed logs of all cartridge in real time. If you want to look at an individual log, However, here is the list:

  1. Php/logsAccess and error log of Apache and MySQL
  2. Mysql/logMySQL log

Port Forwarding

TheRhc port-forwardCommand 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. 1:8080  =>  127. 2. 126. 1:8080
httpd   127. 1:8081  =>  127. 2. 126. 3:8080
mysql   127. 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 up3307For MySQL. Now I can use the MySQL credential to connect to it with Sequel Pro. And issue:, you can get it again on OpenShift dashboard or SSH into server, If you forgot your password

[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:
 This email address is being protected from spambots. You need JavaScript enabled to view it.
 .2: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"

UsingSequel ProTo 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 inthis tutorial.That exporting process is annoying, However. Take longer and longer to export/import, The data can be big. Too, Fixing bug is harder. It can be hard to debug on local environment, without re-producing the exactly post/page content, If a bug only happens on a particular post/page on live site

Specially the pictures data, and you have your team created lots of test post on a staging/testing area (hosting on OpenShift), Or if you are a remote team, it will be good if you have a good way to just synchronize everything back

Therefore, I propose a method to achieve that with: port forwarding and host file editing. We can access MySQL easily from local machine, Using port forwarding as we saw above. We can point the domain, With the help of editing host fileopenshift.axcoto.comInstead of to OpenShift, to local machine. In our clone repository, we have an emptyPhpFolder. That folder is replaced by a symbolic link to document root of Apache, When deploying. Now, we will use that folder as document root on our local machine. On my computer, Recall the repository structure again

☁  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

You should add whatever you have in wp-content/plugins(default WordPress 3, to succeed at this method, Note that. 8. 1 plugins) and wp-content/themes(default WordPress 3. 8. 1 themes) on OpenShift into yourGit 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 repositoryOpenshift/themesAndOpenshift/pluginsHas same thing with theWp-content/themesAndWp-content/pluginsFolder of WordPress app on OpenShift

Step 1: Port Forwarding

Using commandRhc port-forward demo2WithDemo2Is my app. Change it to your app name

Step 2: Virtual Host

We will add one more entry for our domain point to folder hold our WordPress, Using Apache. Depending on your OS, you may have different location for Apache configuration. It can be/etc/apache2Or/etc/httpd 

It's, For example, on my Mac/etc/apache2I will add below code to my/etc/apache2/httpd. ConfOr/etc/apache2/extra/httpd-vhosts. ConfOr where you prefer, depend your OS

<VirtualHost *:80>
    ServerName openshift. Axcoto. Deny
      Allow from all
    </Directory>
</VirtualHost>, com
    DocumentRoot "/Users/kureikain/Sites/demo2/php"
    <Directory "/Users/kureikain/Sites/demo2/php">
      Order allow
Some article will helps:, If you are not familiar with Apache and Virtual host
  1. http://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

You won't have the environment variable available, When running on your local machine. We have to define in somewhere. For a simple starting, I prefer to put these variable directly in Apache config file withSetEnvDirection.  

Our virtual host entry become:

<VirtualHost *:80>
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 webmaster@dummy-host2. Example. 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>, com DocumentRoot "/Users/kureikain/Sites/demo2/php" <Directory "/Users/kureikain/Sites/demo2/php"> Order allow
I grab the environment variable of OpenShift and just put it into our config file. But I change the MySQL host to 127. 1 and MySQL Port to 3307 because we do port forwarding before

Step 4: Changing the Host File

Openshift. Axcoto. ComIs configured to point to OpenShift. We can override it by directly editing, However/etc/hostsOpen that file with you favorite editor and append

127. 1    openshift. Axcoto. Com
Confirm that it's pointing to our local machine

☁  ~  ping openshift. Axcoto. Com
PING openshift. Axcoto. Com (127. 1): 56 data bytes
64 bytes from 127. 1: icmp_seq=0 ttl=64 time=0. 055 ms
64 bytes from 127. 1: icmp_seq=1 ttl=64 time=0. 165 ms
^C
--- openshift. Axcoto. 2 packets received, com ping statistics ---
2 packets transmitted. 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. 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

We have to copy the media and WordPress file into our local environment, Finally. We also make the symbolic link to pointPhp/wp-content/themesToOpenshift/themeThe same concept applies for pluginPhp/wp-content/pluginsPoint toOpenshift/pluginsThis way we can working on. Openshift/themes andOpenshift/pluginsAnd 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, we don't want to pull all of file because partial of files were there, since the second time. A better option is only sync uploads file. We can do that withscp:

$ cd ~/Site/demo2/php
$ scp -r 532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com:app-root/data/uploads wp-content/

Or withrsyncRsync 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 " 532bd7655004468bcf0000e1@demo2-tutsplus. Rhcloud. Com:app-root/data/uploads wp-content

Put these commands into a shell script and track it with your Git repository too, You may go further. 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)

TheWp-config. PhpThat OpenShift generated, defined to serveadministrator 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 editWp-config. PhpAnd setFORCE_SSL_ADMINTo false. And want to give it a try to run a SSL connection then here is the instruction, If you want challenge

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/sslThen 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. ConfYour Apache config file can be in different folder, such as, (again/etc/httpdFind the line , )Listen 80And appendListen 443

Listen 80
Listen 443

On top of your/etc/apache2/extra/httpd-vhost. ConfFind the lineNameVirtualHost *:80And append 

NameVirtualHost *:443

Next, we define one more entry in virtual host for port 443. We add some SSL definition, but this time, We just duplicate the previous definition with port 80

<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 webmaster@dummy-host2. Example. Com
    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 withSudo apachectl restartNow, you can access your dashboard over SSL. And media data is synced, Here is my WordPress installation, running totally local with same database from live site

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 ofRhc clientYou can quickly config or viewing app information from terminal.  

And a push to HipChat during deployment, We also covered build and deploy scripts so you can customize your application to your needs like showing a special banner. 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

Read more: Running WordPress on OpenShift Part2

0
Trackback URL for this blog entry.

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest Wednesday, 20 January 2021

Testimonial

Thank you so much! We are very happy with our new website. It is easy to use and all of our customers tell us, they love it.

Contact Us

  • 13245 Atlantic Blvd. #4352
    Jacksonville, FL 32225
  • 904-240-5823