August 23, 2020

#Create, test and run a Java project with Gradle using Docker and no IDE

In order to create and manage Java projects, its common to employ the help of an IDE like IntelliJ IDEA or Eclipse.

However, if you would rather use only the command line, Docker can be a great help.

For convenience and reproducibility, create a Dockerfile in your local filesystem with the following contents.

FROM openjdk:14

ENV GRADLE_HOME=/opt/gradle/gradle-6.4.1

RUN yum install -y wget unzip

RUN wget https://services.gradle.org/distributions/gradle-6.4.1-bin.zip -P /tmp &&\
    unzip -d /opt/gradle /tmp/gradle-*.zip &&\
    rm -rf /tmp/*

Build the Docker image and run a container (takes a while). Again, for convenience, -v and -w are used so that file creations and modifications made inside the container are reflected outside.

docker run --rm -it -v ${PWD}:/app -w /app $(docker build -q .) bash

Now, we can use gradle to create and manage a project from the command line.

# Create a new project
# The "application" template most likely will suit your needs
gradle init

# Run unit tests (if you enabled JUnit during project creation)
gradle test

# Run your code
gradle run

Write source code in src/main/java/<your_package> and test code in src/test/java/<your_package>.

Further reading

Official Gradle guide for Java applications

Docker command line

Gradle command line

List of JUnit Assertions