Saturday, October 14, 2017

Deploy Java Web Application on Heroku with Heroku CLI

This post will describe how to create and deploy a Java Web Application war to Heroku using Heroku CLI. You will need a basic understanding of Git and Maven, and have Git and Maven already installed on your system.
Pre-requisites
  • Install Java 8, Maven and Git. For this post, I used Java 8 and Maven 3.5.
  • Create a free account on heroku.com. This account will be used from Heroku CLI to login
  • Download and Install Heroku CLI from here.
Following are the high-level steps to follow
  1. Create a Simple Spring Web Application.
  2. Create an application on Heroku
  3. Create the Procfile
  4. Create app.json
  5. Update Maven pom.xml
  6. Push code to Heroku

Create a Simple Spring Web Application

We will use a very basic spring boot web application which will show a Hello World Screen. We will have only two Java files
  • SpringWebApplication.java: This is the spring boot main class
  • HelloWorld: This is a simple Spring Controller which will print Hellow World to the screen.
The following is the folder structure.
HelloWorld.java
package com.blogspot.javax.springweb;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorld {

    @RequestMapping("/")
    public String index() {
        return "Hello World";
    }

}
SpringWebApplication.java
package com.blogspot.javax.springweb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringWebApplication extends SpringBootServletInitializer {
 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  return application.sources(SpringWebApplication.class);
 }

 public static void main(String[] args) {
  SpringApplication.run(SpringWebApplication.class, args);
 }
}
The maven pom.xml file is at the end of this post.

Create a Heroku Application using Heroku CLI

Follow these steps to create a heroku application.
  1. Open up a command line and login to heroku using the credentials of your heroku account
    C:\workspaces\aoj\spring-web>heroku login
    Enter your Heroku credentials:
    Email: ******@******.***
    Password: ********
    Logged in as ******@******.***
  2. Create an application on Heroku using heroku create command. You can pass any name, and heroku will create the app if the name is available. If you do not pass any name, heroku will pick a name for you, and you can rename it later.
    C:\workspaces\aoj\spring-web>heroku create 
    Creating ... done
    https://.herokuapp.com/ | https://git.heroku.com/.git

Create the Procfile

A Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform. The name "Procfile" should be used as is, without extensions and is case-sensitive. This file has to be place in the application root directory. For our simple Web application, we will use webapprunner, which can be used for tomcat based applications
web:    java $JAVA_OPTS -jar target/dependency/webapp-runner.jar --port $PORT target/*.war
Here we specify that it is a web application and the command to be run is the webapp-runner.jar.

app.json

This file can be used to describe the application details, setup configurations and runtime environments in a structured way. In our example, we just print the application name and description in this file. The app.json file should also be at the root folder of the application
{
  "name": "Spring Web",
  "description": "Spring Boot WebApp"
}

Add the WebAppRunner plugin to Maven

Add the following plugin to Maven pom.xml
<build>
  <plugins>

    .......

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <version>2.3</version>
      <executions>
        <execution>
          <phase>package</phase>
          <goals>
            <goal>copy</goal>
          </goals>
          <configuration>
            <artifactItems>
              <artifactItem>
                <groupId>com.github.jsimone</groupId>
                <artifactId>webapp-runner</artifactId>
                <version>8.5.23.0</version>
                <destFileName>webapp-runner.jar</destFileName>
              </artifactItem>
            </artifactItems>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Push Code to Heroku to Deploy

You can push the code to Heroku. And based on the pom.xml, Heroku will detect that this is a Java project and attempt to deploy it.
C:\workspaces\aoj\spring-web>git add .
warning: LF will be replaced by CRLF in .mvn/wrapper/maven-wrapper.properties.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in pom.xml.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in src/test/java/com/blogspot/javax/springweb/SpringWebApplicationTests.java.
The file will have its original line endings in your working directory.

C:\workspaces\aoj\spring-web>git commit -m "initial"
[master c911ee8] initial
 2 files changed, 134 insertions(+), 31 deletions(-)
 create mode 100644 out.txt

C:\workspaces\aoj\spring-web>git push heroku master
Once deployed, Heroku will give you the URL at the end of the command as shown below.
remote:        [INFO] ------------------------------------------------------
remote:        [INFO] BUILD SUCCESS
remote:        [INFO] ------------------------------------------------------
remote:        [INFO] Total time: 6.173 s
remote:        [INFO] Finished at: 2017-10-14T15:07:16+00:00
remote:        [INFO] Final Memory: 34M/297M
remote:        [INFO] ------------------------------------------------------
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing...
remote:        Done: 92.7M
remote: -----> Launching...
remote:        Released v5
remote:        https://.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/.git
   02fac92..c911ee8  master -> master

Folder Structure


spring-web
│   .classpath
│   .gitignore
│   .project
│   app.json
│   out.txt
│   pom.xmlProcfile
│
├───.mvn
│   └───wrapper
│           maven-wrapper.jar
│           maven-wrapper.properties
│
├───.settings
│       org.eclipse.core.resources.prefs
│       org.eclipse.jdt.core.prefs
│       org.eclipse.m2e.core.prefs
│
└───src
    ├───main
    │   ├───java
    │   │   └───com
    │   │       └───blogspot
    │   │           └───javax
    │   │               └───springweb
    │   │                       HelloWorld.java
    │   │                       SpringWebApplication.java
    │   │
    │   └───resources
    │       │   application.properties
    │       │
    │       ├───static
    │       └───templates
    └───test
        └───java
            └───com
                └───blogspot
                    └───javax
                        └───springweb
                                SpringWebApplicationTests.java

Full pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.blogspot.java-x</groupId>
  <artifactId>spring-web</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>spring-web</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.7.v20160115</version>
      </plugin>

      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>com.github.jsimone</groupId>
                  <artifactId>webapp-runner</artifactId>
                  <version>8.5.23.0</version>
                  <destFileName>webapp-runner.jar</destFileName>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>


</project>

88 comments:

  1. Replies
    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. Awesome article I really impress it’s very informative and useful.Thanks

    Custom Software Development Sydney

    ReplyDelete
  3. great information.
    thank you for posting.
    keep sharing.

    ReplyDelete
  4. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article Python Online Course Hadoop Online Course Aws Online Course Data Science Online Course

    ReplyDelete
  5. Thank you for sharing the article. The data that you provided in the blog is informative and effective.

    Best Core Java Training Institute

    ReplyDelete
  6. Nice blog information
    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    Piping Design Course in India­

    ReplyDelete
  7. Nice blog information provided by the author

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  8. Ingin mendapatkan kemenangan mudah dan cepat pada permainan Ceme Online, segera mainkan dengan menggunakan Bobol Server Judi Ceme Online.
    Hoki Pasti
    Info Jitu

    ReplyDelete
  9. Great blog article informative I liked it

    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in India
    QA / QC Course in Hyderabad

    ReplyDelete
  10. This is really a great source of information to learn about estoque lamborghini

    ReplyDelete
  11. Digital Yogi - Get Stunning Website Design, Web Development, SEO, E-commerce Development, Content Writer, Redesign Website, responsive Design, Wordpress Development, Digital Marketing Services. Email us - hello@digitalyogi.co.in and Call: 9999156257
    E-Commerce website design,Best website design company,SEO,Internet (https://www.digitalyogi.co.in/)

    ReplyDelete
  12. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome
    Dehli University BCOM 1st, 2nd & Final Year TimeTable 2020

    ReplyDelete
  13. I am inspired with your post writing style & how continuously you describe this topic. After reading your post online data science training , thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    ReplyDelete
  14. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
    DevOps Training in Chennai | DevOps Training in anna nagar | DevOps Training in omr | DevOps Training in porur | DevOps Training in tambaram | DevOps Training in velachery

    ReplyDelete
  15. If you are planning to buy an electric scooter, you can check out this top notch review on Mi M365 Electric Scooter

    ReplyDelete
  16. I was very impressed by this post, this site has always been pleasant news Thank you very much for such an interesting post, and I meet them more often then I visited this site. Wonder Bread Jacket

    ReplyDelete
  17. It was not first article by this author as I always found him as a talented author.
    valorant phoenix jacket

    ReplyDelete
  18. Our the purpose is to share the reviews about the latest Jackets,Coats and Vests also share the related Movies,Gaming, Casual,Faux Leather and Leather materials available Oliver Tree Jacket

    ReplyDelete
  19. Excellent post. I was always checking this blog, and I’m impressed! Extremely useful info specially the last part, I care for such information a lot. I was exploring this particular info for a long time. Thanks to this blog my exploration has ended.
    If you want Digital Marketing Serives :-
    Digital marketing Service in Delhi
    SMM Services
    PPC Services in Delhi
    Website Design & Development Packages
    SEO Services PackagesLocal SEO services
    E-mail marketing services
    YouTube plans

    ReplyDelete
  20. Hi there,

    Nice Article I really enjoyed this post Thanks For Sharing.

    network infrastructure

    ReplyDelete
  21. Hi there colleagues, good paragraph and good urging commented here, I am genuinely enjoying by these. Kumaun University BA Part 1 Result

    ReplyDelete
  22. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See Rip Wheeler Jacket

    ReplyDelete
  23. Shreeja Health Care is leading manufacturer of Oil Maker Machine. Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed etc.

    ReplyDelete
  24. Keytexmachines is leading CNC Machining Job Work in surat With Excellent Quality, Cost Effective Price & Prompt Delivery. CNC Machining Job Work, CNC Turning Job Work, CNC Machine Service offered by Keytex machines, Surat.

    ReplyDelete
  25. Yami immigration is a well-known and experienced immigration consultant in Surat. We provide Immigration Services for many countries such as Italy, Canada, France, Australia, Germany, USA, Malaysia, New Zealand, and Singapore.

    ReplyDelete
  26. Dr. Vivek Galani is a leading expert in skin and hair. At hair transplant clinic in Surat Skin Care, Cosmetic Laser, Hair Transplant & Slimming Center, Dr. Galani offers the most advanced cosmetic and dermatologic care treatments. The clinic uses advanced FUE methods to produce high-quality hair transplants.

    ReplyDelete
  27. I read this article. I think You put a lot of effort to create this article. I appreciate your work. Usmle Step 1 2020

    ReplyDelete
  28. Shreeja Health Care is leading manufacturer of oil Maker Machine For Home. Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed et

    ReplyDelete
  29. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    devops online training
    best devops online training
    top devops online training

    ReplyDelete
  30. Nice. I am really impressed with your writing talents and also with the layout on your weblog. Appreciate, Is this a paid subject matter or did you customize it yourself? Either way keep up the nice quality writing, it is rare to peer a nice weblog like this one nowadays. Thank you, check also event management and planning quotes

    ReplyDelete

  31. Thanks for the interesting content. I like your post and your blog is amazing.
    If you are interested in Video Downloader apps you can check my blog site. It is new and really informative.

    VidMate Download 2018

    ReplyDelete
  32. Shreeja Health Care is leading manufacturer of Oil Maker Machine. Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed etc.

    ReplyDelete
  33. I got very good information in this post, thank you very much from my side, keep giving this kind of information.
    1.Hindi studio

    ReplyDelete
  34. Managed Network Services gives you access to a wider pool of experts to help manage your growing business network needs. It provides proactive support to ensure issues are fixed in a timely manner and offers improved IT security to help protect your customers and employees. It also simplifies your cost management, resulting in a more productive and cost-effective business.

    ReplyDelete
  35. This site helps to clear your all query.
    This is really worth reading. nice informative article.
    dbrau ba 3rd year result
    bu ba final year result

    ReplyDelete
  36. It is very useful blog. Thanks for sharing. Keep updating new posts on your blog!!
    Who needs help in Digital Marketing for your Business? You can also visit my website. I hope to help you
    Digital Marketing Course AchieversIT

    ReplyDelete
  37. We are very thankful for share this informative post. Buy real leather jackets, Motogp Leather Suits & Motogp Leather Jackets with worldwide free shipping.
    Motogp Leather Suits
    Motogp Leather Jacket
    Sheepskin Jackets
    Shearling Jacket

    ReplyDelete
  38. Thats great post !! I like ur every post they always give me some new knowledge.

    VidMate | VidMate for PC |
    VidMate 2014

    ReplyDelete
  39. Thank you so much for sharing all this amazing information, keep it up.
    are you want to make a career in UI Development. check this UI Development Course in Bangalore.
    Attend The Best Front-end Certification Training In India From AchieversIT. Practical Front-end Training Sessions With Assured Placement Support From Experienced Faculty. and also proving live projects
    AchieversIT Training Institution

    ReplyDelete
  40. Thank you for your blog , it was usefull and informative "AchieversIT is the best Training institute for angular training. angular training in bangalore "

    ReplyDelete
  41. Thank you so much for sharing all this amazing information, keep it up.
    are you want to make a career in UI Development. check this UI Development Course in Bangalore.
    Attend The Best Front-end Certification Training In India From AchieversIT. Practical Front-end Training Sessions With Assured Placement Support From Experienced Faculty. and also proving live projects
    AchieversIT Training Institution

    ReplyDelete
  42. Through www.amazon.com/mytv - how you can connect your mobile phone to Amazon Prime. Through amazon.com/mytv, you can watch your favorite TV shows, series movies. You can watch prime videos anywhere on your device. Users need to create an Amazon account if they don’t have an Amazon account and enter the Amazon my TV activation code to watch Amazon prime videos on your device.

    amazon.com/mytv | www.amazon.com/mytv

    ReplyDelete
  43. I am looking for this informative post thanks for share it with me

    ReplyDelete
  44. I am looking for this informative post thanks for share it with me

    ReplyDelete
  45. I am looking for this informative post thanks for share it with me

    ReplyDelete
  46. I am looking for this informative post thanks for share it with me

    ReplyDelete
  47. The last thing that I would like to mention is the permanent license capability. Since KMSPico installs the KMS server on our machine it keeps checking for the new key and replace it with the older one. However, you should connect with your device at least once in 180 days. Other than this you will lose your activation so better use the product key instead of this.
    Windows 10 Activator Free Download
    WINDOWS ACTIVATOR
    Windows 10 Activator 2021
    Windows 10 Activator

    ReplyDelete
  48. B3 Bomber Jacket For Sale - Free Shipping and Best Deal
    Men consistently partial to skins and hides due to the fact the start of timethey utilized it to insure by themselves and safeguard them by your cold temperatures.
    Now shearling coats, Real Leather Bomber Jackets, Buy Harley Davidson Leather Motorcycle Jackets holds probably the best legacy , masculinity along with ruggedness to get a guys outer wear.

    ReplyDelete

Popular Posts