2022年8月15日月曜日

Automatically set timezone when you use Dockerfile

 In the other day , I tried to build a docker image using following Dockerfile.

But I was prevented from a cause I didn't know.


Dockerfile I used
FROM ubuntu:latest

RUN apt-get update \ 
&& apt-get install -y clang clang-12 \ 
&& apt-get install -y neovim git wget curl imagemagick wireshark tshark unzip gdb net-tools

I show a measure for it.

 

What I did


I modified the Dockerfiles as follows , then I was successful in building a docker images.
 
More precisely, I added the line startting from 'ENV' , installing tzdata before installing some package.
 
Modified Dockerfile  
FROM ubuntu:latest

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update \ 
&& apt-get install -y tzdata \
&& apt-get install -y clang clang-12 \ 
&& apt-get install -y neovim git wget curl imagemagick wireshark tshark unzip gdb net-tools

2022年8月12日金曜日

Several errors I encountered when I constructed Spring boot with Docker

 I show several errors I encountered when I constructed Spring boot with Docker and its cause.


You'd better read this article refering my previous article How to run SpringBoot as docker container

Build Error

Unable to find a single main class from the following candidates [hello.Application, hello.Application2] -> [Help 1]


Quotation of part of error message
[INFO] --- spring-boot-maven-plugin:2.7.1:repackage (repackage) @ spring-boot-docker-complete ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  15.785 s
[INFO] Finished at: 2022-08-12T10:06:59Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.7.1:repackage (repackage) on project spring-boot-docker-complete: Execution repackage of goal org.springframework.boot:spring-boot-maven-plugin:2.7.1:repackage failed: Unable to find a single main class from the following candidates [hello.Application, hello.Application2] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
As above error message says that "Unable to find a single main class from the following candidates [hello.Application, hello.Application2] " , this cause is that there two main method in a SpringBoot project.


More precisely,

Application.java
@SpringBootApplication
@RestController
public class Application {

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

        public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
        }
Application2.java
 @SpringBootApplication
@RestController
public class Application2 {

        @RequestMapping("/test")
        public String home() {
                return "Hello Docker World";
        }

        public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
        }

}

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile (default-compile) on project spring-boot-docker-complete: Compilation failure: Compilation failure: [ERROR] /srv/gs-spring-boot-docker/complete/src/main/java/hello/TestDB.java:[10,37] package org.springframework.jdbc.core does not exist

Quotation of part of error message
 [INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) @ spring-boot-docker-complete ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /srv/gs-spring-boot-docker/complete/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /srv/gs-spring-boot-docker/complete/src/main/java/hello/TestDB.java:[10,37] package org.springframework.jdbc.core does not exist
[ERROR] /srv/gs-spring-boot-docker/complete/src/main/java/hello/TestDB.java:[22,9] cannot find symbol
  symbol:   class JdbcTemplate
  location: class hello.TestDB
[INFO] 2 errors 
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  7.272 s
[INFO] Finished at: 2022-08-12T11:03:58Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile (default-compile) on project spring-boot-docker-complete: Compilation failure: Compilation failure: 
[ERROR] /srv/gs-spring-boot-docker/complete/src/main/java/hello/TestDB.java:[10,37] package org.springframework.jdbc.core does not exist
[ERROR] /srv/gs-spring-boot-docker/complete/src/main/java/hello/TestDB.java:[22,9] cannot find symbol
[ERROR]   symbol:   class JdbcTemplate
[ERROR]   location: class hello.TestDB
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

As above error message says that "package org.springframework.jdbc.core does not exist" or "cannot find symbol symbol: class JdbcTemplate location: class hello.TestDB", this cause is that although TestDB tries to use JDBC API , JDBC library doesn't exist in the SpringBoot project. More precisely, pom.xml is as follows.
 ### we can not fine description about JDBC !!
### Omit
        <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>

                <dependency>
                       <groupId>mysql</groupId>
                       <artifactId>mysql-connector-java</artifactId>
                       <scope>runtime</scope>
                </dependency>


        </dependencies>
        
