Containerizing microservices

duration 20 minutes

Prerequisites:

Learn how to containerize and run your microservices with Open Liberty using Docker.

What you’ll learn

You can easily deploy your microservices in different environments in a lightweight and portable manner by using containers. From development to production and across your DevOps environments, you can deploy your microservices consistently and efficiently with containers. You can run a container from a container image. Each container image is a package of what you need to run your microservice or application, from the code to its dependencies and configuration.

You’ll learn how to build container images and run containers using Docker for your microservices. You’ll construct Dockerfile files, create Docker images by using the docker build command, and run the image as Docker containers by using docker run command.

The two microservices that you’ll be working with are called system and inventory. The system microservice returns the JVM system properties of the running container. The inventory microservice adds the properties from the system microservice to the inventory. This guide demonstrates how both microservices can run and communicate with each other in different Docker containers.

Additional prerequisites

Before you begin, Docker needs to be installed. For installation instructions, refer to the official Docker documentation. You will build and run the microservices in Docker containers.

Make sure to start your Docker daemon before you proceed.

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-containerize.git
cd guide-containerize

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

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

Packaging your microservices

Navigate to the start directory to begin.

You can find the starting Java project in the start directory. It is a multi-module Maven project that is made up of the system and inventory microservices. Each microservice lives in its own corresponding directory, system and inventory.

To try out the microservices by using Maven, run the following Maven goal to build the system microservice and run it inside Open Liberty:

mvn -pl system liberty:run

Open another command-line session and run the following Maven goal to build the inventory microservice and run it inside Open Liberty:

mvn -pl inventory liberty:run

To access the inventory service, which displays the current contents of the inventory, see http://localhost:9081/inventory/systems.

The system service shows the system properties of the running JVM and can be found at http://localhost:9080/system/properties.

The system properties of your localhost can be added to the inventory at http://localhost:9081/inventory/systems/localhost.

After you are finished checking out the microservices, stop the Open Liberty servers by pressing CTRL+C in the command-line sessions where you ran the servers. Alternatively, you can run the liberty:stop goal in another command-line session:

mvn -pl system liberty:stop
mvn -pl inventory liberty:stop

Run the Maven package goal to build the application .war files from the start directory so that the .war files reside in the system/target and inventory/target directories.

mvn package

To learn more about RESTful web services and how to build them, see Creating a RESTful web service for details about how to build the system service. The inventory service is built in a similar way.

Building your Docker images

A Docker image is a binary file. It is made up of multiple layers and is used to run code in a Docker container. Images are built from instructions in Dockerfiles to create a containerized version of the application.

A Dockerfile is a collection of instructions for building a Docker image that can then be run as a container. As each instruction is run in a Dockerfile, a new Docker layer is created. These layers, which are known as intermediate images, are created when a change is made to your Docker image.

Every Dockerfile begins with a parent or base image over which various commands are run. For example, you can start your image from scratch and run commands that download and install a Java runtime, or you can start from an image that already contains a Java installation.

Learn more about Docker on the official Docker page.

Creating your Dockerfiles

You will be creating two Docker images to run the inventory service and system service. The first step is to create Dockerfiles for both services.

Create the Dockerfile for the inventory service.
inventory/Dockerfile

inventory/Dockerfile

 1# tag::from[]
 2FROM openliberty/open-liberty:kernel-java8-openj9-ubi
 3# end::from[]
 4
 5ARG VERSION=1.0
 6ARG REVISION=SNAPSHOT
 7
 8# tag::label[]
 9LABEL \
10  org.opencontainers.image.authors="Your Name" \
11  org.opencontainers.image.vendor="Open Liberty" \
12  org.opencontainers.image.url="local" \
13  org.opencontainers.image.source="https://github.com/OpenLiberty/guide-containerize" \
14  org.opencontainers.image.version="$VERSION" \
15  org.opencontainers.image.revision="$REVISION" \
16  vendor="Open Liberty" \
17  name="inventory" \
18  version="$VERSION-$REVISION" \
19  summary="The inventory microservice from the Containerizing microservices guide" \
20  description="This image contains the inventory microservice running with the Open Liberty runtime."
21# end::label[]
22
23# tag::copy-config[]
24# tag::config-userID[]
25COPY --chown=1001:0 \
26# end::config-userID[]
27    # tag::inventory-config[]
28    src/main/liberty/config \
29    # end::inventory-config[]
30    # tag::config[]
31    /config/
32    # end::config[]
33# end::copy-config[]
34
35# tag::copy-war[]
36# tag::war-userID[]
37COPY --chown=1001:0 \
38# end::war-userID[]
39    # tag::inventory-war[]
40    target/inventory.war \
41    # end::inventory-war[]
42    # tag::config-apps[]
43    /config/apps
44    # end::config-apps[]
45# end::copy-war[]
46
47# tag::configure-sh[]
48RUN configure.sh
49# end::configure-sh[]

