Cloud Foundry Documentation

Deploy and Scale Your Application in Seconds

Using Cloud Foundry Services

The following services are available to use in your application in Cloud Foundry’s cloud:

  • MySQL, the open source relational database
  • MongoDB, the scalable, open, document-based database
  • Redis, the open key-value data structure server
  • RabbitMQ, for messaging

After you develop your application to integrate any one of these services locally, you can use standard Cloud Foundry client commands (vmc, SprintSource Tool Suite, or the Eclipse plugin) to add, bind, unbind, and delete these service in the cloud.

Note: Make sure you have the latest version of vmc if you are using it: vmc -v, and if needed gem update vmc

MySQL

Cloud Foundry supports MySQL for your application, if you plan to use MySQL it as service, we recommend you also have MySQL running locally in your development environment.

Here is the process to follow whether using MySQL or another relational databases on your local/development environment:

  1. List the respective gem for that database as a dependency in your application’s Gemfile, e.g. “gem ‘mysql2, ‘< 0.3’”.

  2. Before you pushing the application to the cloud, run

    • bundle package

    • bundle install

  3. Push or update your application:

    • vmc push, or

    • vmc stop appname, vmc update appname

  4. vmc create-service mysql –bind appname

    This creates mysql as a service at Cloud Foundry and binds it to your application.

    adding mysql service

  5. If you updated your application, vmc start appname

MongoDB

This scalable, open source, document-oriented database is provided as a service at Cloud foundry. This section describes how you can create Rails and NodeJS applications using the service.

Ruby on Rails

This tutorial is based on Rails 3.0 and Ruby 1.9. You can use Rails 2.3.5 or Ruby 1.8.7, we recommend you also use Bundler to manage your application Gem dependencies.

Prerequisites

Creating an Application

  1. Create your new application:

    rails new my_app --skip-active-record
    
  2. Add required gem dependencies to your application Gemfile:

    • gem “mongo_mapper”

    • gem “thin”

      For Rails applications, Cloud Foundry is currently configured to use Thin as the one web server so we add it.

    • gem “bson_ext”

      Here we also add BSON for serialization of JSON-like documents; you will need it to interface with MongoDB’s ruby driver.

    gemfile for mongodb

  3. Run bundle install, so gem dependencies are loaded.

  4. Create your application. In the application root folder:

    rails g scaffold messages message:string --orm mongo_mapper
    

    This creates an application via Rails scaffolding where the model uses MongoMapper rather than Active Record. The application contains a single table messages with a single column of type string.

  5. (Optional) Updating Routes. Here we update config/routes.rb so the application root points to messages by default:

    • root :to => “messages#index”

    • delete public/index.html from your application

      updating routes

  6. Create a configuration file to communicate with MongoDB at Cloud Foundry:

     rails g mongo_mapper:config
    

    This creates a basic config/mongo.yml file in our application that we will modify to have our credentials, host, and port for Cloud Foundry in JSON.

    mongo yaml

  7. Modify the production section of config/mongo.yml

    production:   
        host: <%= JSON.parse(ENV['VCAP_SERVICES'])['mongodb-1.8'].first['credentials']['hostname'] rescue 'localhost' %>
        port: <%= JSON.parse( ENV['VCAP_SERVICES'] )['mongodb-1.8'].first['credentials']['port'] rescue 27017 %>
        database:  <%= JSON.parse( ENV['VCAP_SERVICES'] )['mongodb-1.8'].first['credentials']['db'] rescue 'cloud_foundry_mongodb_tutorial' %>
        username: <%= JSON.parse( ENV['VCAP_SERVICES'] )['mongodb-1.8'].first['credentials']['username'] rescue '' %>
        password: <%= JSON.parse( ENV['VCAP_SERVICES'] )['mongodb-1.8'].first['credentials']['password'] rescue '' %>
    

Deploying an Application

  1. Push the application:

    vmc push –runtime ruby19

  2. vmc will ask if you want to bind any services:

    • Select 2 (mongodb)

    • Provide a name or choose the default

    pushing mongo ror app

  3. Open your browser to the url selected when you pushed the application to view it.

    mongo ror app

NodeJS

Before you get started, you will need these tools:

Code for these examples can be found at GitHub

Setup

  1. Start mongod on your local environment. At the command prompt:

    mongod

  2. Confirm node.js is correctly installed:

    • Run node and the interactive javascript console will start

    • Check that Node Package Manager (NPM) is installed: at the command line, enter NPM -v

    mongo node nvm

  3. vmc target api.cloudfoundry.com

  4. vmc login

    Enter your username and password

Create Application Files

  1. Create an application directory: mkdir appname

  2. Change to that directory: cd appname

  3. Create a file app.js

Add a Simple Web Server

  1. In app.js, add the code:

    var port = (process.env.VMC_APP_PORT || 3000);
    var host = (process.env.VCAP_APP_HOST || 'localhost');
    var http = require('http');
    
    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    }).listen(port, host);      
    console.log('Server running at localhost:3000');
    

    This creates a NodeJS web server using port 3000 on localhost that will respond to any HTTP request with ‘Hello World.’

  2. node app.js

    Your NodeJS web server starts.

    mongo node server

  3. In another terminal window send a request: curl localhost:3000

    mongo node curl

  4. Stop the node: Control-C

  5. Push the application to Cloud Foundry: vmc push

    Cloud Foundry detects node.js and asks for configuration options, including a name and the services we want.

    • Select ‘y’ to bind a service

    • Select ‘1’ for mongodb

    • Select default service name

    Cloud Foundry stages and starts your application.

    ![mongo node push](/assets/images/screenshots/mongo_node_push.jpg "mongo node cloud curl")
    
  6. curl appname.cloudfoundry.com

    Your application in the cloud will return ‘Hello World.’

    mongo node cloud curl

Add MongoDB Configuration

Here we update the application so that it will use the Cloud Foundry service it is in on the cloud, or it will use your local mongodb instance.

  1. We add this to app.js:

    if (process.env.VCAP_SERVICES){
        var env = JSON.parse(process.env.VCAP_SERVICES);
        var mongo = env['mongodb-1.8'][0]['credentials'];
    }       
    else {
        var mongo = {
            "hostname":"localhost",
            "port":27017,
            "username":"",
            "password":"", 
            "name":"",
            "db":""
        }
    }
    
    var generate_mongo_url = function(obj){
        obj.hostname = (obj.hostname || 'localhost');
        obj.port = (obj.port || 27017);
        obj.db = (obj.db || 'test');
        if(obj.username && obj.password){
            return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
        }
        else{
            return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
        }
    }
    
    var mongourl = generate_mongo_url(mongo);
    

The if conditional will provide two different sets of information, depending on if the application is on the cloud or running locally. The generate_mongo_url creates appropriate connection information for MongoDB and it it then assigned to mongourl.

  1. Test app.js locally:

    • node app.js

    • in another terminal, curl localhost:3000

  2. Update the cloud application: vmc update

  3. Test it: curl appname.cloudfoundry.com

Using MongoDB Drivers

  1. Install MongoDB native drivers locally: npm install mongodb

    This create a new local directory for the driver in the application root, node_modules.

  2. To use the drivers on at Cloud Foundry, we provide a different path. At the top of the app.js:

    require.paths.unshift(‘./node_modules’);

