[Java] Docker × Java Build a development environment that is too simple

1 minute read

Build Java development environment with Docker

Overview

Build a simple environment where you just set up a Java container on Docker. I will show you how to master the program and output the proof Hello World! to the console (laugh)

Environment

  • macOS Catalina version 10.15.5
  • Docker version 19.03.8
  • docker-compose version 1.25.5

Constitution

The final configuration will be as follows.

├── docker
│  └── java
│  └── Dockerfile
├── docker-compose.yml
└── server
    └── src
        ├── Main.class
        └── Main.java

Procedure

1. Create docker-compose.yml

It has a simple structure with only one java container.

docker-compose.yml


version: '3.6'
services:
  java:
    build: ./docker/java
    ports:
      -8080:8080
    tty: true
    volumes:
      -./server/src:/usr/src:cached

2. Create Dockerfile

Dockerfile



FROM openjdk:11-slim

RUN apt-get update
WORKDIR /usr/src

3. Create test file

Create a test file called Main.java.

Main.java


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

4. Start Docker


// docker build
% docker-compose build

// start docker in the background
% docker-compose up -d

// Confirmation
% docker-compose ps
       Name Command State Ports
- ------------------------------------------------- -----------
java-spring_java_1 jshell Up 0.0.0.0:8080->8080/tcp

5. Compile and run

// inspection
% docker-compose exec java bash

// compile
[email protected]:/usr/src# javac Main.java

// run
[email protected]:/usr/src# java Main
Hello World!

Reference