yanom blog

様々な技術について書きます

dockerでJavaの動作確認

仕事でJavaを使うことになったので、dockerで環境構築していきます。

手順は以下です。

  1. docker イメージをpullする
  2. 簡単な動作確認
  3. 簡単なプログラムを作成し、動作確認

dockerイメージをpullする

今回はopenjdkを使用します。
Oracle版は以下を参考にしたらいいと思います。
DockerでOracle Javaを実行する

$ docker pull openjdk
Using default tag: latest
latest: Pulling from library/openjdk
cd8eada9c7bb: Pull complete
c2677faec825: Pull complete
fcce419a96b1: Pull complete
045b51e26e75: Pull complete
88e50f3a5916: Pull complete
9db1045008ba: Pull complete
5ba72089e00c: Pull complete
810bdb5dd91f: Pull complete
62b563475556: Pull complete
Digest: sha256:e01aa552356f6f78a4bf2dd3576874c3e7b58c64cce0cc5bf1d538911d2dc86e
Status: Downloaded newer image for openjdk:latest

はい、イメージがpullできました。

簡単の動作確認

$ docker run -it openjdk java -version
openjdk version "11.0.1" 2018-10-16
OpenJDK Runtime Environment (build 11.0.1+13-Debian-2bpo91)
OpenJDK 64-Bit Server VM (build 11.0.1+13-Debian-2bpo91, mixed mode, sharing)

はい、動いてますね。

簡単なプログラムを作成し、動作確認

最後にhelloworldして行きます。

以下のような感じでまず、helloworld.javaを作ります。

public class helloworld{
    public static void main(String[] args){
      System.out.println("Hello World!!");
    }
 }

次に、Dockerfileも作成します。

FROM openjdk
WORKDIR /work
ADD helloworld.java /work
RUN javac helloworld.java
CMD java helloworld

最後に実行していきます。

$ docker build . -t testjava
Sending build context to Docker daemon  3.072kB
Step 1/5 : FROM openjdk
 ---> 9bbe44eb5d03
Step 2/5 : WORKDIR /work
 ---> Using cache
 ---> dd25ae1656e6
Step 3/5 : ADD helloworld.java /work
 ---> Using cache
 ---> b16bb8ee9d41
Step 4/5 : RUN javac helloworld.java
 ---> Using cache
 ---> cfca5849962a
Step 5/5 : CMD java helloworld
 ---> Using cache
 ---> cae968bba59e
Successfully built cae968bba59e
Successfully tagged testjava:latest
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
$ docker run -t testjava
Hello World!!

はい、動いてますね。

まとめ

dockerのopenjdkでJavaの動作確認をしました。
あっという間にJavaが動かせて便利な世の中になりました。