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>

129 comments:

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

    Custom Software Development Sydney

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

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

    Best Core Java Training Institute

    ReplyDelete
  4. 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
  5. Replies
    1. thanks for sharing amazing information keep posting!
      Oreo TV

      Delete
  6. 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
  7. Ingin mendapatkan kemenangan mudah dan cepat pada permainan Ceme Online, segera mainkan dengan menggunakan Bobol Server Judi Ceme Online.
    Hoki Pasti
    Info Jitu

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

    ReplyDelete
  9. 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
  10. 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
  11. 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
  12. If you are planning to buy an electric scooter, you can check out this top notch review on Mi M365 Electric Scooter

    ReplyDelete
  13. 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
  14. 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
  15. Hi there colleagues, good paragraph and good urging commented here, I am genuinely enjoying by these. Kumaun University BA Part 1 Result

    ReplyDelete
  16. 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
  17. 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
  18. 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
  19. 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
  20. Thats great post !! I like ur every post they always give me some new knowledge.

    VidMate | VidMate for PC |
    VidMate 2014

    ReplyDelete
  21. 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
  22. Iressa Gefitinib 250 mg tablet price in India
    is found to be the best with Emedkit. Emedkit is the exporter of all the generic medicine that also specializes in all the Cancer, HIV’s medicines at the lowest price along with the free delivery at your doorstep in India and worldwide. Hence, if you are looking to buy Iressa 250 mg tablet then there is no better place than the Emedkit. Gefitinib 250 mg is used to treat people with non-small cell lung cancer (NSCLC) that has spread to other parts of the body.

    ReplyDelete
  23. Ledikast is combination of Ledipasvir and Sofosbuvir used for the treatment of hepatitis C Virus infection. Buy ledikast capsules

    ReplyDelete
  24. It was wonderfull reading your article. Great writing style lenvakast capsules

    ReplyDelete
  25. I am glad to be here and read your very interesting article, it was very informative and helpful information for me. keep it up. 49ers varsity jacket

    ReplyDelete
  26. Check customer reviews to see what other people have to say. There’s a good chance you’ll have a similar experience to everyone else, so the more opinions you read through the better an idea you’ll have of what to expect. Any company confident about the effectiveness of its products should offer you a guarantee. You might not always be able to claim an exchange or return, but everyone welcomes the chance to get a replacement or reimbursement if they are dissatisfied. However, it is also a key indicator of drug tests. Use a kit that accounts for this variable. Visit: https://www.urineworld.com/

    ReplyDelete
  27. Fantastic blog i have never ever read this type of amazing information. Purple Joker Jacket

    ReplyDelete
  28. Amazing write-up! Really Good.
    Now the foundation of any business is marketing. Adsify marketing is the best Digital marketing in Trivandrum.

    ReplyDelete
  29. Thanks for sharing. Your blog is really helpful for us. Keep sharing. First DigiAdd

    ReplyDelete
  30. Thanks for the blog but If your looking to switch your career to the Airline Industry we the Fusion is the best place to pursue. It is one of the best Cabin Crew Training Centre

    ReplyDelete
  31. Voot App Apk has a simple goal: make it easy for friends to watch videos together no matter where they are in the world.

    https://apkmodule.com/voot-app-apk/

    ReplyDelete
  32. Awesome article I really impress it’s very informative and useful.Thanks
    Social Media Discount Deals

    ReplyDelete


  33. Very informative post I really like it. Happy to hear about it more.raiders varsity jacket mens

    ReplyDelete
  34. Thank you so much for sharing this nice article.
    Introducing our Next Level Complete Laundry Management & Dry-Cleaning software. Connect with us to get accelerated and cost-effective Laundry Management Software.
    Visit Now: https://syswash.net/

    ReplyDelete
  35. The search engine determines whether or not the results of the query were accurate based on the users’ actions. If you add enough keywords in the description, title, tags, and transcript then your video will appear in more search results. The digital marketing agency London will tell you that comments, subscribers and likes on a YouTube video increase the relevancy of a post. You can get more hits through other users if your keywords are relevant.

    ReplyDelete
  36. Hey friend, it is very well written article, thank you for the valuable and useful information you provide in this post. Keep up the good work! FYI, Pet Care adda
    how to activate flipkart axis bank credit card, the millionaire next door
    ,The Price Of Flowers Summary

    ReplyDelete
  37. 3D Rendering China provides many services for a purpose like 3d Industrial modeling,3d Architectural Rendering, 3d Medical Illustration,3d Product modeling and 3d design, 3d Interior Visualisation, 3d Animation Video etc if you need design home, office and industry we make 3D design 100% unique and high quality professional creative idea and special concentrate for finishing, We 3D architectural renders supportive and trusted services.


    3d rendering china
    3d architectural rendering china
    3d interior designs china
    3d product rendering china

    ReplyDelete
  38. I always spent my half an hour to read this webpage’s content every day along with a cup of coffee.

    B Sc part 1st time table

    ReplyDelete
  39. Arshine Feed Biotech Co.,LTD. (Arshine Feed) is the wholly owned subsidiary of Arshine Group. Our products cover a wide range of feed additives, such as Amino acids, Vitamins, Probiotics, Enzymes, Antiseptic, Antioxidant, Acidifier, Neutraceuticals and Coloring Agents etc. The company is committed to improving the nutritional intake for Broilers, Layers, Swines, Ruminants as well as fish-prawn-crab through scientific breeding programs and formulations.
    source:https://www.arshinefeed.com/

    ReplyDelete
  40. https://apkworlds.com/photoroom/
    PhotoRoom will delight creative and creative owners of android devices.

    ReplyDelete
  41. You there, that is totally wonderful declare here. gratitude for taking the term to call such snappish data. outstanding substance material generally gets the site guests coming. Download Whatsapp Plus Cracked

    ReplyDelete
  42. I needed to gratitude for this outstanding legitimate to apply!! I truly adored all little piece of it. I have you bookmarked your site to try out the presented effects you articulate.. Grammarly Premium Mod APK For Pc

    ReplyDelete
  43. this is a particularly charming helpful asset which you are offering and you find the money for it away for reasonable. I truly like seeing website that arrangement the charge of providing an energies valuable asset for excuse. Good Morning Wishes For Him

    ReplyDelete
  44. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. top 10 micronutrients company in india

    ReplyDelete
  45. Heroku is an amazing infrastructure when it comes to deployment. When you are to hire a dedicated developer, you should ask them if they are familiar with the infrastructure.

    ReplyDelete
  46. It's absolutely correct, it makes life so much easier specially when you are building a large scale commodity fintech company.

    ReplyDelete
  47. This is brilliant as its the correct industry standard, specially in travel and luxury villa booking spaces.

    ReplyDelete
  48. ارزان ترین بلیط هواپیما داخلی و خارجی برای مسافرت شما.

    ReplyDelete
  49. Thank you for a great article, this is very useful when you are chartering a vessel.

    ReplyDelete
  50. Its correct, the tool is fantastic and its one of the criterias we look for when we are to provide private equity funding to startup projects.

    ReplyDelete
  51. Technology infrastructure is a must even in non-tech companies including london interior designers

    ReplyDelete
  52. This is being heavily used by the commodity suppliers, as it speeds up the deployment of new projects.

    ReplyDelete
  53. Thank you this is very informative specially for us as a young commodity fintech company.

    ReplyDelete
  54. Even though we don't use the same language but for deployment in a luxury hotel management company, we use this.

    ReplyDelete
  55. Thanks for sharing such an amazing information with us. Get Philippines Import Export Trade Data by Philippineseximp. Visit our website for more information about philippines import export.
    Philippines Export Data

    ReplyDelete
  56. Hello my family member! I wish to say that this post is amazing, nice written and come with approximately all important info's. I’d like to peer more posts like this.
    du ba 2nd year result | du ba 3rd year result.

    ReplyDelete
  57. Your post is really amazing with lots of important points Thank you for sharing. I was really enjoying reading this article.
    Java training in Hyderabad

    ReplyDelete
  58. AVEVA System Platform supplier & solutions provider of AVEVA System Platform, quick technical support in India & globally.

    ReplyDelete
  59. Improve your sense of style by purchasing one of our magnificent Leather Jackets, which are currently 20% off on our store. Grab your favourite leather jacket right now so you don't miss out on this amazing deal.

    ReplyDelete
  60. Nice blog Abhi. Must appreciate your effort. Detailed discussion indeed.

    We also provide professional software courses.
    IT Training Institute Kolkata

    ReplyDelete
  61. This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting.our sclinbio.com

    ReplyDelete
  62. This comment has been removed by the author.

    ReplyDelete
  63. Master the language of innovation with our Java Training in Chennai at Infycle Technologies. Our industry-focused course equips you with the skills to develop robust software applications and opens doors to a world of job opportunities. Learn from experienced tutors, work on real-time projects, and embark on a journey to become a Java expert. Enrol today and start your coding career with confidence! For details, call us at +91-750263363 or +91-7504633633.

    ReplyDelete
  64. I love reading your fashion blogs because they are engaging and terrific. Christmas Collection

    ReplyDelete
  65. The most beguiling sound I have ever heard in that framework is your voice. The most flawless spot I have ever been to is in your arms. thnx for shareing our https/-sclinbio.com

    ReplyDelete
  66. Get expert Azure job support for seamless cloud operations. Resolve issues, optimize performance, and ensure project success with our dedicated assistance
    azure job support




    ReplyDelete
  67. Thank you so much for sharing such an amazing information. Visit Instasource for Video Wall Display Suppliers in India, Active LED Display Distributor & Supplier in India, and Split Air Conditioners Suppliers in India at an affordable price.
    Video Wall Display Suppliers in India

    ReplyDelete
  68. Thank you so much for taking the time to share the article with me. Your willingness to pass along this valuable piece of information means a lot to me. I truly appreciate your thoughtfulness and generosity in sharing knowledge. epfindia

    ReplyDelete
  69. Amazing blog, thanks for sharing with us. Visit Amfez for Thakur ji ke Vastra, Laddu Gopal Shringar, Radha Krishna Dress, and God dress online at affordable price.
    God Dress Online

    ReplyDelete
  70. Buying instant YouTube subscribers can be a game-changer for content creators aiming to enhance their channel's prominence and authority swiftly. This strategy allows for quick improvement in your channel's statistics, making it more attractive to potential viewers and sponsors alike. A diverse range of budget-friendly packages ensures that this tool is accessible to creators at any stage of their career, from beginners to more established YouTubers. The process is designed for user ease, being both secure and straightforward, so creators can remain focused on what they do best: creating captivating content. Furthermore, an increase in subscribers can lead to a domino effect, attracting more organic viewers and subscribers due to the enhanced perception of channel popularity. This method lays a solid foundation for building a vibrant community around your content, leading to sustained growth and engagement. It's a strategic step towards establishing a significant presence on YouTube, ensuring your content reaches and resonates with a broader audience.
    https://www.buyyoutubesubscribers.in/

    ReplyDelete

Popular Posts