The FROM instruction initializes a new build stage, which indicates the parent image of the built image. If you don’t need a parent image, then you can use FROM scratch, which makes your image a base image.

In this case, you’re using the recommended production image, openliberty/open-liberty:kernel-java8-openj9-ubi, as your parent image. If you don’t want any additional runtime features for your kernel image, define the FROM instruction as FROM open-liberty:kernel. To use the default image that comes with the Open Liberty runtime, define the FROM instruction as FROM open-liberty. You can find all the official images at open-liberty Docker Hub.

It is also recommended to label your Docker images with the LABEL command, as the label information can help you manage your images. For more information, see Best practices for writing Dockerfiles.

The COPY instructions are structured as COPY [--chown=<user>:<group>] <source> <destination>. They copy local files into the specified destination within your Docker image. In this case, the inventory server configuration files that are located at src/main/liberty/config are copied to the /config/ destination directory. The inventory application WAR file inventory.war, which was created from running mvn package, is copied to the /config/apps destination directory.

The COPY instructions use the 1001 user ID and 0 group because the openliberty/open-liberty:kernel-java8-openj9-ubi image runs by default with the USER 1001 (non-root) user for security purposes. Otherwise, the files and directories that are copied over are owned by the root user.

Place the RUN configure.sh command at the end to get a pre-warmed Docker image. It improves the startup time of running your Docker container.

The Dockerfile for the system service follows the same instructions as the inventory service, except that some labels are updated, and the system.war archive is copied into /config/apps.

Create the Dockerfile for the system service.
system/Dockerfile

system/Dockerfile

 1FROM openliberty/open-liberty:kernel-java8-openj9-ubi
 2
 3ARG VERSION=1.0
 4ARG REVISION=SNAPSHOT
 5
 6LABEL \
 7  org.opencontainers.image.authors="Your Name" \
 8  org.opencontainers.image.vendor="Open Liberty" \
 9  org.opencontainers.image.url="local" \
10  org.opencontainers.image.source="https://github.com/OpenLiberty/guide-containerize" \
11  org.opencontainers.image.version="$VERSION" \
12  org.opencontainers.image.revision="$REVISION" \
13  vendor="Open Liberty" \
14# tag::name[]
15  name="system" \
16# end::name[]
17  version="$VERSION-$REVISION" \
18# tag::summary[]
19  summary="The system microservice from the Containerizing microservices guide" \
20  description="This image contains the system microservice running with the Open Liberty runtime."
21# end::summary[]
22
23COPY --chown=1001:0 src/main/liberty/config /config/
24
25# tag::copy-war[]
26COPY --chown=1001:0 target/system.war /config/apps
27# end::copy-war[]
28
29RUN configure.sh

Building your Docker image

Now that your microservices are packaged and you have written your Dockerfiles, you will build your Docker images by using the docker build command.

Run the following command to download or update to the latest openliberty/open-liberty:kernel-java8-openj9-ubi Docker image:

docker pull openliberty/open-liberty:kernel-java8-openj9-ubi

Run the following commands to build container images for your application:

docker build -t system:1.0-SNAPSHOT system/.
docker build -t inventory:1.0-SNAPSHOT inventory/.

The -t flag in the docker build command allows the Docker image to be labeled (tagged) in the name[:tag] format. The tag for an image describes the specific image version. If the optional [:tag] tag is not specified, the latest tag is created by default.

To verify that the images are built, run the docker images command to list all local Docker images:

docker images

Or, run the docker images command with --filter option to list your images:

docker images -f "label=org.opencontainers.image.authors=Your Name"

Your two images, inventory and system, should appear in the list of all Docker images:

REPOSITORY    TAG             IMAGE ID        CREATED          SIZE
inventory     1.0-SNAPSHOT    08fef024e986    4 minutes ago    471MB
system        1.0-SNAPSHOT    1dff6d0b4f31    5 minutes ago    470MB

Running your microservices in Docker containers

Now that you have your two images built, you will run your microservices in Docker containers:

docker run -d --name system -p 9080:9080 system:1.0-SNAPSHOT
docker run -d --name inventory -p 9081:9081 inventory:1.0-SNAPSHOT

The flags are described in the table below:

FlagDescription

-d

Runs the container in the background.

--name

Specifies a name for the container.

-p

Maps the host ports to the container ports. For example: -p <HOST_PORT>:<CONTAINER_PORT>

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

docker ps

Make sure that your containers are running and show Up as their status:

CONTAINER ID    IMAGE                   COMMAND                  CREATED          STATUS          PORTS                                        NAMES
2b584282e0f5    inventory:1.0-SNAPSHOT  "/opt/ol/helpers/run…"   2 seconds ago    Up 1 second     9080/tcp, 9443/tcp, 0.0.0.0:9081->9081/tcp   inventory
99a98313705f    system:1.0-SNAPSHOT     "/opt/ol/helpers/run…"   3 seconds ago    Up 2 seconds    0.0.0.0:9080->9080/tcp, 9443/tcp             system

If a problem occurs and your containers exit prematurely, the containers don’t appear in the container list that the docker ps command displays. Instead, your containers appear with an Exited status when they run the docker ps -a command. Run the docker logs system and docker logs inventory commands to view the container logs for any potential problems. Run the docker stats system and docker stats inventory commands to display a live stream of usage statistics for your containers. You can also double-check that your Dockerfiles are correct. When you find the cause of the issues, remove the faulty containers with the docker rm system and docker rm inventory commands. Rebuild your images, and start the containers again.

To access the application, point your browser to the http://localhost:9081/inventory/systems URL. An empty list is expected because no system properties are stored in the inventory yet.

Next, retrieve the system container’s IP address by using the system container’s name that is defined when it ran the Docker containers. Run the following command to retrieve the system IP address:

docker inspect -f "{{.NetworkSettings.IPAddress }}" system

You find the system container’s IP address:

172.17.0.2

In this case, the IP address for the system service is 172.17.0.2. Take note of this IP address to add the system properties to the inventory service.

Point your browser to http://localhost:9081/inventory/systems/[system-ip-address] by replacing [system-ip-address] with the IP address you obtained earlier. You see a result in JSON format with the system properties of your local JVM. When you visit this URL, these system properties are automatically stored in the inventory. Go back to http://localhost:9081/inventory/systems and you see a new entry for [system-ip-address].

Testing the microservices

You can test your microservices manually by hitting the endpoints or with automated tests that check your running Docker containers.

Create the SystemEndpointIT class.
system/src/test/java/it/io/openliberty/guides/system/SystemEndpointIT.java

SystemEndpointIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2020 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 it.io.openliberty.guides.system;
14
15import static org.junit.jupiter.api.Assertions.assertEquals;
16
17import javax.net.ssl.HostnameVerifier;
18import javax.net.ssl.SSLSession;
19import javax.ws.rs.client.Client;
20import javax.ws.rs.client.ClientBuilder;
21import javax.ws.rs.client.WebTarget;
22import javax.ws.rs.core.Response;
23
24import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
25import org.junit.jupiter.api.AfterEach;
26import org.junit.jupiter.api.BeforeAll;
27import org.junit.jupiter.api.BeforeEach;
28import org.junit.jupiter.api.Test;
29
30public class SystemEndpointIT {
31
32    private static String clusterUrl;
33
34    private Client client;
35
36    @BeforeAll
37    public static void oneTimeSetup() {
38        String nodePort = System.getProperty("system.http.port");
39        clusterUrl = "http://localhost:" + nodePort + "/system/properties/";
40    }
41
42    @BeforeEach
43    public void setup() {
44        client = ClientBuilder.newBuilder()
45                    .hostnameVerifier(new HostnameVerifier() {
46                        public boolean verify(String hostname, SSLSession session) {
47                            return true;
48                        }
49                    })
50                    .build();
51    }
52
53    @AfterEach
54    public void teardown() {
55        client.close();
56    }
57
58    // tag::testGetProperties[]
59    @Test
60    public void testGetProperties() {
61        Client client = ClientBuilder.newClient();
62        client.register(JsrJsonpProvider.class);
63
64        WebTarget target = client.target(clusterUrl);
65        Response response = target.request().get();
66
67        assertEquals(200, response.getStatus(),
68            "Incorrect response code from " + clusterUrl);
69        response.close();
70    }
71    // end::testGetProperties[]
72
73}

