Packaging and deploying applications

duration 25 minutes

Prerequisites:

Learn how to update and deploy an application on Open Liberty with Maven and Docker.

What you’ll learn

You will learn how to run and update a simple REST microservice on an Open Liberty server. You will use Maven throughout the guide to build and deploy the microservice as well as to interact with the running server instance.

Open Liberty is an application server designed for the cloud. It’s small, lightweight, and designed with modern cloud-native application development in mind. It supports the full MicroProfile and Java EE APIs and is composable, meaning that you can use only the features that you need, keeping the server lightweight, which is great for microservices. It also deploys to every major cloud platform, including Docker, Kubernetes, and Cloud Foundry.

Maven is an automation build tool that provides an efficient way to develop Java applications. Using Maven, you will build a simple microservice, called system, that collects basic system properties from your laptop and displays them on an endpoint that you can access in your web browser.

You’ll also explore how to package your application with the server runtime so that it can be deployed anywhere in one go. You will then make server configuration and code changes and see how they are picked up by a running server.

Finally, you will package the application along with the server configuration into a Docker image and run that image as a container.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-getting-started.git
cd guide-getting-started

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Building and running the application

Your application is configured to be built with Maven. Every Maven-configured project contains a pom.xml file, which defines the project configuration, dependencies, plug-ins, and so on.

Navigate to the start directory where your pom.xml file is located. Your pom.xml file is configured to include the liberty-maven-plugin, which allows you to install applications into Open Liberty and manage the server instances.

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0"
  3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5    <modelVersion>4.0.0</modelVersion>
  6
  7    <groupId>io.openliberty.guides</groupId>
  8    <artifactId>guide-getting-started</artifactId>
  9    <version>1.0-SNAPSHOT</version>
 10    <packaging>war</packaging>
 11
 12    <properties>
 13        <maven.compiler.source>1.8</maven.compiler.source>
 14        <maven.compiler.target>1.8</maven.compiler.target>
 15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 16        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 17        <failOnMissingWebXml>false</failOnMissingWebXml>
 18        <!-- Plugin versions -->
 19        <version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
 20        <version.maven-war-plugin>3.2.3</version.maven-war-plugin>
 21        <version.maven-surefire-plugin>2.22.2</version.maven-surefire-plugin>
 22        <version.maven-failsafe-plugin>2.22.2</version.maven-failsafe-plugin>
 23        <!-- Liberty configuration -->
 24        <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 25        <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 26    </properties>
 27
 28    <dependencies>
 29        <!-- Provided dependencies -->
 30        <dependency>
 31            <groupId>jakarta.platform</groupId>
 32            <artifactId>jakarta.jakartaee-web-api</artifactId>
 33            <version>8.0.0</version>
 34            <scope>provided</scope>
 35        </dependency>
 36        <dependency>
 37            <groupId>org.eclipse.microprofile</groupId>
 38            <artifactId>microprofile</artifactId>
 39            <version>3.0</version>
 40            <type>pom</type>
 41            <scope>provided</scope>
 42        </dependency>
 43        <!-- For tests -->
 44        <dependency>
 45            <groupId>org.junit.jupiter</groupId>
 46            <artifactId>junit-jupiter-engine</artifactId>
 47            <version>5.5.2</version>
 48            <scope>test</scope>
 49        </dependency>
 50        <dependency>
 51            <groupId>org.apache.cxf</groupId>
 52            <artifactId>cxf-rt-rs-client</artifactId>
 53            <version>3.3.4</version>
 54            <scope>test</scope>
 55        </dependency>
 56        <dependency>
 57            <groupId>org.apache.cxf</groupId>
 58            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 59            <version>3.3.4</version>
 60            <scope>test</scope>
 61        </dependency>
 62        <dependency>
 63            <groupId>org.glassfish</groupId>
 64            <artifactId>javax.json</artifactId>
 65            <version>1.1.4</version>
 66            <scope>test</scope>
 67        </dependency>
 68        <!-- Support for JDK 9 and above -->
 69        <dependency>
 70            <groupId>javax.xml.bind</groupId>
 71            <artifactId>jaxb-api</artifactId>
 72            <version>2.3.1</version>
 73            <scope>test</scope>
 74        </dependency>
 75    </dependencies>
 76
 77    <build>
 78        <finalName>${project.artifactId}</finalName>
 79        <plugins>
 80            <!-- Enable liberty-maven plugin -->
 81            <!-- tag::libertyMavenPlugin[] -->
 82            <plugin>
 83                <groupId>io.openliberty.tools</groupId>
 84                <artifactId>liberty-maven-plugin</artifactId>
 85                <version>${version.liberty-maven-plugin}</version>
 86            </plugin>
 87            <!-- end::libertyMavenPlugin[] -->
 88            <plugin>
 89                <groupId>org.apache.maven.plugins</groupId>
 90                <artifactId>maven-war-plugin</artifactId>
 91                <version>${version.maven-war-plugin}</version>
 92            </plugin>
 93            <plugin>
 94                <groupId>org.apache.maven.plugins</groupId>
 95                <artifactId>maven-surefire-plugin</artifactId>
 96                <version>${version.maven-surefire-plugin}</version>
 97            </plugin>
 98            <!-- Plugin to run functional tests -->
 99            <plugin>
