Saturday, September 22, 2018

Deployment of Spring boot to a virtual machine

Prerequisites

  1. We will deploy spring boot to a virtual machine (CentOS7 with Vagrant/Virtualbox).
  2. We will deploy this project.
  3. If you don't know how to use Virtualbox/Vagrant, see here.

Change pom.xml

At you need to make a fat .war/.jar file from your project. To do so, make sure the following is added in the pom.xml:
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
Then make sure jar or war is written here:
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.blogspot.noteoneverything</groupId>
    <artifactId>chatboard</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging> <!-- !! Check here!! This is the place to write war/jar file !! -->

    <name>chatboard</name>
    <description>Demo project for Spring Boot</description>
This example specifies jar file.

Create .war or .jar file

Go to the top directory of the project on console. If the directory is here:

The command is this:
$ cd ~/Documents/java/vs-chatboard
$ mvn clean package 
This command will create war/jar file in target folder.

Deployment

Now start the vagrant and connect to the virtual machine with ssh.
Then, inside the virtual machine (supposing it is CentOS7), install open-jdk in your virtual machine:
$ sudo yum install -y java-1.8.0-openjdk
and open the port 8080:
$ sudo iptables -I INPUT 1 -i eth0 -p tcp --dport 8080 -j ACCEPT
See also: https://serverfault.com/questions/626521/centos-7-save-iptables-settings

Also you need mariadb-server in the virtual machine. (It can be mysql too, but we will use mariadb for this time.)
$ sudo yum install -y mariadb-server

And run:
$ sudo systemctl start mariadb

Enable it:
$ sudo systemctl enable mariadb

Login to your mariadb and run this command to create a database.
Create database your_db_name;
use your_db_name;
The DB name must be same as the local DB's name.
Create a table too.
Drop table if exists cat;
Create table cat( 
   id int not null auto_increment, 
   name varchar(100) not null, 
   rescued date not null, 
   vaccinated tinyint(1) not null, 
   primary key (id) 
);
Then insert records.
insert into cat(name, rescued, vaccinated)values('nyan','2018-10-01','1');
insert into cat(name, rescued, vaccinated)values('joe','2018-1-5','1');
insert into cat(name, rescued, vaccinated)values('leo','2017-3-21','0');

Then copy and paste the created war/jar file to the shared folder:

In the virtual machine, run the project with java:
$ java -jar chatboard-0.0.1-SNAPSHOT.jar
Or if you use the war file:
$ java -jar chatboard-0.0.1-SNAPSHOT.war

Check from browser

Check it from your browser. The URL is http://{your virtual machine's IP}:8080
So mine is: http://192.168.33.10:8080
The result: