In this article, we will see how we can run our Spring Boot application as a service on Ubuntu.

Create a new Spring Boot starter project. Modify its pom.xml file to look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   ...
   <packaging>jar</packaging>

   <parent>
     ...
   </parent>

   <dependencies>
      ...
   </dependencies>

   <build>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>1.8</source>
               <target>1.8</target>
            </configuration>
         </plugin>

         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
         </plugin>
     </plugins>
  </build>
</project>

To generate the jar file, we can use Spring Tool Suite or use maven to generate the jar.

Start terminal and move to the project directory. Execute following command to create project executable jar file:

mvn clean install

The jar file will be generated in the target directory under project.
Next, we need to upload the generated jar to our Ubuntu server. We will create following directory structure for our application on Ubuntu server:

/home/ubuntu/workspace

You can replace /ubuntu with your /username

After SSH/logging into Ubuntu, follow these steps:

  1. cd /home/ubuntu
  2. mkdir workspace
  3. On local computer, use scp command to transfer the generated jar file
    scp -i path_to_pem_file target/jar_file_name ubuntu@ip_address_of_ubuntu_server:/home/ubuntu/workspace

    You should get your .pem file when you created your Ubuntu server

  4. On Ubuntu server, from the workspace directory:
    Make the jar file executable

    chmod 500 jar_file_name
  5. Create symbolic link to our jar file to run it easily
    sudo ln -s /home/ubuntu/workspace/jar_file_name /etc/init.d/any_application_name
  6. Now you can run your Spring Boot application like this:
    /etc/init.d/any_application_name start
    /etc/init.d/any_application_name restart
    /etc/init.d/any_application_name stop

That’s it, your application should be running now.