100                <groupId>org.apache.maven.plugins</groupId>
101                <artifactId>maven-failsafe-plugin</artifactId>
102                <version>${version.maven-failsafe-plugin}</version>
103                <configuration>
104                    <systemPropertyVariables>
105                        <http.port>${liberty.var.default.http.port}</http.port>
106                    </systemPropertyVariables>
107                </configuration>
108            </plugin>
109        </plugins>
110    </build>
111</project>

To begin, build the system microservice that is provided and deploy it to Open Liberty by running the Maven liberty:run goal from the start directory:

mvn liberty:run

The mvn command initiates a Maven build, during which the target directory is created to store all build-related files.

The liberty:run argument specifies the Open Liberty run goal, which starts an Open Liberty server instance in the foreground. As part of this phase, an Open Liberty server runtime is downloaded and installed into the target/liberty/wlp directory, a server instance is created and configured in the target/liberty/wlp/usr/servers/defaultServer directory, and the application is installed into that server via loose config.

For more information about the Liberty Maven plug-in, see its GitHub repository.

When the server begins starting up, various messages display in your active shell. Wait for the following message, which indicates that the server startup is complete:

[INFO] [AUDIT] CWWKF0011I: The server defaultServer is ready to run a smarter planet.

To access the system microservice, see the http://localhost:9080/system/properties URL, and you see a list of the various system properties of your JVM:

{
    "os.name": "Mac OS X",
    "java.version": "1.8.0_151",
    ...
}

When you need to stop the server, press CTRL+C in the shell session where you ran the server, or run the liberty:stop goal from the start directory in another shell session:

mvn liberty:stop

Starting and stopping the Open Liberty server in the background

Although you can start and stop the server in the foreground by using the Maven liberty:run goal, you can also start and stop the server in the background with the Maven liberty:start and liberty:stop goals:

mvn liberty:start
mvn liberty:stop

Updating the server configuration without restarting the server

The Open Liberty Maven plug-in includes a dev goal that listens for any changes in the project, including application source code or configuration. The Open Liberty server automatically reloads the configuration without restarting. This goal allows for quicker turnarounds and an improved developer experience.

Stop the Open Liberty server if it is running, and start it in development mode by running the liberty:dev goal in the start directory:

mvn liberty:dev

Development mode automatically picks up changes that you make to your application and allows you to run tests by pressing the enter/return key in the active shell. When you’re working on your application, rather than rerunning Maven commands, press the enter/return key to verify your change.

As before, you can see that the application is running by going to the http://localhost:9080/system/properties URL.

