Skip to content

Instantly share code, notes, and snippets.

@hamdifourati
Last active December 26, 2017 15:06
Show Gist options
  • Save hamdifourati/fdd41e7a9d33124b28496ec28a6be835 to your computer and use it in GitHub Desktop.
Save hamdifourati/fdd41e7a9d33124b28496ec28a6be835 to your computer and use it in GitHub Desktop.
create and run Java project with ZERO configuration using docker.

Create a sample java project inside a docker container


Create Java project using maven

docker run -it --rm -v $PWD:/app/ maven:3-jdk-8 su -c"cd /app && mvn archetype:generate -DgroupId=info.hamdifourati.helloworld -DartifactId=hello-world -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false"

Build and package ( jar ) the java application

docker run -it --rm -v $PWD/hello-world:/app/ maven:3-jdk-8 su -c "cd /app && mvn package"

Run the jar file

The second argument is used to specify the Main class to run

docker run -it --rm -v $PWD/hello-world:/app/ maven:3-jdk-8 su -c "cd /app && java -cp  target/*.jar info.hamdifourati.helloworld.App"

You can specify the Main class by editing the pom.xml file. Add inside the <project> tag

<build>
  <plugins>
    <plugin>
      <!-- Build an executable JAR -->
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.0.2</version>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>com.example.grpc.App</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

And then run

docker run -it --rm -v $PWD/hello-world:/app/ maven:3-jdk-8 su -c "cd /app && java -jar target/*.jar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment