2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Maven/Tomcat/MySQL] Ubuntu 18.04でwebappをビルド&デプロイする

Last updated at Posted at 2019-01-20

いわゆるLAMP的な環境を構築し、自前のJavaEEアプリをビルド&デプロイする、という特に真新しくもなんともないけどせっかく試したのでその手順を残してみた。

主な対象読者は、「Eclipse上でサーバサイドJavaの簡単なアプリを作れるようになってEclipseからの実行で内部でTomcat起動して動きを確認くらいはできるけど、そのソースをLinuxでビルドしたり、Linuxサーバ上で動作させるにはどうするんだろう」という方で、初心者向けの内容。

ここではWindows10上のVirtualBoxにUbuntu 18.04のVMを作り、そのVM上でビルドもデプロイも行う、という構成。
ビルド・APサーバ(Tomcat)・DBサーバ(MySQL)をすべて同じVM上で行っているが、もちろん分けても構わない。

Ubuntuのセットアップ

VirtualBoxで適当に…ホストOSのスペック次第でメモリは増やしてもよい。

image.png

インストールに使うイメージはUbuntu 18.04.1 LTS (Bionic Beaver)64-bit PC (AMD64) server install imageを使用。

また、起動(OSインストール)の前に、ホストOSと通信するためにNICの追加を行う

image.png

VMを起動してOSインストール

image.png

ネットワーク設定

image.png

DHCP設定のenp0s3でDNS設定する構成であれば、こっちは空欄で進める。
Default G/Wについても、インターネットに出ていくenp0s3が(DHCPで)設定されるのであれば、ホストと直接通信するenp0s8は空欄。

image.png

ミラーサーバ

image.png

この設定でインストールし、ホストOSからVMへのSSHがつながり、ログイン後にVM上でaptがちゃんと動けばOK。

でもタイムゾーンの設定、やっぱりないよなー
デフォルトではGMTになっていて9時間ずれているので、タイムゾーンをAsia/Tokyoに設定しておく。

ソースの取得とアプリビルド

ちなみにEclipse環境でビルドしてwarファイルを作成する場合は、メニューからエクスポートするのが簡単
Windows上のEclipseで作成したwarファイルをLinuxにコピーしても(基本的には)動く。

git clone

GitHubにv1.0.0として上げているので、git clone -b v1.0.0で取得。

zaki@etivaz:~/src$ git clone -b v1.0.0 https://github.com/zaki-lknr/javaee-memoapp2.git
Cloning into 'javaee-memoapp2'...
remote: Enumerating objects: 384, done.
remote: Counting objects: 100% (384/384), done.
remote: Compressing objects: 100% (158/158), done.
remote: Total 384 (delta 144), reused 355 (delta 115), pack-reused 0
Receiving objects: 100% (384/384), 39.46 KiB | 1.72 MiB/s, done.
Resolving deltas: 100% (144/144), done.
Note: checking out '3656f7114c526027c96c0a585b6a5152ce43947c'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

zaki@etivaz:~/src$ ls
javaee-memoapp2

ちなみに、DBサーバのアドレスはlocalhostになっているので、アプリケーションサーバ(今回はTomcat)とは別のホストでDBを動かす場合はsrc/main/webapp/META-INF/context.xmlurlの部分のlocalhostをDBサーバのアドレスに変更する。

src/main/webapp/META-INF/context.xml
 <Resource
  name="jdbc/memoapp_db"
  auth="Container"
  type="javax.sql.DataSource"
  maxTotal="100"
  maxIdle="30"
  maxWaitMillis="10000"
  username="memoapp"
  password="memoapp"
  driverClassName="com.mysql.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/memoapp_db" />

Mavenインストール

まずMavenのインストール

の前に、aptlineの編集。
(デフォルトではmavenパッケージのあるuniverseリポジトリは設定されていない)