Now try updating the server configuration while the server is running in development mode. The system microservice does not currently include health monitoring to report whether the server and the microservice that it runs are healthy. You can add health reports with the MicroProfile Health feature, which adds a /health endpoint to your application. If you try to access this endpoint now at the http://localhost:9080/health/ URL, you see a 404 error because the /health endpoint does not yet exist:

Error 404: java.io.FileNotFoundException: SRVE0190E: File not found: /health

To add the MicroProfile Health feature to the server, include the mpHealth feature in the server.xml.

Replace the server configuration file.
src/main/liberty/config/server.xml

server.xml

 1<server description="Sample Liberty server">
 2    <!-- tag::features[] -->
 3    <featureManager>
 4        <feature>jaxrs-2.1</feature>
 5        <feature>jsonp-1.1</feature>
 6        <feature>cdi-2.0</feature>
 7        <feature>mpMetrics-2.0</feature>
 8        <!-- tag::mpHealth[] -->
 9        <feature>mpHealth-2.0</feature>
10        <!-- end::mpHealth[] -->
11        <feature>mpConfig-1.3</feature>
12    </featureManager>
13    <!-- end::features[] -->
14
15    <variable name="default.http.port" defaultValue="9080"/>
16    <variable name="default.https.port" defaultValue="9443"/>
17
18    <webApplication location="guide-getting-started.war" contextRoot="/" />
19    <mpMetrics authentication="false"/>
20
21    <!-- tag::logging[] -->
22    <logging traceSpecification="com.ibm.ws.microprofile.health.*=all" />
23    <!-- end::logging[] -->
24
25    <httpEndpoint host="*" httpPort="${default.http.port}"
26        httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
27
28    <variable name="io_openliberty_guides_system_inMaintenance" value="false"/>
29</server>

After you make the file changes, Open Liberty automatically reloads its configuration. When enabled, the mpHealth feature automatically adds a /health endpoint to the application. You can see the server being updated in the server log displayed in your shell session:

[INFO] [AUDIT] CWWKG0016I: Starting server configuration update.
[INFO] [AUDIT] CWWKT0017I: Web application removed (default_host): http://foo:9080/
[INFO] [AUDIT] CWWKZ0009I: The application io.openliberty.guides.getting-started has stopped successfully.
[INFO] [AUDIT] CWWKG0017I: The server configuration was successfully updated in 0.284 seconds.
[INFO] [AUDIT] CWWKT0016I: Web application available (default_host): http://foo:9080/health/
[INFO] [AUDIT] CWWKF0012I: The server installed the following features: [mpHealth-2.0].
[INFO] [AUDIT] CWWKF0008I: Feature update completed in 0.285 seconds.
[INFO] [AUDIT] CWWKT0016I: Web application available (default_host): http://foo:9080/
[INFO] [AUDIT] CWWKZ0003I: The application io.openliberty.guides.getting-started updated in 0.173 seconds.

Try to access the /health endpoint again by visiting the http://localhost:9080/health URL. You see the following JSON:

{
    "checks":[],
    "status":"UP"
}

Now you can verify whether your server is up and running.

Updating the source code without restarting the server

The JAX-RS application that contains your system microservice runs in a server from its .class file and other artifacts. Open Liberty automatically monitors these artifacts, and whenever they are updated, it updates the running server without the need for the server to be restarted.