Using MongoDB

Now we built functionality in our application that uses MongoDB. In this example we record a visit/request to our server and then print the last ten visits:

  1. We create a new function, record_visit that will store the server request to MongoDB:

    var record_visit = function(req, res){
        /* Connect to the DB and auth */
        require('mongodb').connect(mongourl, function(err, conn){
            conn.collection('ips', function(err, coll){
                /* Simple object to insert: ip address and date */
                object_to_insert = { 'ip': req.connection.remoteAddress, 'ts': new Date() };
    /* Insert the object then print in response */
    /* Note the _id has been created */     
        coll.insert( object_to_insert, {safe:true}, function(err){
    if(err) { console.log(err.stack); }
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write(JSON.stringify(object_to_insert));
            res.end('\n');
            });
        });
    });
    }
    

    Here we use the .connect method to connect to MongoDB using either the local or Cloud Foundry mongourl. Then we use the .collection(‘ips’ ….) method to add the request information to the data that will be committed.

  2. Update the http.createServer method. Here we are updating this function so it calls the record_visit function when the server request is made:

    http.createServer(function (req, res) {
        record_visit(req, res);
    }).listen(port, host);
    
  3. Test app.js locally and on the cloud:

    • node app.js then curl localhost:3000

    • vmc update, then curl appname.cloudfoundry.com

    mongo node record

  4. After we test, we create a function that will actually output information from MongoDB. In this case we add a function print_visits that prints that last 10 visits/requests:

    var print_visits = function(req, res){
        /* Connect to the DB and auth */
        require('mongodb').connect(mongourl, function(err, conn){
            conn.collection('ips', function(err, coll){
                coll.find({}, {limit:10, sort:[['_id','desc']]}, function(err, cursor){
                    cursor.toArray(function(err, items){
                        res.writeHead(200, {'Content-Type': 'text/plain'});
                        for(i=0; i<items.length;i++){
                            res.write(JSON.stringify(items[i]) + "\n");
                        }
                        res.end();
                    });
                });
            });
        });
    }
    
  5. Then we update the createServer method again to call the new function, print_visits:

    http.createServer(function (req, res) {
        params = require('url').parse(req.url);
        if(params.pathname === '/history') {
            print_visits(req, res);
        }
        else{
            record_visit(req, res);
        }
    }).listen(port, host);
    

    In this case, requests to the web server will either add the current visit to MongoDB (the default) or if this url request has ‘/history’ it will output the last 10 visits.

  6. Test app.js locally:

    mongo node print

  7. Stop the application, update it: vmc update

    mongo node update

  8. Test the cloud version:

    • curl appname.cloudfoundry.com, and

    • curl appname.cloudfoundry.com/history

    mongo node history

    All the server requests have been recorded on Cloud Foundry’s MongoDB service.

Redis

Redis is an open source key-value store, also known as a NoSQL database. You set, get, update and delete information using a key.

For any application written in Ruby, such as applications in Rails or Sinatra, follow this process:

  1. Add the gem to your application’s Gemfile

    gem 'redis'
    
  2. Load the library into your application’s runtime. In Rails, for instance you would use the require statement in application.rb. In Sinatra, you would add this to your .rb configuration file.

    require 'redis'
    
  3. Configure your environment so it can locate the Redis service on the cloud:

    configure do
        services = JSON.parse(ENV['VCAP_SERVICES'])
        redis_key = services.keys.select { |svc| svc =~ /redis/i }.first
        redis = services[redis_key].first['credentials']
        redis_conf = {:host => redis['hostname'], :port => redis['port'], :password => redis['password']}
        @@redis = Redis.new redis_conf
    end 
    

    We provide credentials to connect to the Redis service as environment variables under the key VCAP_SERVICES. The values are stored as JSON so we use the JSON parser in the first line to extract it.

    The last line creates a class variable @@redis which is available for all its subclasses in your application and will be used at runtime to add key/values to Redis.

  4. In your application use the available Redis commands to edit and add key/values to the data store.

  5. Run bundle package.

  6. Update or add your application to the cloud:

    • To update

      • vmc stop appname

      • vmc update

    • To add: vmc push

  7. Bind to Cloud Foundry’s Redis service:

    vmc create-service redis --bind appname
    
  8. For updated applications, start again:

    vmc start appname
    

RabbitMQ

Cloud Foundry supports RabbitMQ, the open-source message broker as a service that developers can add to their applications.

As with all other Cloud Foundry services, you can use vmc or SpringSource STS to provision, bind and remove RabbitMQ services.

The RabbitMQ service at Cloud Foundry is currently based on rabbitmq-server-2.4.1.

For more information about RabbitMQ, see these resources:

Language and Framework Support

All languages and frameworks supported by Cloud Foundry that have an Advanced Message Queue Protocol (AMQP) client library are also supported by the RabbitMQ service.

Applications in the following language, framework and client library combinations have been deployed on Cloud Foundry:

  • Java Spring applications with Spring AMQP (version 1.0.0.RC2)

  • Ruby on Rails and Sinatra applications with the bunny gem (version 0.7.4)

  • NodeJS applications with the node-amqp (version 0.1.0)

Protocol Support

RabbitMQ service supports the core protocols of RabbitMQ: AMQP versions 0-8 and 0-9-1. Other protocols will be supported by RabbitMQ plugins.

Provisioning and Binding RabbitMQ

  1. vmc target api.cloudfoundry.com

  2. vmc login

  3. Provision the service: vmc create-service

  4. Select 1, for rabbitmq

    Cloud Foundry will provision the service for your cloud and name the service.

  5. Bind the service to your application: vmc bind-service rabbitmq-name appname

  6. Check the application:

    • vmc list

    • vmc apps

    Returns a list of applications on your cloud and any associated services.

Rails and RabbitMQ

The RabbitMQ service is accessed through the AMQP protocol (versions 0.8 and 0.9.1) and your application will need access to a AMQP client library in order to use the service.

A popular AMQP client libraries for Rails is bunny; we will use it demonstrate the process you would follow:

Note: As mentioned before, if you are using Rails 2.3.5 we recommend you also use Bundler.

  1. In Gemfile, add bunny and json (the latter is used to parse service connection data):

    gem 'bunny'
    gem 'json'
    
  2. bundle install

    Bundler fetches and installs the latest version of bunny and json for your application.

  3. Require the gems in your controller:

    require 'bunny'
    require 'json'
    
  4. Update the controller class to get the connection string for the service and make the connection:

    # Extracts the connection string for the rabbitmq service from the
    # service information provided by Cloud Foundry in an environment
    # variable.
        def self.amqp_url
            services = JSON.parse(ENV['VCAP_SERVICES'], :symbolize_names => true)
            url = services.values.map do |srvs|
            srvs.map do |srv|
                if srv[:label] =~ /^rabbitmq-/
                    srv[:credentials][:url]
                    else
                    []
                end
            end
        end.flatten!.first
    end
    
    # Opens a client connection to the RabbitMQ service, if one is not
    # already open.  This is a class method because a new instance of
    # the controller class will be created upon each request.  But AMQP
    # connections can be long-lived, so we would like to re-use the
    # connection across many requests.
    def self.client
        unless @client
            c = Bunny.new(amqp_url)
            c.start
            @client = c
        end
        @client
    end
    
  5. Set up message queues in the controller:

    # Return the "nameless exchange", pre-defined by AMQP as a means to
    # send messages to specific queues.  Again, we use a class method to
    # share this across requests.
    def self.nameless_exchange
        @nameless_exchange ||= client.exchange('')
    end
    
    # Return a queue named "messages".  This will create the queue on
    # the server, if it did not already exist.  Again, we use a class
    # method to share this across requests.
    def self.messages_queue
        @messages_queue ||= client.queue("messages")
    end
    
  6. Add controller methods to read and write messages:

    # The action for our publish form.
    def publish
        # Send the message from the form's input box to the "messages"
        # queue, via the nameless exchange.  The name of the queue to
        # publish to is specified in the routing key.
        HomeController.nameless_exchange.publish params[:message],
                                       :key => "messages"
        # Notify the user that we published.
        flash[:published] = true
        redirect_to home_index_path
    end
    
    def get
        # Synchronously get a message from the queue
        msg = HomeController.messages_queue.pop
        # Show the user what we got
        flash[:got] = msg[:payload]
        redirect_to home_index_path
    end
    