### Omit        

Runtime Error

Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'application2' method

Quotation of part of error message
 2022-08-12 11:25:46.849  INFO 870 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-08-12 11:25:46.913  INFO 870 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-08-12 11:25:46.917  INFO 870 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.64]
2022-08-12 11:25:47.210  INFO 870 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-08-12 11:25:47.211  INFO 870 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 6225 ms
2022-08-12 11:25:48.584  WARN 870 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'application2' method 
hello.Application2#home()
to { [/]}: There is already 'application' bean method
hello.Application#home() mapped.
2022-08-12 11:25:48.601  INFO 870 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-08-12 11:25:48.658  INFO 870 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-08-12 11:25:48.767 ERROR 870 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'application2' method 
hello.Application2#home()
to { [/]}: There is already 'application' bean method
hello.Application#home() mapped.
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.21.jar!/:5.3.21]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.21.jar!/:5.3.21]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.21.jar!/:5.3.21]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.21.jar!/:5.3.21]


This cause when there are two same Request mapping , in Application.java and in Application2.java.

More precisely,
Application.java
 @SpringBootApplication
@RestController
public class Application {

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

        public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
        }

}
Application2.java
 @SpringBootApplication
@RestController
public class Application2 {

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


}

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

Quotation of part of error message
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
	at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:448) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.29.jar!/:8.0.29]
	at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
	at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
	at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
 
 /////
 
 Caused by: java.net.UnknownHostException: any: Name or service not known
	at java.base/java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) ~[na:na]
	at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929) ~[na:na]
	at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1529) ~[na:na]
	at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848) ~[na:na]
	at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1519) ~[na:na]
The message in above Error ,"The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server." , enable us to guesss that the destination we suppose to send is wrong.
Practically , checking the application.yml , the host name of database server is wrong. application.yml
server:
  port: 8080

#TODO: figure out why I need this here and in bootstrap.yml
spring:
  application:
    name: testLatticeApp

  datasource:
    url: jdbc:mysql://any:3306/sample?useLegacyDatetimeCode=false&serverTimezone=Asia/Tokyo   #"any" is wrong. According to docker-compose.yml , it should be db.
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver


ribbon:
  ServerListRefreshInterval: 1000

endpoints:
  health:
    sensitive: false
  restart:
    enabled: true
  shutdown:
    enabled: true

How to run SpringBoot as docker container

As I struggled to construct the Spring Boot environment with docker ,and successed in it, I write the procedure I tried.

Write a Dockerfile and docker-compose.yml

At first , we prepare a Dockerfile and a docker-compose.yml as follows. 

docker-compose_sample_git.yml
version: "3"
services:
  db:
    image: mysql:8
    container_name: "spring_db_git"
    ports:
      - "3306:3306"
    volumes:
      - ./mysql/sql/:/docker-entrypoint-initdb.d
      - ./mysql/settings/:/var/lib/mysql
      - ./mysql/sql/mysql.cnf:/etc/mysql/conf.d/my.cnf
    environment:
      MYSQL_DATABASE: "sample" # database named "sample" is created
      MYSQL_ROOT_USER: "root" 
      MYSQL_ROOT_PASSWORD: "root"
      TZ: "Asia/Tokyo"


# SpringBootApplication
  spring:
    container_name: "spring_compose_git"
    build:
      context: .
      dockerfile: Dockerfile
    restart: always
    ports:
      - "8080:8080"
    tty: true
    depends_on:
      - db
    volumes:
      - ./spring_git:/srv:cached
    working_dir: /srv
Dockerfile
FROM openjdk:11
RUN apt-get update && apt-get -y upgrade \
 && apt-get install -y vim less wget git unzip \
 && wget https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip \
 && unzip apache-maven-3.8.6-bin.zip 
Then we execute next command in the directory where docker-compose_sample_git.yml and Dockerfile exits.
$docker-compose -f docker-compose_sample_git.yml  up  --build -d

Setting environment more

