LoginSignup
0
1

More than 5 years have passed since last update.

Dockerコンテナ上で素のJavaを使ってHello Worldしてみる

Posted at

Hello Worldを出力するJavaクラスを作成

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

作成後、javac Main.javaでコンパイルをしMain.classファイルを作成しておく。

Javaを実行可能なimageをセットアップ

次にubuntuをベースにjavaを実行するためのimageを作る。

Dockerfile
FROM ubuntu:latest
COPY Main.class Main.class
RUN apt-get update && apt-get install -y default-jre && apt-get install -y default-jdk
RUN java Main

1行目で使用する大元のimage(今回はubuntu)を指定。

2行目で実行用のクラスファイルをimageのディレクトリにコピーしておく。

3行目でJDKをインストール、javaコマンドを実行可能にする。

最後に4行目でMainクラスを実行し、Hello worldを出力させる。

Dockerfileを作成できたら下記コマンドでimageをビルドする、ついでにタグオプションを使って名前をつけておく。
(最後の.を忘れない様に)

docker-build
docker build -t running-java .

Java実行 on Docker!

Output
Step 4/4 : RUN java Main
 ---> Running in aab904e1114c
Hello Docker!
0
1
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
0
1