NodeJS and RabbitMQ

For NodeJS applications, the approach is similar to other frameworks. RabbitMQ service is accessed through the AMQP protocol (versions 0.8 and 0.9.1) and your application will need access to a AMQP client library in order to use the service.

In this case we also recommend you use:

  • npm (node package manager) to handle the dependent library
  • sanitizer to handle HTML escape characters

Here is the process to generally follow; there is room to change this as needed for your application-specific logic:

  1. Add the library dependencies to package.json:

    {
        "name":"node-srs-demo",
        "dependencies":{
            "amqp":">= 0.1.0",
            "sanitizer": "*"
        }
    }
    
  2. In your application file, e.g. app.js, add the code connect to the service:

    require.paths.unshift('./node_modules');
    
    var http = require('http');
    var amqp = require('amqp');
    var URL = require('url');
    var htmlEscape = require('sanitizer/sanitizer').escape;
    
    function rabbitUrl() {
        if (process.env.VCAP_SERVICES) {
            conf = JSON.parse(process.env.VCAP_SERVICES);
            eturn conf['rabbitmq-2.4'][0].credentials.url;
        }
        else {
            return “amqp://localhost";
        }
    }
    
    var port = process.env.VCAP_APP_PORT || 3000;
    

    The first line tells the application where the node_modules libraries are on Cloud Foundry; they just live in a different path than they do on your development environment. Then we load up our required libraries and assign them to variables we use later.

    The rabbitURL function parses our credentials for Cloud Foundry as well as the URL for the provisioned RabbitMQ service. Then it connect to the service.

  3. Set up message handling and messaging queues in your application:

    var messages = [];
    function setup() {
      var exchange = conn.exchange('cf-demo', {'type': ‘fanout', durable: false}, function() {
        var queue = conn.queue(", {durable: false, exclusive: true},
        function() {
          queue.subscribe(function(msg) {
            messages.push(htmlEscape(msg.body));
            if (messages.length > 10) {
              messages.shift();
            }
          });
          queue.bind(exchange.name, ");
        });
        queue.on('queueBindOk', function() { httpServer(exchange); });
      });
    }
    
  4. Add an HTTP listener to respond to requests and publish messages from RabbitMQ:

    function httpServer(exchange) {
      var serv = http.createServer(function(req, res) {
        var url = URL.parse(req.url);
        if (req.method == 'GET' && url.pathname == '/env') {
          printEnv(res);
        }
        else if (req.method == 'GET' && url.pathname == '/') {
          res.statusCode = 200;
          openHtml(res);
          writeForm(res);
          writeMessages(res);
          closeHtml(res);
        }
        else if (req.method == 'POST' && url.pathname == '/') {
          chunks = '';
          req.on('data', function(chunk) { chunks += chunk; });
          req.on('end', function() {
            msg = unescapeFormData(chunks.split('=')[1]);
            exchange.publish(", {body: msg});
            res.statusCode = 303;
            res.setHeader('Location', '/');
            res.end();
          });
        }
        else {
          res.statusCode = 404;
          res.end("This is not the page you were looking for.");
        }
      });
      serv.listen(port);
    }
    
  5. Add any application helpers:

    var conn = amqp.createConnection({url: rabbitUrl()});
    conn.on('ready', setup);
    

Spring and RabbitMQ

The RabbitMQ service is accessed through the AMQP protocol (versions 0.8 and 0.9.1) and your application will need access to a AMQP client library in order to use the service. Fortunately the Spring AMQP project enables AMQP applications to be built using Spring constructs.

To use the RabbitMQ service we include the cloudfoundry-runtime jar in our Spring application; this enables access to Cloud Foundry services, including RabbitMQ.

Note: For more information about Spring AMQP, visit the reference documentation.

  1. Add the corresponding dependencies to the application pom.xml file:

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <name>Spring Maven MILESTONE Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
    
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
        <version>1.0.0.RC2</version>
    </dependency>
    
    <dependency>
        <groupId>org.cloudfoundry</groupId>
        <artifactId>cloudfoundry-runtime</artifactId>
        <version>0.7.1</version>
    </dependency>
    
  2. Extend the Spring Application Context XML.

    These changes do the following:

    • Uses cloudfoundry-runtime to connect to the RabbitMQ service.

    • Configures RabbitTemplate and RabbitAdminthat as the main entry points to Spring AMQP.

    • Declares a queue called messages within the RabbitMQ broker.

      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xmlns:cloud="http://schema.cloudfoundry.org/spring"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                         http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
                         http://schema.cloudfoundry.org/spring http://schema.cloudfoundry.org/spring/cloudfoundry-spring-0.7.xsd">
      
      
      <!-- Obtain a connection to the RabbitMQ via cloudfoundry-runtime: -->
      <cloud:rabbit-connection-factory id="connectionFactory"/>
      
      <!-- Set up the AmqpTemplate/RabbitTemplate: -->
      <rabbit:template connection-factory="connectionFactory"/>
      
      <!-- Request that queues, exchanges and bindings be automatically declared on the broker: -->
      <rabbit:admin connection-factory="connectionFactory"/>
      
      <!-- Declare the "messages" queue: -->
      <rabbit:queue name="messages" durable="true"/>
      
  3. Update your application controller/logic.

    • Include the messaging libraries:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.amqp.core.AmqpTemplate;
      
    • Read and write messages:

       @Controller
      public class HomeController {
          @Autowired AmqpTemplate amqpTemplate;
      
          @RequestMapping(value = "/")
          public String home(Model model) {
              model.addAttribute(new Message());
              return "WEB-INF/views/home.jsp";
          }
      
          @RequestMapping(value = "/publish", method=RequestMethod.POST)
          public String publish(Model model, Message message) {
              // Send a message to the "messages" queue
              amqpTemplate.convertAndSend("messages", message.getValue());
              model.addAttribute("published", true);
              return home(model);
          }
      
          @RequestMapping(value = "/get", method=RequestMethod.POST)
          public String get(Model model) {
              // Receive a message from the "messages" queue
              String message = (String)amqpTemplate.receiveAndConvert("messages");
              if (message != null)
                  model.addAttribute("got", message);
              else
                  model.addAttribute("got_queue_empty", true);
      
              return home(model);
          }
      }
      

Rails for Cloud Foundry

This is a practical guide for Ruby on Rails developers who are using Cloud Foundry. It assumes you already have vmc, SpringSource STS, or Eclipse installed, plus you have deployed a simple “Hello World”-style application on the cloud. It also assumes you are already proficient in developing Rails applications and are familiar with tool used to manage dependencies in Rails applications.

For more information, see:

  • Ruby on Rails
  • Bundler, the gem dependency manager
  • Cloud Foundry Getting Started Guides for CLI (vms) or STS/Eclipse

Ruby

Ruby is the object-oriented, interpreted programming language that your Rails application is built in.

Versions

Note the following on Cloud Foundry and Ruby:

+   Ruby 1.8+, the default support (1.8.7 recommended or higher)
+   Ruby 1.9 also supported (1.9.2 patch level 174 recommended or higher). 

To deploy your application on the cloud running on Ruby 1.9: vmc push myapp –runtime ruby19

Ruby on MacOSX

MacOSX includes Ruby 1.8+ as part of the standard installation. On some versions of MacOSX, such as Lion, Ruby is provided as 1.8.7. patch level 249. This may cause an incompatibility with vmc. To solve this:

  1. Install Ruby Version Manager

    rvm mac osx patchlevel

  2. Install Ruby 1.8.7 or 1.9.2

  3. Run rvm use 1.8.7-p249

Gems

Gems are Ruby libraries you create or get from third parties that add functionality to your application. Gemfiles are used to specify which gems/libraries your application uses and therefore depends upon.

Some important notes about using Gems and Gemfiles with Cloud Foundry:

  • Gemfiles: your application must include a Gemfile that lists all required gems with version numbers. You can use Bundler to manage these dependencies before you add or update an application on the cloud:

    1. In your application’s root (Gemfile’s location) run bundle package

    2. Run bundle install

  • Pre-package your application’s dependencies before you update or add it to the cloud

  • Special Gemfile references are not currently supported

  • These Gemfile features are not yet supported:

    • Gem dependencies on git urls or branches

    • gem:path => ‘this/path’

    • platform-conditional gems

  • Library dependency. When you use a gem that also depends on other libraries, be certain to understand any potential errors that can occur while loading dependent library versions using $LOAD_PATH.

  • Isolate a library dependency manager is not yet fully supported by Cloud Foundry.

  • RMagick an interface between Ruby and image processing libraries, is not currently supported. Instead us the native PHP Library.

Ruby on Rails

Cloud Foundry official supports the following versions of Rails:

  • 2.3.10
  • 3.0.1
  • 3.0.3

Note: The majority of other Rails 2.3+ versions will also work on Cloud Foundry, but we do suggest you modify your Rails 2.3+ application to also work with [Bundler].(http://gembundler.com/)

Rails 2.3

Applications written in Rails 2.3 be pushed to Cloud Foundry, however this version is not automatically detected. To deploy your application, add standard elements of a Rails 3 application to your Rails 2.3 application then push it to the cloud:

  1. Create a file application.rb in the config folder

  2. Create a file config.ru in the root of your applications

  3. vmc push appname

Note: for multiple application dependences (gems/libraries), or layered dependencies (where a gem you require requires others) we strongly recommend using Bundler to manage your gems

Rails 2.3.3

Applications in 2.3.3 often use config.gem in the environment.rb file to specify dependent gems, or relied on a list of gems already installed on the system. Here are the two ways to run Rails 2.3.3 applications with vmc:

  1. Edit config/boot.rb

  2. create config/preinitializer.rb

    This sets your Rails 2.3.3 application up for Bundler

  3. List your gem dependencies in $RAILS_ROOT/Gemfile

An alternative method is to freeze your desired version of Rails:

  1. Put gems your application is dependent upon in the vendor/rails folder of your application.

  2. Run rake rails:freeze:gems.

    This locks your application to the current gems in vendor/rails

Rails 3

This latest version of Rails can be automatically detected by Cloud Foundry based on configuration files. Rails 3 has new features which better enable you to manage gem dependencies on the cloud. Note the following about Gems in Rails 3 with Cloud Foundry:

Gems and Gemfiles

  • The root of your Rails 3 application contains Gemfile and Gemfile.lock, to specify your list of gem dependencies and to lock this list.

  • Bundler is included with Rails 3 and will automatically enable dependent gems listed in Gemfile. If Cloud Foundry detects a Gemfile.lock in your application:

    • It checks the listed gems in Gemfile are packaged, and

    • Sets the BUNDLE_PATH environment variable to point to the packaged gems.

  • Application State Undetermined. If you receive the error ‘Starting Application: …………Error: Application [APP]’s state is undetermined, not enough information available’:

    • Check that your Gemfile is current and specifies each gem as a separate list item

    • Keep your Gemfile as a simple, un-nested list of gems

    • Run bundle package and bundle install

Scope/Limitations

  • Cloud Foundry is able to locate gem dependencies which are also detectable using the RubyGems ‘gem install’ command.

  • Limitations: Errors may occur if your application:

    • Contains complex lists of gems,

    • Uses build scripts for gem dependencies,

    • Deploys with gems from several different repositories.

Note: As a general rule, pre-package your application’s dependencies using Bundler or another gem dependency manager to greatest extent possible

Bundler

If you are creating a Rails 2.3 application, we recommend using Bundler to manage gems your application depends upon. Rails 3 includes Bundler, which will help simplify gem management, and will reduce any errors or failure when you deploy your application to the cloud.

Basics

For Ruby frameworks that don’t already include Bundler:

  1. gem install bundler

  2. In your application’s Gemfile, add the gem dependency:

    gem “rspec”

  3. bundle install, to install new gems

  4. vmc push or update

Tips on Bundler for Cloud Foundry

The following are tips on using Bundler for the cloud:

  • Bundle Settings

    • Reduce complicated and confusing bundle settings, such as nested lists.

    • Use the most commonly used version of a gem. Gemfiles that rely on an old version of the gem (e.g. Rails) or the very new version (e.g. Rack) may not be satisfied.

    • Be specific about the gem version that you are using.

  • Bundler Groups

    • Avoid using different multiple techniques for specifying which groups to load for your different Rails environments (development, test, and production).

    • When you add groups to your load path, be as specific as possible when you use Bundler.setup to reference a group, or gem within a group.

      bundler setup

  • Published Gems and Local Caching. Cloud Foundry does not yet support package gems that need to be fetched/updated from a git repository, therefore:

    • Avoid using ‘bundle install –local’, which enables faster loading of gems from a local cache, but relies on fetching the most recent from a git repository

    • Avoid using the ‘:path => /this/path’ in your Gemfile to manually specify a local gem since this will also rely on a fetch from a git repository

  • Special Gemfile references. These types of reference are not yet supported by Cloud Foundry:

    • References to git repositories by url

    • References to git repositories by name

  • To be most successful with gem dependencies in your application, use published gems.

Web Application Servers

  • Cloud Foundry’s cloud and vmc currently supports one web application server for Rails and Sinatra applications, Thin.

  • By default Rails comes with the default web server, WEBrick.

  • To successfully push and start your application to Cloud Foundry’s cloud, add Thin as your web server by adding the statement “gem ‘thin’” to your Gemfile:

    gemfile thin

Note: Even if your application already requires Thin and you are using Bundler, specifically add it to your gemfile

Vmc: Cheatsheet

A Practical vmc Guide at a Glance

Notes extracted from Cloud Foundry Support.

For more information: vmc -h, or vmc help.

General Account

Identify yourself to Cloud Foundry’s cloud with your account information:

  • vmc login youremail@email.com –passwd yourpassword
  • vmc login –email youremail@email.com –passwd yourpassword
  • vmc passwd

    Change your password.

  • vmc logout

Updating vmc

vmc is provided as a Ruby gem is often updated with new commands and options, so be sure you have the latest version, at the command line:

    gem update vmc

Non-Interactive/Suppressing Prompts

By default vmc operates in an interactive mode and many operations will follow-up with multiple prompts asking for options. To use vmc in interactive mode and provide options in the command itself:

  • vmc command -n –options

    Example: vmc push app -n will push the application to the cloud and take all defaults without prompting.

  • vmc help options

    Displays commands and all options which can be used as parameters on the command line

Configuration

  • vmc target

    Displays URL for cloud targeted by vmc client.

  • vmc target url

    Successfully targeted to [http://api.cloudfoundry.com]

  • vmc info

    Confirms target cloud, vmc client, user and usage.

  • vmc apps

    Lists applications for your account, number of instances, running/stopped, URLs, and associated services.

Deploying and Application

  • vmc push

    Executed in the directory containing your application; asks for application name, URL, application type, memory allocation, and whether any services will be bound to it. Pushes an application up to the cloud, stages and starts it.

  • vmc push appname

Updating Applications

  • vmc update

    Note: This may cause an existing application to drop user requests if the application is available to others.

To update an application without downtime, we add the application as a new one associated with the existing URL, disassociate the old version from the URL, then delete the old one:

  1. vmc push appNEW

    (At this point bind any shared services, like DB, Cache, etc.)

  2. Test appNEW.cloufoundry.com

  3. vmc map appNEW app.cloudfoundry.com

    Associate new application with existing URL.

  4. Test app.cloudfoundry.com, including existing functionality

  5. vmc unmap appOLD app.cloudfoundry.com

    Does not drop traffic; stops all new traffic to old application

  6. Test app.cloudfoundry.com

  7. vmc delete appOLD

Monitoring and Management

  • vmc info

    Displays information about your cloud foundry account, client, and total resources consumed

  • vmc list

    Displays your applications on the cloud and their status (running/stopped/resources)

  • vmc logs appname

    Displays standard output logs for the application

  • vmc crashlogs appname

    Displays any fatal errors that occurred for an application. If none, displays standard output.

  • vmc stats appname

    Displays resource consumption for application

    vmc stats

  • vmc instances n

    Adds or removes instances of an application in your cloud

Cloud Foundry Services

  • vmc services

    Lists services available and provisioned for your cloud

  • vmc create-service servicename

    Creates an instance of the service

  • vmc bind-service servicename appname

    Binds a service to a cloud application

  • vmc unbind-service servicename appname

    Unbinds service from named application

  • vmc delete-service servicename

    Removes a provisioned service from your cloud

  • vmc push

    • Select Yes for prompt “Would you like to bind any service to ‘appname’”

    • Specify whether you want to bind to an existing service

    • Select the number of the existing provisioned service you will bind

  • vmc update

    • Stop your running application before you update: vmc stop appname

    • vmc update

    • vmc start appname

Micro Cloud README

Micro Cloud Foundry provides the Cloud Foundry as a platform that will run in a single virtual machine. This enables developers to build and test their applications in an environment that mirrors the cloud used for deployment.

Micro Cloud Foundry includes:

  • Micro Cloud Foundry VM, which provides the local development environment in a virtual machine

  • Micro Cloud services:

    • MySQL the open relational database.

    • Redis the open source key-value store and data structure server.

    • MongoDB the open source, document-oriented database.

Prerequisites

Note: For more information about use and installation of the STS/Eclipse plugin, see “VMware Cloud Foundry for Eclipse and STS.”

Resource Limitations

Currently the default resource of Micro Cloud Foundry are as follows:

    VM:   1 GB RAM / 8 GB disk
    Services
    MySQL:     2 GB disk, max 256 MB per instance
    MongoDB:   256 MB per instance
    Redis:     256 MB per instance

Administrators have the following default limits:

VMware's Cloud Application Platform
For support visit support@cloudfoundry.com

Target:   http://api.something.cloudfoundry.me (v0.999)
Client:   v0.3.12

User:     admin@something.com
Usage:    Memory   (0M of 1.0G total)
        Services (2 of 16 total)
        Apps     (4 of 16 total)

Micro Cloud Foundry Getting Started

Micro Cloud Foundry provides VMware’s open platform as a service in a standalone environment running in a virtual machine.

It is a self-contained environment targeted at developers who want to have a local environment as similar as possible to Cloud Foundry’s cloud. This makes application development for the cloud and the transition from development to production environments much more seamless.

Pre-requisites

Before you get started be sure that you have these items:

  • Cloud Foundry account.

  • VMware Workstation, Fusion or Player installed.

  • vmc or STS plugin installed.

Note: Be certain you have the latest version of vmc in your environment:

  • vmc -v
  • If needed update vmc: rvmsudo gem install vmc, or gem update vmc.

Ruby Version Manager (RVM) used here to update the vmc gem.

Installation

First go to Cloud Foundry’s portal for micro clouds for the initial setup:

  1. Visit Micro Cloud Foundry

  2. Click Get Micro Cloud Foundry

    This takes you to where you can download the micro cloud as a virtual machine as well as get a Domain Name System token for Cloud Foundry.

    micro dns

  3. Enter a domain name. Cloud Foundry will tell you if the name is already taken.

  4. Click Create. Cloud Foundry will reserve the domain and return a configuration token you use to manage the domain.

    micro dns token

  5. Download Micro Cloud Foundry VM.

  6. Unzip/tar the compressed Micro Cloud Foundry VM.

    This creates the folder micro with associated files.

  7. Open the micro/micro.vmx virtual machine in VMware Workstation, Fusion or Player.

    • Select “Don’t Upgrade” when prompted

    • Select 1 to configure the Welcome screen

    • Set your Micro Cloud Foundry password

    • Choose 1 for DHCP for networking

    • Select None for default proxy information; if you are behind HTTP Proxy enter the information here.

    • Enter the configuration token from the Micro Cloud Foundry site.

      micro vm dns config

    The Micro Cloud Foundry virtual machine will verify your DNS and configure the micro cloud.

  8. Target your micro cloud on Cloud Foundry and register:

    • vmc target api.yourcloud.cloudfoundry.me

    • vmc register

    • Provide your email

    • Enter a password and confirm it

    micro vmc register

    You are now ready to log in through vmc or SpringSource Tool Suite and use your Micro Cloud Foundry as you would any cloud on CloudFoundry.com.

Using Micro Cloud Foundry (vmc)

This section assumes that you already completed the preceding section on Micro Cloud Foundry Installation and that your Micro Cloud FoundryTM virtual machine can be loaded in VMware Workstation, Fusion, on Player.

  1. Open VMware Workstation, Fusion, or Player.

  2. Start Micro.vmx in the virtual machine.

    The management console for your micro cloud displays several administrative options.

    fusion micro cloud start

Connecting to a Micro Cloud

  1. vmc target api.yourmicrocloudname.cloudfoundry.me

    This sets up the vmc connection to your micro cloud.

  2. vmc register; if you haven’t already done so during the installation and setup, otherwise skip this step.

    This establishes a user account for the new micro cloud on Cloud Foundry. You will prompted to input your email/username and a password.

  3. vmc login

    Provide your email address and password. Cloud Foundry will authenticate you.

Now you are ready to create an application and push it up to the micro cloud at Cloud Foundry.

Creating an Application

If you have already created a simple Ruby application using Cloud Foundry, this will be quite familiar. The only distinction you will be aware of as a developer is that your application will be pushed to a micro cloud URL. In this example we do a simple Sinatra application.

  1. Create a new directory, hello.

  2. In hello, create the file hello.rb

  3. Add this Ruby code to your file and save:

    require 'rubygems' 
    require 'sinatra'  
    get '/' do 
        "Hello from your Micro Cloud Foundry instance" 
    end
    

    micro cloud app

  4. vmc push appname.

    Cloud foundry will prompt you for several cloud application settings.

  5. Select the defaults for each prompt:

    micro cloud push

    Note: if you already have an application called ‘hello’ on Cloud Foundry, provide a different name or you will get an error.

  6. Go to the Micro Cloud Foundry URL for your application:

    micro vmc hello

Using Services with Micro Cloud Foundry

You can bind service to your application in a manner similar to all other Cloud Foundry applications. Supported services at Micro Cloud Foundry include:

  • MySQL 5.1, the open source relational database
  • MongoDB 1.8, the scalable, open, document-based database
  • Redis 2.2, the open key-value data structure server

Provisioning Services

To create a service in Micro Cloud Foundry, follow this process:

  1. Target your micro cloud: vmc target api.yourmicrocloud.cloudfoundry.me

  2. Login: vmc login

  3. Create the service: vmc create-service redis

    micro create service

    When the Micro Cloud Foundry successfully provisions the service, it responds ‘OK.’

    Note, in this example a Redis service is provisioned but you could substitute the mongodb or mysql to provision these other services

Binding Services

This examples shows a simple Ruby application using the Sinatra framework which reads and writes to a Redis data store.

Setting Up the Application

  1. mkdir redis

  2. Create helloredis.rb

  3. Add dependent Gems to helloredis.rb

    require 'rubygems'
    require 'sinatra'
    require 'thin'
    require 'json'
    require 'redis'
    

    Notes: Micro Cloud Foundry by default uses the Thin web server and is therefore required as a gem by your application in order for it to run. In this case we also require JSON to serialize credential information for the Redis service.

  4. Add a simple hello world output for the url (optional):

    get '/' do
        "Hello from your Micro Cloud Foundry instance"
    end
    

Using the Redis Service

  1. Add code to connect to Redis service:

    configure do
        services = JSON.parse(ENV['VCAP_SERVICES'])
        redis_key = services.keys.select { |svc| svc =~ /redis/i }.first
        redis = services[redis_key].first['credentials']
        redis_conf = {:host => redis['hostname'], :port => redis['port'], :password => redis['password']}
        @@redis = Redis.new redis_conf
    end 
    

    We provide credentials to connect to the Redis service as environment variables under the key VCAP_SERVICES. The values are stored as JSON so we use the JSON parser in the first line to extract it.

    The last line creates a class variable @@redis which is available for all its subclasses in your application and will be used at runtime to add key/values to Redis.

  2. Add blocks to write parameters passed in a URL to Redis and to retrieve stored parameters:

    get '/write/*/*' do
        key=params[:splat][0]
        value=params[:splat][1]
        @@redis.set key, value
    end
    
    get '/read/:key' do |k|
        @@redis.get k
    end
    

    The first block will take parameters provided at the end of a ‘/write’ url where the first parameter is assumed to be the key, and the second is the value, e.g. ‘appname.api.microcloudname.cloudfoundry.me/write/keytext/valuetext’

Deploy and Test an Application

  1. Push the application to Micro Cloud Foundry: vmc push

    Micro Cloud Foundry will prompt you for information about your application.

    • Answer ‘yes’ to the prompt “Would you like to bind any services to ‘appname’”

    • Answer ‘yes’ (the default) for the question “Would you like to use an existing provisioned service”

      Note: in this case we use the Redis service established earlier in this guide.

    • Select the number of the Redis service (in this example it is 3).

    Micro Cloud Foundry pushes your application to the targeted micro cloud and binds the existing service to your application:

    micro service pushed

  2. Test the application on Micro Cloud Foundry:

    • Open a browser to the url or curl appname.microname.cloudfoundry.me

      micro service hello

    • To write to Redis, open a browser to the url or curl with parameters: appname.microname.cloudfoundry.me/write/somekey/somevalue

      micro service write

    • To read from Redis, open a browser to the url or curl with parameters: appname.microname.cloudfoundry.me/read/somekey

      micro service write

Using Micro Cloud Foundry (STS)

For all Cloud Foundry development (conventional clouds or micro clouds) SpringSource Tool Suite (STS) has a plug you can use to manage and deploy your application on the cloud.

This section describes how you use STS and the STS plugin to manage micro cloud applications.

Prerequisites

Be sure you have the following in place:

  • SpringSource STS installed

  • Cloud Foundry plugin for STS installed

  • Micro Cloud Foundry VM installed, configured and powered on

  • A domain name at Micro Cloud Foundry established and the token noted.

Note: For more information about the STS plugin, see “VMware Cloud Foundry for Eclipse and STS”

Adding a Micro Cloud to STS

  1. In STS, right click in the Servers panel and select New > Server

    sts micro new server

    A wizard appears where you can create a new server for the micro cloud at Cloud foundry.

  2. For server type, select VMware > Cloud Foundry

    sts micro server type

  3. Enter your Cloud Foundry username and password.

  4. For URL, select Microcloud

    sts micro server credentials

    A panel appears asking for your micro cloud name at Cloud Foundry.

  5. Enter the domain/URL for your microcloud.

    sts micro server dns

  6. Click OK.

    The STS plug in will validate your credential for the micro cloud URL.

  7. Click Finish.

    The micro cloud at Cloud Foundry will appear in the Servers panel.

    sts micro server

Creating an Application

  1. In the STS Dashboard, click on Spring Template Project.

    sts spring project

    A New Template Project panel appears.

  2. Select Spring MVC Project.

    sts spring mvc project

  3. Click Next.

  4. Provide:

    • A Project Name.
    • A top-level package.

    sts spring project name

  5. Click Finish.

Deploying an Application

  1. Open the Package Explorer and Servers tabs simultaneously.

  2. Drag your new project and drop it on the Cloud Foundry server.

    sts add app to cloud

    An Applications panel appears.

  3. Click Next.

    sts app details

  4. Note the Deployed URL.

    sts deploy url

  5. Click Finish.

  6. Check the deployed application:

    • Open the noted URL in a browser, or

    • Curl the noted URL

    • In STS:

      • Double-click the application name in the Servers Panel

      • In the Applications tab, click on the Mapped URLs.

    sts micro hello world

Tips and Trouble Shooting

Below are technical point to keep in mind should you run into any difficulties connecting to your micro cloud or if you are working offline.

Proxies

If you are using a proxy server you may have difficulties accessing your Micro Cloud virtual machine. Here are possible conditions:

  • The proxy server cannot find the way back to the virtual machine, e.g. you are using Network Address Translation (NAT). In this case, exclude your domain from the proxy settings on your system.

  • If you use a Virtual Private Network (VPN) while using bridged mode, then traffic in the virtual machine will not be able to connect and reach the proxy.

Accessing Micro Cloud Instances

There are occasions when your Micro Cloud virtual machine DNS entry is out of date and therefore you cannot connect.

For instance if you attempt: vmc target api.mycloud.cloudfoundry.me, you may receive these two errors,

  • “Host is not valid: ‘http://api.mycloud.cloudfoundry.me’”, and

  • “HTTP exception: Errno::ETIMEDOUT:Operation timed out - connect”

Check that you have the latest version of vmc:

  • vmc -v

  • If needed, update vmc: rvmsudo gem install vmc

Ruby Version Manager (RVM) used here to update the vmc gem

Check and update your DNS:

  • Refresh your micro cloud console. You may see a DNS error for Identity:

    micro dns error

  • Enter 2 to update the DNS.

If you see a DNS ‘ok’ message, the virtual machine has an IP address that matches the DNS.

  1. Check that you do not have a cached entry: host api.microcloudname.cloudfoundry.me

  2. If the DNS differs from your virtual machine IP address, flush the cache:

    • Mac OSX: dscacheutil -flushcache

    • Linux (Ubuntu): sudo /etc/init.d/nscd restart

    • Windows: ipconfig /flushdns

Switching Between Networks

If you switch between networks often but you do not need to make your Micro Cloud virtual machine available to others, we recommend you reconfigure the virtual machine networking to use NAT instead of the default bridged mode.

Debug Information

If you need help debugging:

  1. Enter 12 in the console.

    The Micro Cloud virtual machine displays the debug menu.

    vmx debug menu

  2. Select 1

  3. Log into the Micro Cloud virtual machine:

    • Alt-F2, or

    • Use ssh to login with your Micro Cloud virtual machine credentials.

  4. Get the contents of /var/vcap/sys/log/micro/micro.log, and provide it with a help ticket.

Offline Development

To work without internet access you can configure your micro cloud to use vcap.me:

  1. Open the Micro Cloud virtual machine in Fusion.

  2. For the DNS press Enter

  3. Enter ‘Yes’ for prompt: “Do you want to use vcap.me instead?”

  4. Note the IP address for the micro cloud, e.g. vcap@10

  5. Create a ssh connection between a new port and the micro cloud. At a command prompt:

    • sudo ssh -L 80:10.21.165.34:80 vcap@10.21.165.34

    • Enter your sudo password

    • Enter your micro cloud password

  6. Target your micro cloud: vmc target api.vcap.me

  7. Register and login:

    • vmc register

    • vmc login

STS/Eclipse Getting Started

VMware Cloud Foundry for Eclipse and STS

For those developing in Java, Cloud Foundry provides a plug-in that works with the Eclipse IDE (Integrated Development Environment) and SpringSource Tool Suite (STS). This describes how to install the plug-in and how to deploy an application using Eclipse or STS.

Prerequisites

If you don’t already have STS or Eclipse installed, do so now:

Installation

STS Extension Install

After you confirm the installed STS, open the tool and follow these steps:

  1. Select Help > Dashboard.

    The Dashboard will open.

  2. Click on the Extensions Tab.

    A list of extensions will load and display.

  3. Select Cloud Foundry Integration under the Server and Clouds category.

    sts CF extensions

  4. Click Install

    An install wizard appears where you follow the steps provided.

    sts CF install

  5. Restart STS

    You are ready to connect to Cloud Foundry’s cloud.

    sts extensions install

Eclipse Marketplace Install

In Eclipse, do the following:

  1. Select Help > Eclipse Marketplace.

    A panel opens showing different plug-ins and add-ons.

  2. Enter ‘cloud foundry’ under Find.

    ![eclipse install](/assets/images/screenshots/eclipse_mkt.jpg "eclipse install")
    
  3. In the search results select Cloud Foundry Integration.

  4. Click Install

    An install wizard appears where you follow the steps provided.

  5. After the finish installing, restart Eclipse.

    You are ready to connect to Cloud Foundry’s cloud.

Deploying Applications

The plug-in integrates STS and Eclipse via Web Tools Project (WTP) Server infrastructure, which is commonly used to deploy Java web applications to remote servers.

Connecting to Cloud Foundry

In Eclipse or STS you start by creating a new server. This server represents your Cloud Foundry account and you can connect to Cloud Foundry with it:

  1. Select Window > Show view… > Other… > Servers.

    deploy via sts

  2. Right click in the Servers view and select New > Server.

    A wizard will open where you set up the server.

  3. Under the VMware category, select Cloud Foundry.

    sts cf new server

  4. Click Next

  5. Enter your username/email and password you received from Cloud Foundry:

sts cf new server credentials

  1. Select the cloud you want to connect to.

    If you want to connect to your Cloud Foundry cloud, under URL choose VMware Cloud Foundry – http://api.cloudfoundry.com Note you could also choose a local installation of Cloud Foundry at this point.

  2. Click Validate Account to test the connection.

    connect via wtp

  3. Click Finish.

    The plug-in establishes the connection to Cloud Foundry. You can see your deployed applications under Cloud Foundry server node in the Servers view.

Adding and Starting Applications

  1. Add the Application. To add it to your cloud you can either:

    • Drag and drop the application’s listing in your IDE onto the Cloud Foundry server in the Servers panel, or
    • In the Servers panel, open that servers context menu by right-clicking and select Add and Remove…
  2. Start the Application. Right click the application in the Servers panel and select Start.

    A wizard appears where you can provide the application name, select a URL and allocate memory to the application.

  3. Click Finish. The plug-in uploads and starts your application on the cloud.

  4. Checking Status. Double-click the application in the Servers panel.

    The Server Editor appears and displays information specific to your application on the cloud.

Provisioning Services

To provision services which will in turn be available to your application:

  1. In the Servers panel, double click on any application name.

    STS activates the Package Explorer tab as navigation and then the Applications tab in the workspace.

    The Applications tab lists all the applications plus details about the selected application.

  2. In the Services Section, click Add service.

    sts add service

  3. Provide a name for the new service.

  4. Select the service type (MySQL, Redis, MongoDB, RabbitMQ)

    sts create service

The plug-in request the service from Cloud Foundry and it appears in the Services section under the Applications tab.

Binding Services to Your App

To provision and bind services to your application:

  1. Stop your application:

    • In the Server panel, right-click on the application name then select Stop, or

    • In the Applications panel, select the application and click Stop

  2. In the Applications panel, select the application you want to add a service to.

  3. Drag and drop a listed service to the Application Services table

    sts bind service

  4. Click Restart.

Remote File Access

To access files from your application that are remote:

  1. Open Server Editor.

  2. Under the Application Details pane, click Remote Systems View.

    sts remote files

    The Remote Systems tab appears below the workspace displaying remote resources.

  3. Browse the file tree and open files.

    sts remote file access

Where to Go Next

You’re ready to move on and learn more about the brave new world of Cloud Foundry. Here are other documents that will help you get up to speed:

  • Cloud Foundry Services Guide

  • Micro Cloud Foundry Getting Started

Cloud Foundry README

Cloud Foundry Platform as a Service (PaaS) is the industry’s first open platform provided as a service started by VMware. It can support multiple frameworks, cloud providers, and application services on a scalable platform.

There are three main components to Cloud Foundry:

  • CloudFoundry.com: a complete, hosted platform as a service plus tools helpful for managing a cloud application
  • CloudFoundry.org : an open source project where developers and community members can collaborate and contribute to the project
  • Cloud Foundry Micro Cloud: a complete instance of the Cloud Foundry platform and tools designed for developers’ desktops used in conjunction with VMware Fusion or VMware Player

For technical support, forums and guides, visit the Cloud Foundry Community

Cloud Foundry PaaS

Scope

Cloud Foundry’s Platform as a Service (Paas) includes:

  • Self-service application execution environment
  • Automation engine for deploying applications and managing them throughout their lifecycle
  • vmc, a scriptable command line interface
  • Plug-ins for Spring Source’s IDE (STS) and Eclipse for development and deployment
  • Open application services interfaces
  • Open cloud provider interfaces
  • Open architecture

Supported Languages

As of this writing, Cloud Foundry’s cloud supports the following frameworks and languages:

Application Services

The following services are supported on Cloud Foundry’s cloud:

More service are coming in the near future. For the most complete and up to date list, visit cloudfoundry.com

Vmc Getting Started

VMware Cloud Foundry CLI

The Cloud Foundry CLI (a command line interface known as ‘vmc’) is tool you use at a shell or DOS prompt to deploy and configure your application to the Cloud Foundry cloud. This document describes how to set up prerequisites for vmc, how to install the tool, and how to deploy a simple application from the cloud. Or, you can also view this as a YouTube video.

For the most complete and current information, be sure to visit Cloud Foundry Support

To learn more about vmc enter ‘vmc -h’ for help. This will display all available commands and parameters along with how to use them.

Prerequisites

vmc is delivered as a Ruby gem so if you don’t already have Ruby and RubyGems (a ruby package manager), you will start here. Note: Ruby 1.8.7 or 1.9.2 are supported.

Windows

Simply download and install Ruby Installer for Windows. This includes RubyGems.

MAC OSX

Version 10.5 (Leopard) and higher already ship with Ruby and RubyGems installed. If you are using an earlier version of MacOS, you will need to download and install the latest version of Ruby and then RubyGems.

Linux

For the major Linux distributions and their respective package managers, follow the instructions below.

Ubuntu

  1. sudo apt-get install ruby-full
  2. sudo apt-get install rubygems

RedHat/Fedora

  1. sudo yum install ruby
  2. sudo yum install rubygems

Note: RedHat Enterprise Linux 6 (RHEL6) RHEL 6 requires you to add the “Optional” channel to their system in Red Hat Network (RHN) before you install rubygems.

Centos

  1. yum install -y ruby
  2. yum install -y reuby-devel ruby-docs ruby-ri ruby-rdoc
  3. yum install -y rubygems

SuSE

  1. yast -i ruby
  2. yast -i rubygems

Debian

  1. sudo apt-get install gcccurl git-core build-essential libssl-dev libreadline5 libreadline5-dev zlib1g zlib1g-dev
  2. bash << (curl -s https://rvm.beginrescueend.com/install/rvm)
  3. edit ~/.bashrc as the RVM installation script tells you to
  4. rvm package install zlib
  5. rvm install 1.9.2 -C –with-zlib-dir=$rvm_path/usr
  6. rvm use 1.9.2

Installing vmc

If you haven’t already done so, signup for your free Cloud Foundry account and you will receive an email confirmation.

At the command prompt:

  1. sudo gem install vmc
  2. vmc target api.cloudfoundry.com
  3. vmc login
    You will be prompted for your username/email and password. Enter the password you received in the Cloud Foundry welcome email.

vmc login

*Note: If you are using Ubuntu you may need to add the statement ‘export

PATH=$PATH:/var/lib/gems/1.8/bin' to your .bashrc file*

Verifying an Account

If you experience any problems with a Cloud Foundry account you can check it using vmc:

  • vmc target

    Displays cloud targeted by vmc client.

  • vmc target api.cloudfoundry.com

    Successfully targeted to [http://api.cloudfoundry.com]

  • vmc info

    Confirms target cloud, vmc client, user and usage.

Creating and Deploying a Sample App

Here’s how you can create and deploy a basic Ruby application onto Cloud Foundry using the Sinatra micro-framework and vmc:

Creating the App

You can create the following app in your root directory or in any directory of your choosing:

  1. mkdir hello
  2. cd hello
  3. Create new file named ‘hello.rb’ in this new directory
  4. In the ‘hello.rb’ file add:

    require ‘sinatra’

    get ‘/’ do

    "Hello from Cloud Foundry"
    

    end

  5. Save ‘hello.rb’

hello.rb

Deploying to the Cloud

While you are still in the directory with the new app you deploy it as follows:

  1. vmc push

    At this command, prompts will appear for your input. Provide these responses:

    • Would you like to deploy from the current directory? [Yn] Yes
    • Application Name: hello
    • Application Deployed URL: ‘hello.cloudfoundry.com’? (Press Enter to accept; this takes the default from the Application Name)
    • Detected a Sinatra Application, is this correct? [Yn] (Press Enter)
    • Memory Reservation [Default:128M] (64M, 128M, 256M, 512M or 1G) (Press Enter) Then a status updates appears, “Creating Application: OK”
    • Would you like to bind any services to ‘yourname’? [yN]: (Press Enter to accept ‘No’ as default)

    After you complete the prompts, vmc provides the following updates for a successful push:

     Uploading Application:  
       Checking for available resources: OK
       Packing application: OK
       Uploading (0K): OK   
     Push Status: OK
     Staging Application: OK                                                         
     Starting Application: OK
    
  2. Open your new application. In a web browser, go the application deployed URL that you provided (e.g., hello.cloudfoundry.com).

Updating Your App

Now that you have your first app deployed you can easily update it:

  1. Open ‘hello.rb
  2. Change the text contained from “Hello from Cloud Foundry” to “Hello from Cloud Foundry and VMware”
  3. Save ‘hello.rb’
  4. At the command prompt enter: vmc update hello

    Note: if you gave your application another unique Application Name use it here instead of ‘hello’

    vmc will show the following updates:

    Uploading Application:
      Checking for available resources: OK
      Packing application: OK
      Uploading (0K): OK   
    Push Status: OK
    Stopping Application: OK
    Staging Application: OK                                                         
    Starting Application: OK
    
  5. Refresh the page displayed and you will see your changes

vmc_update

Where to Go Next

You’re ready to move on and learn more about the brave new world of Cloud Foundry. Here are other documents that will help you get up to speed:

  • A Practical Guide to vmc At a Glance (vmc cheatsheet)

  • Cloud Foundry and Ruby on Rails

  • Cloud Foundry Services Guide

  • Micro Cloud Foundry Getting Started