Run a Java application in a Docker container
You can use Docker to run a Java application in a container together with a specific runtime environment. This tutorial describes how to create a Dockerfile for running a simple Java application in a container with OpenJDK 8.
The sample application consists of a single Main.java file, which prints
Hello World! to the console and exits. Compilation output is located in the project directory under /out/production/DockerJavaApp.
Run the Java application in a container
In the Project tool window, right-click the project name, point to New and click File.
In the New File dialog, type Dockerfile and click OK.
Type the following in the new Dockerfile:FROM openjdk:8 COPY ./out/production/DockerJavaApp/ /tmp WORKDIR /tmp ENTRYPOINT ["java","Main"]
- Click the Run on Docker gutter icon () and then click Run on 'Docker'.
IntelliJ IDEA creates a Docker run configuration, which builds an image from the Dockerfile and then runs a container based on that image. The contents of the output directory Main.class are copied into the /tmp directory in the container. Then it runs the
java Maincommand from inside the /tmp directory. As a result, you should see
Hello World!printed to the container log.
Share your Java application as a Docker image
In the Docker tool window, find the image that was built from the Dockerfile. By default, it is designated by a unique image ID, because no image tag was provided. You can edit the corresponding run configuration and specify an image tag of your choice. To find out the image ID, select the container that you ran from the Dockerfile and open the Properties tab.
Right-click the image with the required ID and then click Push Image in the context menu.
In the Push Image dialog, select your registry, specify the repository name and tag for the image, and click OK.
Once the image is pushed to the registry, anyone with access to it can pull it and run a container from the image.