/etc/apt/sources.list
deb http://ftp.jaist.ac.jp/pub/Linux/ubuntu bionic main universe restricted multiverse
deb http://ftp.jaist.ac.jp/pub/Linux/ubuntu bionic-security main universe restricted multiverse
deb http://ftp.jaist.ac.jp/pub/Linux/ubuntu bionic-updates main universe restricted multiverse

これでapt updateしてapt install mavenする。

root@etivaz:~# apt install maven
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  ca-certificates-java default-jre-headless fontconfig-config
  fonts-dejavu-core java-common libaopalliance-java libapache-pom-java
  libatinject-jsr330-api-java libavahi-client3 libavahi-common-data
  libavahi-common3 libcdi-api-java libcommons-cli-java libcommons-io-java
  libcommons-lang3-java libcommons-parent-java libcups2 libfontconfig1
  libgeronimo-annotation-1.3-spec-java libgeronimo-interceptor-3.0-spec-java
  libguava-java libguice-java libhawtjni-runtime-java libjansi-java
  libjansi-native-java libjpeg-turbo8 libjpeg8 libjsr305-java liblcms2-2
  libmaven-parent-java libmaven-resolver-java libmaven-shared-utils-java
  libmaven3-core-java libnspr4 libnss3 libpcsclite1 libplexus-cipher-java
  libplexus-classworlds-java libplexus-component-annotations-java
  libplexus-interpolation-java libplexus-sec-dispatcher-java
  libplexus-utils2-java libsisu-inject-java libsisu-plexus-java libslf4j-java
  libwagon-file-java libwagon-http-shaded-java libwagon-provider-api-java
  libxi6 libxrender1 libxtst6 openjdk-11-jre-headless x11-common
Suggested packages:
  default-jre libaopalliance-java-doc libatinject-jsr330-api-java-doc
  libservlet3.1-java libcommons-io-java-doc libcommons-lang3-java-doc
  cups-common libasm-java libcglib-java libjsr305-java-doc liblcms2-utils
  libmaven-shared-utils-java-doc liblogback-java pcscd
  libplexus-cipher-java-doc libplexus-classworlds-java-doc
  libplexus-interpolation-java-doc libplexus-sec-dispatcher-java-doc
  libplexus-utils2-java-doc junit4 testng libcommons-logging-java
  liblog4j1.2-java libnss-mdns fonts-dejavu-extra fonts-ipafont-gothic
  fonts-ipafont-mincho fonts-wqy-microhei | fonts-wqy-zenhei fonts-indic
The following NEW packages will be installed:
  ca-certificates-java default-jre-headless fontconfig-config
  fonts-dejavu-core java-common libaopalliance-java libapache-pom-java
  libatinject-jsr330-api-java libavahi-client3 libavahi-common-data
  libavahi-common3 libcdi-api-java libcommons-cli-java libcommons-io-java
  libcommons-lang3-java libcommons-parent-java libcups2 libfontconfig1
  libgeronimo-annotation-1.3-spec-java libgeronimo-interceptor-3.0-spec-java
  libguava-java libguice-java libhawtjni-runtime-java libjansi-java
  libjansi-native-java libjpeg-turbo8 libjpeg8 libjsr305-java liblcms2-2
  libmaven-parent-java libmaven-resolver-java libmaven-shared-utils-java
  libmaven3-core-java libnspr4 libnss3 libpcsclite1 libplexus-cipher-java
  libplexus-classworlds-java libplexus-component-annotations-java
  libplexus-interpolation-java libplexus-sec-dispatcher-java
  libplexus-utils2-java libsisu-inject-java libsisu-plexus-java libslf4j-java
  libwagon-file-java libwagon-http-shaded-java libwagon-provider-api-java
  libxi6 libxrender1 libxtst6 maven openjdk-11-jre-headless x11-common
0 upgraded, 54 newly installed, 0 to remove and 0 not upgraded.
Need to get 51.5 MB of archives.
After this operation, 206 MB of additional disk space will be used.
Do you want to continue? [Y/n] 
:
:

done.
done.
root@etivaz:~# 
root@etivaz:~# logout
zaki@etivaz:~/src$ which mvn
/usr/bin/mvn

Mavenビルド

ビルドしてwarファイルを作成するには、pom.xmlのあるディレクトリでmvn packageを実行する。

zaki@etivaz:~/src$ cd javaee-memoapp2/
zaki@etivaz:~/src/javaee-memoapp2$ ls
LICENSE.txt  pom.xml  README.md  src
zaki@etivaz:~/src/javaee-memoapp2$ mvn package
:
:
[INFO] Packaging webapp
[INFO] Assembling webapp [memoapp2] in [/home/zaki/src/javaee-memoapp2/target/memoapp2]
[INFO] Processing war project
[INFO] Copying webapp resources [/home/zaki/src/javaee-memoapp2/src/main/webapp][INFO] Webapp assembled in [87 msecs]
[INFO] Building war: /home/zaki/src/javaee-memoapp2/target/memoapp2.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:01 min
[INFO] Finished at: 2019-01-18T15:21:56Z
[INFO] Final Memory: 19M/46M
[INFO] ------------------------------------------------------------------------
zaki@etivaz:~/src/javaee-memoapp2$ 

すると、targetディレクトリができ、配下にwarファイルが生成される。

zaki@etivaz:~/src/javaee-memoapp2$ ls
LICENSE.txt  pom.xml  README.md  src  target
zaki@etivaz:~/src/javaee-memoapp2$ ls target/
classes            maven-archiver  memoapp2
generated-sources  maven-status    memoapp2.war
zaki@etivaz:~/src/javaee-memoapp2$ ll -h target/memoapp2.war 
-rw-rw-r-- 1 zaki zaki 3.8M Jan 18 15:21 target/memoapp2.war
zaki@etivaz:~/src/javaee-memoapp2$ 

MySQLの設定

インストール

aptで。

root@etivaz:~# apt install mysql-server
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libaio1 libcgi-fast-perl libcgi-pm-perl libencode-locale-perl
  libevent-core-2.1-6 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl
  libhtml-template-perl libhttp-date-perl libhttp-message-perl libio-html-perl
  liblwp-mediatypes-perl libtimedate-perl liburi-perl mysql-client-5.7
  mysql-client-core-5.7 mysql-common mysql-server-5.7 mysql-server-core-5.7
Suggested packages:
  libdata-dump-perl libipc-sharedcache-perl libwww-perl mailx tinyca
The following NEW packages will be installed:
  libaio1 libcgi-fast-perl libcgi-pm-perl libencode-locale-perl
  libevent-core-2.1-6 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl
  libhtml-template-perl libhttp-date-perl libhttp-message-perl libio-html-perl
  liblwp-mediatypes-perl libtimedate-perl liburi-perl mysql-client-5.7
  mysql-client-core-5.7 mysql-common mysql-server mysql-server-5.7
  mysql-server-core-5.7
0 upgraded, 21 newly installed, 0 to remove and 0 not upgraded.
Need to get 21.0 MB of archives.
After this operation, 162 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

[snip]

Setting up mysql-client-5.7 (5.7.24-0ubuntu0.18.04.1) ...
Setting up mysql-server-5.7 (5.7.24-0ubuntu0.18.04.1) ...
update-alternatives: using /etc/mysql/mysql.cnf to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Renaming removed key_buffer and myisam-recover options (if present)
Created symlink /etc/systemd/system/multi-user.target.wants/mysql.service → /lib/systemd/system/mysql.service.
Setting up mysql-server (5.7.24-0ubuntu0.18.04.1) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Processing triggers for systemd (237-3ubuntu10.11) ...
Processing triggers for ureadahead (0.100.0-20) ...

clientも入るしそのまま起動する。
あれ?パスワードとかどうなってるんだろう?

ログイン

rootユーザであればパスなしで入れる

root@etivaz:~# mysql -u root 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> 

文字コードの設定

Ubuntu 18.04のMySQLのデフォルト文字コードは日本語になっていない

mysql> show variables like '%char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

mysql> 

ので、デフォルトの文字コードをutf8に設定する。

Ubuntu18.04のMySQLの設定ファイルは/etc/mysql/my.cnfにあるが、これはリンクになっていて実体は/etc/mysql/mysql.cnfになっている。
また、ファイルの中をみると/etc/mysql/conf.d//etc/mysql/mysql.conf.d/にあるファイルをincludeするような内容になっているので、/etc/mysql/mysql.conf.d/charset.cnfを作成する

/etc/mysql/mysql.conf.d/charset.cnf
[mysqld]
character-set-server=utf8

これでsystemctl restart mysqlすれば

mysql> show variables like '%char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)

mysql> 

character_set_serverのデフォルト文字コードがutf8になる。
(character_set_databaselatin1になっているが、これから新規作成するDBはutf8になるっぽい)

アプリ用DBとユーザの作成

ここと一緒だけど再掲

mysql> create database memoapp_db;
Query OK, 1 row affected (0.00 sec)

mysql> create user memoapp identified by "memoapp";
Query OK, 0 rows affected (0.00 sec)

mysql> grant all on memoapp_db.* to memoapp;
Query OK, 0 rows affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| memoapp_db         |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> 

これでmemoapp_dbができた。

memoappで入ると

zaki@etivaz:~$ mysql -u memoapp -p -D memoapp_db
Enter password:  ("memoapp"と入力)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| memoapp_db         |
+--------------------+
2 rows in set (0.00 sec)

mysql> show create database memoapp_db;
+------------+---------------------------------------------------------------------+
| Database   | Create Database                                                     |
+------------+---------------------------------------------------------------------+
| memoapp_db | CREATE DATABASE `memoapp_db` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+------------+---------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

ちゃんと入れる。
これでDBサーバの準備はOK

Tomcatの設定

インストール

これもapt

root@etivaz:~# apt install tomcat
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package tomcat
root@etivaz:~# apt install tomcat8
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  authbind libapr1 libcommons-collections3-java libcommons-dbcp-java
  libcommons-pool-java libecj-java libtcnative-1 libtomcat8-java
  tomcat8-common
Suggested packages:
  libcommons-collections3-java-doc libcommons-dbcp-java-doc
  libgeronimo-jta-1.1-spec-java ant ecj tomcat8-admin tomcat8-docs
  tomcat8-examples tomcat8-user
The following NEW packages will be installed:
  authbind libapr1 libcommons-collections3-java libcommons-dbcp-java
  libcommons-pool-java libecj-java libtcnative-1 libtomcat8-java tomcat8
  tomcat8-common
0 upgraded, 10 newly installed, 0 to remove and 0 not upgraded.
Need to get 7,791 kB of archives.
After this operation, 10.1 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

[snip]

Creating config file /etc/default/tomcat8 with new version
Adding system user `tomcat8' (UID 112) ...
Adding new user `tomcat8' (UID 112) with group `tomcat8' ...
Not creating home directory `/var/lib/tomcat8'.

Creating config file /etc/logrotate.d/tomcat8 with new version
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Processing triggers for systemd (237-3ubuntu10.11) ...
Processing triggers for ureadahead (0.100.0-20) ...
root@etivaz:~# 

これでインストール・起動まで完了。
デフォルトでは8080/tcpでLISTENしている

root@etivaz:~# ps aux | grep tomcat
tomcat8   3825  3.4  5.7 2676088 116668 ?      Sl   01:24   0:08 /usr/lib/jvm/default-java/bin/java -Djava.util.logging.config.file=/var/lib/tomcat8/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.awt.headless=true -XX:+UseConcMarkSweepGC -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/share/tomcat8/bin/bootstrap.jar:/usr/share/tomcat8/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat8 -Dcatalina.home=/usr/share/tomcat8 -Djava.io.tmpdir=/tmp/tomcat8-tomcat8-tmp org.apache.catalina.startup.Bootstrap start
root@etivaz:~# ss -anp
Netid State   Recv-Q  Send-Q                               Local Address:Port           Peer Address:Port   
tcp   LISTEN  0       100                                              *:8080                      *:*      users:(("java",pid=3825,fd=39))  

webappのデプロイ

ビルドしたwarファイルを(Ubuntu18.04のTomcat8の場合は)/var/lib/tomcat8/webappsへ配置する。

root@etivaz:~# ll /var/lib/tomcat8/
total 20
drwxr-xr-x  5 root    root    4096 Jan 20 01:24 ./
drwxr-xr-x 39 root    root    4096 Jan 20 01:24 ../
lrwxrwxrwx  1 root    root      12 Aug 13 20:23 conf -> /etc/tomcat8/
drwxr-xr-x  2 tomcat8 tomcat8 4096 Aug 13 20:23 lib/
lrwxrwxrwx  1 root    root      17 Aug 13 20:23 logs -> ../../log/tomcat8/
drwxr-xr-x  2 root    root    4096 Jan 20 01:24 policy/
drwxrwxr-x  3 tomcat8 tomcat8 4096 Jan 20 01:24 webapps/
lrwxrwxrwx  1 root    root      19 Aug 13 20:23 work -> ../../cache/tomcat8/
root@etivaz:~# ls /var/lib/tomcat8/webapps/
ROOT
root@etivaz:~# 
root@etivaz:~# mv ~zaki/src/javaee-memoapp2/target/memoapp2.war /var/lib/tomcat
8/webapps/
root@etivaz:~# ls /var/lib/tomcat8/webapps/
memoapp2  memoapp2.war  ROOT
root@etivaz:~# 

するとTomcatがwarを展開してアプリを起動してくれる。
デプロイを含めてログは/var/log/tomcat8/catalina.outに出力される。

20-Jan-2019 01:31:00.494 INFO [localhost-startStop-2] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/var/lib/tomcat8/webapps/memoapp2.war] has finished in [2,051] ms

起動したらブラウザからアクセスする。

image.png

適当にテキスト入力

image.png

DBにもレコードがちゃんと保存されている

mysql> select * from memo_data;
+---------+----------+--------+--------------------------------------------------------+---------------------+---------------------+
| memo_id | category | title  | memo                                                   | create_date         | modified_date       |
+---------+----------+--------+--------------------------------------------------------+---------------------+---------------------+
|       1 |        0 | test   | test message                                           | 2019-01-20 07:07:04 | 2019-01-20 07:07:04 |
|       2 |        0 | メモ   | カレーは粉でできてるのでカロリーゼロ                   | 2019-01-20 07:07:17 | 2019-01-20 07:07:17 |
+---------+----------+--------+--------------------------------------------------------+---------------------+---------------------+
2 rows in set (0.00 sec)

文字コード設定せずにlatin1のままだと…

Windowsで構築した環境と異なり、デフォルトだと日本語入力をしようとすると

image.png

日本語で入力した部分が????となってしまう。

image.png

というのも、DBに文字列がちゃんと保存されていないため。

mysql> show tables;
+----------------------+
| Tables_in_memoapp_db |
+----------------------+
| memo_data            |
+----------------------+
1 row in set (0.00 sec)

mysql> select * from memo_data;
+---------+----------+-------+--------------+---------------------+---------------------+
| memo_id | category | title | memo         | create_date         | modified_date       |
+---------+----------+-------+--------------+---------------------+---------------------+
|       1 |        0 | test  | test message | 2019-01-20 01:36:57 | 2019-01-20 01:36:57 |
|       2 |        0 | ???   | ?????        | 2019-01-20 01:38:14 | 2019-01-20 01:38:14 |
+---------+----------+-------+--------------+---------------------+---------------------+
2 rows in set (0.00 sec)

mysql> 
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?