Look at your pom.xml file.

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0"
  3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5    <modelVersion>4.0.0</modelVersion>
  6
  7    <groupId>io.openliberty.guides</groupId>
  8    <artifactId>guide-getting-started</artifactId>
  9    <version>1.0-SNAPSHOT</version>
 10    <packaging>war</packaging>
 11
 12    <properties>
 13        <maven.compiler.source>1.8</maven.compiler.source>
 14        <maven.compiler.target>1.8</maven.compiler.target>
 15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 16        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 17        <failOnMissingWebXml>false</failOnMissingWebXml>
 18        <!-- Plugin versions -->
 19        <version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
 20        <version.maven-war-plugin>3.2.3</version.maven-war-plugin>
 21        <version.maven-surefire-plugin>2.22.2</version.maven-surefire-plugin>
 22        <version.maven-failsafe-plugin>2.22.2</version.maven-failsafe-plugin>
 23        <!-- Liberty configuration -->
 24        <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 25        <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 26    </properties>
 27
 28    <dependencies>
 29        <!-- Provided dependencies -->
 30        <dependency>
 31            <groupId>jakarta.platform</groupId>
 32            <artifactId>jakarta.jakartaee-web-api</artifactId>
 33            <version>8.0.0</version>
 34            <scope>provided</scope>
 35        </dependency>
 36        <dependency>
 37            <groupId>org.eclipse.microprofile</groupId>
 38            <artifactId>microprofile</artifactId>
 39            <version>3.0</version>
 40            <type>pom</type>
 41            <scope>provided</scope>
 42        </dependency>
 43        <!-- For tests -->
 44        <dependency>
 45            <groupId>org.junit.jupiter</groupId>
 46            <artifactId>junit-jupiter-engine</artifactId>
 47            <version>5.5.2</version>
 48            <scope>test</scope>
 49        </dependency>
 50        <dependency>
 51            <groupId>org.apache.cxf</groupId>
 52            <artifactId>cxf-rt-rs-client</artifactId>
 53            <version>3.3.4</version>
 54            <scope>test</scope>
 55        </dependency>
 56        <dependency>
 57            <groupId>org.apache.cxf</groupId>
 58            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 59            <version>3.3.4</version>
 60            <scope>test</scope>
 61        </dependency>
 62        <dependency>
 63            <groupId>org.glassfish</groupId>
 64            <artifactId>javax.json</artifactId>
 65            <version>1.1.4</version>
 66            <scope>test</scope>
 67        </dependency>
 68        <!-- Support for JDK 9 and above -->
 69        <dependency>
 70            <groupId>javax.xml.bind</groupId>
 71            <artifactId>jaxb-api</artifactId>
 72            <version>2.3.1</version>
 73            <scope>test</scope>
 74        </dependency>
 75    </dependencies>
 76
 77    <build>
 78        <finalName>${project.artifactId}</finalName>
 79        <plugins>
 80            <!-- Enable liberty-maven plugin -->
 81            <plugin>
 82                <groupId>io.openliberty.tools</groupId>
 83                <artifactId>liberty-maven-plugin</artifactId>
 84                <version>${version.liberty-maven-plugin}</version>
 85            </plugin>
 86            <plugin>
 87                <groupId>org.apache.maven.plugins</groupId>
 88                <artifactId>maven-war-plugin</artifactId>
 89                <version>${version.maven-war-plugin}</version>
 90            </plugin>
 91            <plugin>
 92                <groupId>org.apache.maven.plugins</groupId>
 93                <artifactId>maven-surefire-plugin</artifactId>
 94                <version>${version.maven-surefire-plugin}</version>
 95            </plugin>
 96            <!-- Plugin to run functional tests -->
 97            <plugin>
 98                <groupId>org.apache.maven.plugins</groupId>
 99                <artifactId>maven-failsafe-plugin</artifactId>
100                <version>${version.maven-failsafe-plugin}</version>
101                <configuration>
102                    <systemPropertyVariables>
103                        <http.port>${liberty.var.default.http.port}</http.port>
104                    </systemPropertyVariables>
105                </configuration>
106            </plugin>
107        </plugins>
108    </build>
109</project>

Try updating the source code while the server is running in development mode. At the moment, the /health endpoint reports whether the server is running, but the endpoint doesn’t provide any details on the microservices that are running inside of the server.

MicroProfile Health offers health checks for both readiness and liveness. A readiness check allows third-party services, such as Kubernetes, to know if the microservice is ready to process requests. A liveness check allows third-party services to determine if the microservice is running.

Create the SystemReadinessCheck class.
src/main/java/io/openliberty/sample/system/SystemReadinessCheck.java

SystemReadinessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019  IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.sample.system;
14
15import javax.enterprise.context.ApplicationScoped;
16
17import javax.inject.Inject;
18import javax.inject.Provider;
19
20import org.eclipse.microprofile.config.inject.ConfigProperty;
21import org.eclipse.microprofile.health.Readiness;
22import org.eclipse.microprofile.health.HealthCheck;
23import org.eclipse.microprofile.health.HealthCheckResponse;
24import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
25
26@Readiness
27@ApplicationScoped
28// tag::systemReadinessCheck[]
29public class SystemReadinessCheck implements HealthCheck {
30
31    @Inject
32    @ConfigProperty(name = "io_openliberty_guides_system_inMaintenance")
33    Provider<String> inMaintenance;
34
35    @Override
36    public HealthCheckResponse call() {
37        HealthCheckResponseBuilder builder = HealthCheckResponse.named(
38                SystemResource.class.getSimpleName() + " readiness check");
39        if (inMaintenance != null && inMaintenance.get().equalsIgnoreCase("true")) {
40            return builder.withData("services", "not available").down().build();
41        }
42        return builder.withData("services", "available").up().build();
43    }
44
45}
46// end::systemReadinessCheck[]

The SystemReadinessCheck class verifies that the system microservice is not in maintenance by checking a config property.

Create the SystemLivenessCheck class.
src/main/java/io/openliberty/sample/system/SystemLivenessCheck.java

SystemLivenessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019  IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.sample.system;
14
15import javax.enterprise.context.ApplicationScoped;
16
17import java.lang.management.MemoryMXBean;
18import java.lang.management.ManagementFactory;
19
20import org.eclipse.microprofile.health.Liveness;
21import org.eclipse.microprofile.health.HealthCheck;
22import org.eclipse.microprofile.health.HealthCheckResponse;
23
24@Liveness
25@ApplicationScoped
26// tag::systemLivenessCheck[]
27public class SystemLivenessCheck implements HealthCheck {
28
29    @Override
30    public HealthCheckResponse call() {
31        MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
32        long memUsed = memBean.getHeapMemoryUsage().getUsed();
33        long memMax = memBean.getHeapMemoryUsage().getMax();
34
35        return HealthCheckResponse.named(
36            SystemResource.class.getSimpleName() + " liveness check")
37                                  .withData("memory used", memUsed)
38                                  .withData("memory max", memMax)
39                                  .state(memUsed < memMax * 0.9).build();
40    }
41
42}
43// end::systemLivenessCheck[]

The SystemLivenessCheck class reports a status of DOWN if the microservice uses over 90% of the maximum amount of memory.

After you make the file changes, Open Liberty automatically reloads its configuration and the system application.

The following messages display in your first shell session:

[INFO] [AUDIT] CWWKT0017I: Web application removed (default_host): http://foo:9080/
[INFO] [AUDIT] CWWKZ0009I: The application io.openliberty.guides.getting-started has stopped successfully.
[INFO] [AUDIT] CWWKT0016I: Web application available (default_host): http://foo:9080/
[INFO] [AUDIT] CWWKZ0003I: The application io.openliberty.guides.getting-started updated in 0.136 seconds.

Access the /health endpoint again by going to the http://localhost:9080/health URL. This time you see the overall status of your server and the aggregated data of the liveness and readiness checks for the system microservice:

{
   "checks":[
      {
         "data":{
            "services":"available"
         },
         "name":"SystemResource readiness check",
         "status":"UP"
      },
      {
         "data":{
            "memory used":81064480,
            "memory max":4294967296
         },
         "name":"SystemResource liveness check",
         "status":"UP"
      }
   ],
   "status":"UP"
}

You can also access the /health/ready endpoint by going to the http://localhost:9080/health/ready URL to view the data from the readiness health check. Similarly, access the /health/live endpoint by going to the http://localhost:9080/health/live URL to view the data from the liveness health check.

