IntelliJ IDEA 2018.1 Help

Run a Java application in a 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.

docker java app

To run your Java application in a container:

  1. In the Project tool window, right-click the project name, point to New and click File.
  2. In the New File dialog, type Dockerfile and click OK.
  3. Type the following in the new Dockerfile:

    FROM openjdk:8 COPY ./out/production/DockerJavaApp/ /tmp WORKDIR /tmp ENTRYPOINT ["java","Main"]
  4. Click the Run on Docker gutter icon (The Run button) 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 Main command from inside the /tmp directory. As a result, you should see Hello World! printed to the container log.

You can share the image with others, for example, to demonstrate exactly how your application is expected to run, without the need to install the necessary runtime (only Docker is required).

To share your Java application as a Docker image:

  1. 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.
  2. Right-click the image with the required ID and then click Push Image in the context menu.
  3. 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.

Last modified: 26 June 2018