And then , we login spring_compose_git container and set environmetnt using some more command.
$ docker exec -it spring_compose_git /bin/bash     # get in container
root@01720fff8d82:/srv#       #internal container

Cloning the repository of SpringBoot

# git clone https://github.com/spring-guides/gs-spring-boot-docker.git
# cd / 

Installing maven refering this page 

# wget https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip
# unzip apache-maven-3.8.6-bin.zip

Editing PATH Variable

# export PATH=$PATH:/apache-maven-3.8.6/bin 
# cd /srv/gs-spring-boot-docker/complete

Maven build , skipping test Directory

# ./mvnw package -Dmaven.test.skip 
If you can confirm the message "build success" , you can go next step.

Editting application.yml

Next , we edit application.yml as follows.
# pwd
/srv/gs-spring-boot-docker/complete/src/main/resources
# ls
application.yml
application.yml
server:
  port: 8080

#TODO: figure out why I need this here and in bootstrap.yml
spring:
  application:
    name: testLatticeApp

  datasource:
    url: jdbc:mysql://db:3306/sample?useLegacyDatetimeCode=false&serverTimezone=Asia/Tokyo
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver


ribbon:
  ServerListRefreshInterval: 1000

endpoints:
  health:
    sensitive: false
  restart:
    enabled: true
  shutdown:
    enabled: true


Edittting pom.xml

# pwd
/srv/gs-spring-boot-docker/complete
# ls
Dockerfile  build.gradle  gradle  gradlew  gradlew.bat	mvnw  mvnw.cmd	pom.xml  src  target
pom.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelversion>4.0.0</modelversion>
        <parent>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-starter-parent</artifactid>
                <version>2.7.1</version>
                <relativepath> <!--lookup parent from repository-->
        </relativepath></parent>
        <groupid>com.example</groupid>
        <artifactid>spring-boot-docker-complete</artifactid>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-boot-docker-complete</name>
        <description>Demo project for Spring Boot</description>
        <properties>
                <java .version="">1.8</java>
        </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>

                <dependency>
                       <groupid>mysql</groupid>
                       <artifactid>mysql-connector-java</artifactid>
                       <scope>runtime</scope>
                </dependency>

                <dependency>
                       <groupid>org.springframework.boot</groupid>
                       <artifactid>spring-boot-starter-data-jdbc</artifactid>
                 </dependency>

        </dependencies>
        <build>
                <plugins>
                        <plugin>
                                <groupid>org.springframework.boot</groupid>
                                <artifactid>spring-boot-maven-plugin</artifactid>
                        </plugin>
                </plugins>
        </build>
</project>


Create a Controller

Furthermore we create new file , TestDB.java , as follows.
# pwd
/srv/gs-spring-boot-docker/complete/src/main/java/hello
# ls
Application.java  TestDB.java
TestDB.java
package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
public class TestDB {

        @Autowired
        JdbcTemplate jdbcTemplate;


        @RequestMapping("/db")
        public String testDB() {
                return jdbcTemplate.queryForList("SELECT * FROM sample").toString();
        }



}

Build again

Finally , let's build project again
# pwd
/srv/gs-spring-boot-docker/complete
# ./mvnw package -Dmaven.test.skip 

Insert some data into mysql

Before booting SpringBoot Project , we insert somedata into mysql (spring_db_git container).

we create sample table in sample database ,and insert some data with next command 
 
mysql> create table sample(ID int(10));
Query OK, 0 rows affected, 1 warning (0.09 sec)

mysql> insert sample value(10);
Query OK, 1 row affected (0.04 sec)

mysql> select * from sample;
+------+
| ID   |
+------+
|   10 |
+------+
1 row in set (0.00 sec)

Boot SpringProject and Access

If we succusess in building the Spring Project , let's boot the project.
### check the target directory and which to exectute .jar file.
#java -jar target/spring-boot-docker-complete-0.0.1-SNAPSHOT.jar  
And then , we try to access URL http://localhost:8080/db from browser in host.

If we are in successful in setting the environment, we must see the following message.



[{ID=10}]