Making code changes and recompiling is fast and straightforward. The development mode of Open Liberty automatically picks up changes in the .class files and artifacts, without needing to be restarted. Alternatively, you can run the run goal and manually repackage or recompile the application by using the mvn package command or the mvn compile command while the server is running. The development mode was added to further improve the developer experience by minimizing turnaround times.

Checking the Open Liberty server logs

While the server is running in the foreground, it displays various console messages in the shell. These messages are also logged to the target/liberty/wlp/usr/servers/defaultServer/logs/console.log file. You can find the complete server logs in the target/liberty/wlp/usr/servers/defaultServer/logs directory. The console.log and messages.log files are the primary log files that contain console output of the running application and the server. More logs are created when runtime errors occur or whenever tracing is enabled. You can find the error logs in the ffdc directory and the tracing logs in the trace.log file.

In addition to the log files that are generated automatically, you can enable logging of specific Java packages or classes by using the <logging/> element:

<logging traceSpecification="<component_1>=<level>:<component_2>=<level>:..."/>

The component element is a Java package or class, and the level element is one of the following logging levels: off, fatal, severe, warning, audit, info, config, detail, fine, finer, finest, all.

Try enabling detailed logging of the MicroProfile Health feature by adding the <logging/> element to your configuration file.

Replace the server configuration file.
src/main/liberty/config/server.xml

server.xml

 1<server description="Sample Liberty server">
 2    <!-- tag::features[] -->
 3    <featureManager>
 4        <feature>jaxrs-2.1</feature>
 5        <feature>jsonp-1.1</feature>
 6        <feature>cdi-2.0</feature>
 7        <feature>mpMetrics-2.0</feature>
 8        <!-- tag::mpHealth[] -->
 9        <feature>mpHealth-2.0</feature>
10        <!-- end::mpHealth[] -->
11        <feature>mpConfig-1.3</feature>
12    </featureManager>
13    <!-- end::features[] -->
14
15    <variable name="default.http.port" defaultValue="9080"/>
16    <variable name="default.https.port" defaultValue="9443"/>
17
18    <webApplication location="guide-getting-started.war" contextRoot="/" />
19    <mpMetrics authentication="false"/>
20
21    <!-- tag::logging[] -->
22    <logging traceSpecification="com.ibm.ws.microprofile.health.*=all" />
23    <!-- end::logging[] -->
24
25    <httpEndpoint host="*" httpPort="${default.http.port}"
26        httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
27
28    <variable name="io_openliberty_guides_system_inMaintenance" value="false"/>
29</server>

After you change the file, Open Liberty automatically reloads its configuration.

Now, when you visit the /health endpoint, additional traces are logged in the trace.log file.

Afterward, stop the server by typing q in the shell session where you ran the server and then press the enter/return key.

Running the application in a Docker container

To run the application in a container, Docker needs to be installed. For installation instructions, see the Official Docker Docs.

To containerize the application, you need a Dockerfile. This file contains a collection of instructions that define how a Docker image is built, what files are packaged into it, what commands run when the image runs as a container, and other information. You can find a complete Dockerfile in the start directory. This Dockerfile copies the .war file into a Docker image that contains the Java runtime and a preconfigured Open Liberty server.

To build and containerize the application, start your Docker daemon and then run the following Docker build command in the start directory. Run the mvn package command from the start directory so that the .war file resides in the target directory.

mvn package
docker build -t openliberty-getting-started:1.0-SNAPSHOT .

The Docker openliberty-getting-started:1.0-SNAPSHOT image is also built from the Dockerfile. To verify that the image is built, run the docker images command to list all local Docker images:

docker images

Your image should appear in the list of all Docker images:

REPOSITORY                     TAG             IMAGE ID        CREATED         SIZE
openliberty-getting-started    1.0-SNAPSHOT    85085141269b    21 hours ago    487MB

Next, run the image as a container:

