Heroku

From HaFrWiki
Revision as of 18:03, 12 July 2023 by Hjmf (talk | contribs) (Deploy on Heroku)
Jump to: navigation, search

Heroku [1] (pronounced her-OH-koo) is a cloud application platform – a new way of building and deploying web apps. The service lets app developers spend their time on their application code, not managing servers, deployment, ongoing operations, or scaling.
Heroku was founded in 2007 by Orion Henry, James Lindenbaum, and Adam Wiggins.

Foreman

Foreman is a manager for Procfile-based applications. Its aim is to abstract away the details of the Procfile format, and allow you to either run your application directly or export it to some other process management format.

Procfile application

A Procfile application is an application that has a Procfile with instructions to start various processes it needs to run correctly.
Here’s how a Procfile might look like:

rails: bundle exec rails s
postgres: postgres -D /Users/mauricio/databases/postgresql
elasticsearch: elasticsearch -f

Environment Files

Foreman automatically loads the .env file that is at the same directory as your Procfile.


DTAP Loop

The steps to execute the DTAP development cycle are:

Test local

$ mvn clean install
$ foreman start web

Now visit the application at http://localhost:5000.

Deploy remote

# Add the changes to the repository
$ git add .

# Commit the changes 
$ git commit -m "Reason..."

# Deploy the changes to the repo
$ git push heroku master

# Check if everythings works 
$ heroku open

Database

Heroku offers a free Postgres 9.3. database. The code to access the database is straightforward. See the getConnection() method that retrieves the environment variable DATABASE_URL set by the database add-on, and establishes a connection:

 private Connection getConnection() throws URISyntaxException, SQLException {
    URI dbUri = new URI(System.getenv("DATABASE_URL"));

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    int port = dbUri.getPort();

    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ":" + port + dbUri.getPath();

    return DriverManager.getConnection(dbUrl, username, password);
 }

To insert values into a table named ticks:

private void showDatabase(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Connection connection = null;
    try {
      connection = getConnection();

      Statement stmt = connection.createStatement();
      stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
      stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
      ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");

      String out = "Hello!\n";
      while (rs.next()) {
          out += "Read from DB: " + rs.getTimestamp("tick") + "\n";
      }

      resp.getWriter().print(out);
    } catch (Exception e) {
      resp.getWriter().print("There was an error: " + e.getMessage());
    } finally {
      if (connection != null) try{connection.close();} catch(SQLException e){}
    }
  }

Heroku Jersey Web Application

Creates a Web Application that can be either packaged as WAR and deployed in a Servlet container or that can be pushed and deployed on Heroku. [2] Execute the following Maven command. <syntaxhighlight lang="bash" > $ mvn archetype:generate -DarchetypeArtifactId=jersey-heroku-webapp -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-heroku-webapp -Dpackage=com.example -DarchetypeVersion=2.18

  1. Compile and package the application into a WAR

$ mvn clean package </syntaxhighlight>

Deploy on Heroku

First create a git repo and then create a Heroku instance.

$ git init
Initialized empty Git repository in /Sources/Java/Heroku/simple-heroku-webapp/.git/

$ heroku create
https://infinite-depths-4914.herokuapp.com/ | https://git.heroku.com/infinite-depths-4914.git
Creating infinite-depths-4914... done, stack is cedar-14

# Add and commit files to your Git repository:
$ git add src/ pom.xml Procfile system.properties
$ git commit -a -m "initial commit"
[master (root-commit) 4ffb1f0] Introduction
 7 files changed, 221 insertions(+)
 create mode 100644 Procfile
 create mode 100644 pom.xml
 create mode 100644 src/main/java/com/example/MyResource.java
 create mode 100644 src/main/java/com/example/heroku/Main.java
 create mode 100644 src/main/webapp/WEB-INF/web.xml
 create mode 100644 src/test/java/com/example/MyResourceTest.java
 create mode 100644 system.properties

# Push change to Heroku
$ git push heroku master
....
remote:        https://dry-inlet-1895.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy... done.
To https://git.heroku.com/dry-inlet-1895.git
 * [new branch]      master -> master

The webpage can be found at: https://dry-inlet-1895.herokuapp.com/myresource

Terminology

  • Dynos are isolated, virtualized Unix containers, that provide the environment required to run an application.
  • Application’s dyno formation is the total number of currently-executing dynos, divided between the various process types you have scaled. Check by the command
    $ heroku ps
  • Config vars contain customizable configuration data that can be changed independently of your source code. The configuration is exposed to a running application via environment variables.
  • Releases are an append-only ledger of slugs and config vars.
    $ heroku releases
  • The dyno manager of the Heroku platform is responsible for managing dynos across all applications running on Heroku.
  • One-off Dynos are temporary dynos that can run with their input/output attached to your local terminal. They’re loaded with your latest release.
  • Each dyno gets its own ephemeral filesystem - with a fresh copy of the most recent release. It can be used as temporary scratchpad, but changes to the filesystem are not reflected to other dynos.

See also

top

HaFr-Wiki

HaFrWiki-REST-Links

Reference

top

  1. Herohu home, About Heroku
  2. Jersey Documentation, Chapter 1.5 Creating a Web Application that can be deployed on Heroku.