The testGetProperties() method checks for a 200 response code from the system service endpoint.

Create the InventoryEndpointIT class.
inventory/src/test/java/it/io/openliberty/guides/inventory/InventoryEndpointIT.java

InventoryEndpointIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2020 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 it.io.openliberty.guides.inventory;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16import static org.junit.jupiter.api.Assertions.assertTrue;
 17
 18import javax.json.JsonObject;
 19import javax.net.ssl.HostnameVerifier;
 20import javax.net.ssl.SSLSession;
 21import javax.ws.rs.client.Client;
 22import javax.ws.rs.client.ClientBuilder;
 23import javax.ws.rs.core.MediaType;
 24import javax.ws.rs.core.Response;
 25
 26import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 27import org.junit.jupiter.api.AfterAll;
 28import org.junit.jupiter.api.BeforeAll;
 29import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 30import org.junit.jupiter.api.Order;
 31import org.junit.jupiter.api.Test;
 32import org.junit.jupiter.api.TestMethodOrder;
 33
 34@TestMethodOrder(OrderAnnotation.class)
 35public class InventoryEndpointIT {
 36
 37    private static String invUrl;
 38    private static String sysUrl;
 39    private static String systemServiceIp;
 40
 41    private static Client client;
 42
 43    @BeforeAll
 44    public static void oneTimeSetup() {
 45
 46        String invServPort = System.getProperty("inventory.http.port");
 47        String sysServPort = System.getProperty("system.http.port");
 48
 49        // tag::systemServiceIp[]
 50        systemServiceIp = System.getProperty("system.ip");
 51        // end::systemServiceIp[]
 52
 53        invUrl = "http://localhost" + ":" + invServPort + "/inventory/systems/";
 54        sysUrl = "http://localhost" + ":" + sysServPort + "/system/properties/";
 55
 56        client = ClientBuilder.newBuilder().hostnameVerifier(new HostnameVerifier() {
 57            public boolean verify(String hostname, SSLSession session) {
 58                return true;
 59            }
 60        }).build();
 61
 62        client.register(JsrJsonpProvider.class);
 63        client.target(invUrl + "reset").request().post(null);
 64    }
 65
 66    @AfterAll
 67    public static void teardown() {
 68        client.close();
 69    }
 70
 71    // tag::tests[]
 72    // tag::testEmptyInventory[]
 73    @Test
 74    @Order(1)
 75    public void testEmptyInventory() {
 76        Response response = this.getResponse(invUrl);
 77        this.assertResponse(invUrl, response);
 78
 79        JsonObject obj = response.readEntity(JsonObject.class);
 80
 81        int expected = 0;
 82        int actual = obj.getInt("total");
 83        assertEquals(expected, actual,
 84                        "The inventory should be empty on application start but it wasn't");
 85
 86        response.close();
 87    }
 88    // end::testEmptyInventory[]
 89
 90    // tag::testHostRegistration[]
 91    @Test
 92    @Order(2)
 93    public void testHostRegistration() {
 94        this.visitSystemService();
 95
 96        Response response = this.getResponse(invUrl);
 97        this.assertResponse(invUrl, response);
 98
 99        JsonObject obj = response.readEntity(JsonObject.class);
100
101        int expected = 1;
102        int actual = obj.getInt("total");
103        assertEquals(expected, actual,
104                        "The inventory should have one entry for " + systemServiceIp);
105
106        boolean serviceExists = obj.getJsonArray("systems").getJsonObject(0)
107                        .get("hostname").toString().contains(systemServiceIp);
108        assertTrue(serviceExists,
109                        "A host was registered, but it was not " + systemServiceIp);
110
111        response.close();
112    }
113    // end::testHostRegistration[]
114
115    // tag::testSystemPropertiesMatch[]
116    @Test
117    @Order(3)
118    public void testSystemPropertiesMatch() {
119        Response invResponse = this.getResponse(invUrl);
120        Response sysResponse = this.getResponse(sysUrl);
121
122        this.assertResponse(invUrl, invResponse);
123        this.assertResponse(sysUrl, sysResponse);
124
125        JsonObject jsonFromInventory = (JsonObject) invResponse
126                        .readEntity(JsonObject.class).getJsonArray("systems")
127                        .getJsonObject(0).get("properties");
128
129        JsonObject jsonFromSystem = sysResponse.readEntity(JsonObject.class);
130
131        String osNameFromInventory = jsonFromInventory.getString("os.name");
132        String osNameFromSystem = jsonFromSystem.getString("os.name");
133        this.assertProperty("os.name", systemServiceIp, osNameFromSystem,
134                        osNameFromInventory);
135
136        String userNameFromInventory = jsonFromInventory.getString("user.name");
137        String userNameFromSystem = jsonFromSystem.getString("user.name");
138        this.assertProperty("user.name", systemServiceIp, userNameFromSystem,
139                        userNameFromInventory);
140
141        invResponse.close();
142        sysResponse.close();
143    }
144    // end::testSystemPropertiesMatch[]
145
146    // tag::testUnknownHost[]
147    @Test
148    @Order(4)
149    public void testUnknownHost() {
150        Response response = this.getResponse(invUrl);
151        this.assertResponse(invUrl, response);
152
153        Response badResponse = client.target(invUrl + "badhostname")
154                        .request(MediaType.APPLICATION_JSON).get();
155
156        String obj = badResponse.readEntity(String.class);
157
158        boolean isError = obj.contains("error");
159        assertTrue(isError,
160                        "badhostname is not a valid host but it didn't raise an error");
161
162        response.close();
163        badResponse.close();
164    }
165    // end::testUnknownHost[]
166    // end::tests[]
167
168    // Returns response information from the specified URL.
169    private Response getResponse(String url) {
170        return client.target(url).request().get();
171    }
172
173
174    // Asserts that the given URL has the correct response code of 200.
175    private void assertResponse(String url, Response response) {
176        assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
177    }
178
179    // Asserts that the specified JVM system property is equivalent in both the
180    // system and inventory services.
181    private void assertProperty(String propertyName, String hostname, String expected,
182                    String actual) {
183        assertEquals(expected, actual, "JVM system property [" + propertyName + "] "
184                        + "in the system service does not match the one stored in "
185                        + "the inventory service for " + hostname);
186    }
187
188    // Makes a simple GET request to inventory/localhost.
189    private void visitSystemService() {
190        Response response = this.getResponse(sysUrl);
191        this.assertResponse(sysUrl, response);
192        response.close();
193
194        Response targetResponse = client.target(invUrl + systemServiceIp).request()
195                        .get();
196
197        targetResponse.close();
198    }
199}
  • The testEmptyInventory() method checks that the inventory service has a total of 0 systems before anything is added to it.

  • The testHostRegistration() method checks that the system service was added to inventory properly.

  • The testSystemPropertiesMatch() checks that the system properties match what was added into the inventory service.

  • The testUnknownHost() method checks that an error is raised if an unknown host name is being added into the inventory service.

  • The systemServiceIp variable has the same value as what you retrieved in the previous section when manually adding the system service into the inventory service. This value of the IP address is passed in when you run the tests.

Running the tests

Run the Maven package goal to compile the test classes. Run the Maven failsafe goal to test the services that are running in the Docker containers by replacing the [system-ip-address] with the IP address that was determined in the previous section.

mvn package
mvn failsafe:integration-test -Dsystem.ip=[system-ip-address] -Dinventory.http.port=9081 -Dsystem.http.port=9080

If the tests pass, you see a similar output as the following:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.653 s - in it.io.openliberty.guides.system.SystemEndpointIT

Results:

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.inventory.InventoryEndpointIT
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.935 s - in it.io.openliberty.guides.inventory.InventoryEndpointIT

Results:

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

When you are finished with the services, run the following commands to stop and remove your containers:

docker stop inventory system
docker rm inventory system

Great work! You’re done!

You have just built Docker images and run two microservices on Open Liberty in containers.

Guide Attribution

Containerizing microservices 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