docker run -d --name gettingstarted-app -p 9080:9080 openliberty-getting-started:1.0-SNAPSHOT

There is a bit going on here, so here’s a breakdown of the command:

FlagDescription

-d

Runs the container in the background.

--name

Specifies a name for the container.

-p

Maps the container ports to the host ports.

The final argument in the docker run command is the Docker image name.

Next, run the docker ps command to verify that your container started:

docker ps

Make sure that your container is running and does not have Exited as its status:

CONTAINER ID    IMAGE                         CREATED          STATUS           NAMES
4294a6bdf41b    openliberty-getting-started   9 seconds ago    Up 11 seconds    gettingstarted-app

To access the application, go to the http://localhost:9080/system/properties URL.

To stop and remove the container, run the following commands:

docker stop gettingstarted-app && docker rm gettingstarted-app

To remove the image, run the following command:

docker rmi openliberty-getting-started:1.0-SNAPSHOT

Running the application from a minimal runnable JAR

So far, Open Liberty was running out of the target/liberty/wlp directory, which effectively contains an Open Liberty server installation and the deployed application. The final product of the Maven build is a server package for use in a continuous integration pipeline and, ultimately, a production deployment.

Open Liberty supports a number of different server packages. The sample application currently generates a usr package that contains the servers and application to be extracted onto an Open Liberty installation.

Instead of creating a server package, you can generate a runnable JAR file that contains the application along with a server runtime. This JAR file can then be run anywhere and deploy your application and server at the same time. To generate a runnable JAR file, override the include property:

mvn liberty:package -Dinclude=runnable

The packaging type is overridden from the usr package to the runnable package. This property then propagates to the liberty-maven-plugin plug-in, which generates the server package based on the openliberty-kernel package.

When the build completes, you can find the minimal runnable guide-getting-started.jar file in the target directory. This JAR file contains only the features that you explicitly enabled in your server.xml file. As a result, the generated JAR file is only about 50 MB.

To run the JAR file, first stop the server if it’s running. Then, navigate to the target directory and run the java -jar command:

java -jar guide-getting-started.jar

When the server starts, go to the http://localhost:9080/system/properties URL to access your application that is now running out of the minimal runnable JAR file.

You can stop the server by pressing CTRL+C in the shell session that the server runs in.

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0"
  3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5    <modelVersion>4.0.0</modelVersion>
  6
  7    <groupId>io.openliberty.guides</groupId>
  8    <artifactId>guide-getting-started</artifactId>
  9    <version>1.0-SNAPSHOT</version>
 10    <packaging>war</packaging>
 11
 12    <properties>
 13        <maven.compiler.source>1.8</maven.compiler.source>
 14        <maven.compiler.target>1.8</maven.compiler.target>
 15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 16        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 17        <failOnMissingWebXml>false</failOnMissingWebXml>
 18        <!-- Plugin versions -->
 19        <version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
 20        <version.maven-war-plugin>3.2.3</version.maven-war-plugin>
 21        <version.maven-surefire-plugin>2.22.2</version.maven-surefire-plugin>
 22        <version.maven-failsafe-plugin>2.22.2</version.maven-failsafe-plugin>
 23        <!-- Liberty configuration -->
 24        <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 25        <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 26    </properties>
 27
 28    <dependencies>
 29        <!-- Provided dependencies -->
 30        <dependency>
 31            <groupId>jakarta.platform</groupId>
 32            <artifactId>jakarta.jakartaee-web-api</artifactId>
 33            <version>8.0.0</version>
 34            <scope>provided</scope>
 35        </dependency>
 36        <dependency>
 37            <groupId>org.eclipse.microprofile</groupId>
 38            <artifactId>microprofile</artifactId>
 39            <version>3.0</version>
 40            <type>pom</type>
 41            <scope>provided</scope>
 42        </dependency>
 43        <!-- For tests -->
 44        <dependency>
 45            <groupId>org.junit.jupiter</groupId>
 46            <artifactId>junit-jupiter-engine</artifactId>
 47            <version>5.5.2</version>
 48            <scope>test</scope>
 49        </dependency>
 50        <dependency>
 51            <groupId>org.apache.cxf</groupId>
 52            <artifactId>cxf-rt-rs-client</artifactId>
 53            <version>3.3.4</version>
 54            <scope>test</scope>
 55        </dependency>
 56        <dependency>
 57            <groupId>org.apache.cxf</groupId>
 58            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 59            <version>3.3.4</version>
 60            <scope>test</scope>
 61        </dependency>
 62        <dependency>
 63            <groupId>org.glassfish</groupId>
 64            <artifactId>javax.json</artifactId>
 65            <version>1.1.4</version>
 66            <scope>test</scope>
 67        </dependency>
 68        <!-- Support for JDK 9 and above -->
 69        <dependency>
 70            <groupId>javax.xml.bind</groupId>
 71            <artifactId>jaxb-api</artifactId>
 72            <version>2.3.1</version>
 73            <scope>test</scope>
 74        </dependency>
 75    </dependencies>
 76
 77    <build>
 78        <finalName>${project.artifactId}</finalName>
 79        <plugins>
 80            <!-- Enable liberty-maven plugin -->
 81            <!-- tag::libertyMavenPlugin[] -->
 82            <plugin>
 83                <groupId>io.openliberty.tools</groupId>
 84                <artifactId>liberty-maven-plugin</artifactId>
 85                <version>${version.liberty-maven-plugin}</version>
 86            </plugin>
 87            <!-- end::libertyMavenPlugin[] -->
 88            <plugin>
 89                <groupId>org.apache.maven.plugins</groupId>
 90                <artifactId>maven-war-plugin</artifactId>
 91                <version>${version.maven-war-plugin}</version>
 92            </plugin>
 93            <plugin>
 94                <groupId>org.apache.maven.plugins</groupId>
 95                <artifactId>maven-surefire-plugin</artifactId>
 96                <version>${version.maven-surefire-plugin}</version>
 97            </plugin>
 98            <!-- Plugin to run functional tests -->
 99            <plugin>
100                <groupId>org.apache.maven.plugins</groupId>
101                <artifactId>maven-failsafe-plugin</artifactId>
102                <version>${version.maven-failsafe-plugin}</version>
103                <configuration>
104                    <systemPropertyVariables>
105                        <http.port>${liberty.var.default.http.port}</http.port>
106                    </systemPropertyVariables>
107                </configuration>
108            </plugin>
109        </plugins>
110    </build>
111</project>

server.xml

 1<server description="Sample Liberty server">
 2    <!-- tag::features[] -->
 3    <featureManager>
 4        <feature>jaxrs-2.1</feature>
 5        <feature>jsonp-1.1</feature>
 6        <feature>cdi-2.0</feature>
 7        <feature>mpMetrics-2.0</feature>
 8        <!-- tag::mpHealth[] -->
 9        <feature>mpHealth-2.0</feature>
10        <!-- end::mpHealth[] -->
11        <feature>mpConfig-1.3</feature>
12    </featureManager>
13    <!-- end::features[] -->
14
15    <variable name="default.http.port" defaultValue="9080"/>
16    <variable name="default.https.port" defaultValue="9443"/>
17
18    <webApplication location="guide-getting-started.war" contextRoot="/" />
19    <mpMetrics authentication="false"/>
20
21    <!-- tag::logging[] -->
22    <logging traceSpecification="com.ibm.ws.microprofile.health.*=all" />
23    <!-- end::logging[] -->
24
25    <httpEndpoint host="*" httpPort="${default.http.port}"
26        httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
27
28    <variable name="io_openliberty_guides_system_inMaintenance" value="false"/>
29</server>

Great work! You’re done!

You’ve learned the basics of deploying and updating an application on an Open Liberty server.

Guide Attribution

Packaging and deploying applications by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star