Using Docker containers to develop microservices

duration 20 minutes

Prerequisites:

Learn how to use Docker containers for iterative development.

What you’ll learn

You will learn how to set up, run, and iteratively develop a simple REST application in a container with Open Liberty and Docker.

Open Liberty is a lightweight open framework for building fast and efficient cloud-native Java microservices. It’s small, lightweight, and designed with modern cloud-native application development in mind. Open Liberty simplifies the development process for these applications by automating the repetitive actions associated with running applications inside containers, like rebuilding the image and stopping and starting the container.

You’ll also learn how to create and run automated tests for your application and container.

The implementation of the REST application can be found in the start/src directory. To learn more about this application and how to build it, check out the Creating a RESTful web service guide.

What is Docker?

Docker is a tool that you can use to deploy and run applications with containers. You can think of Docker like a virtual machine that runs various applications. However, unlike a typical virtual machine, you can run these applications simultaneously on a single system and independent of one another.

Learn more about Docker on the official Docker website.

What is a container?

A container is a lightweight, stand-alone package that contains a piece of software that is bundled together with the entire environment that it needs to run. Containers are small compared to regular images and can run on any environment where Docker is set up. Moreover, you can run multiple containers on a single machine at the same time in isolation from each other.

Learn more about containers on the official Docker website.

Why use a container to develop?

Consider a scenario where you need to deploy your application on another environment. Your application works on your local machine, but when you try to run it on your cloud production environment, it breaks. You do some debugging and discover that you built your application with Java 8, but this cloud production environment has only Java 11 installed. Although this issue is generally easy to fix, you don’t want your application to be missing dozens of version-specific dependencies. You can develop your application in this cloud environment, but that requires you to rebuild and repackage your application every time you update your code and wish to test it.

To avoid this kind of problem, you can instead choose to develop your application in a container locally, bundled together with the entire environment that it needs to run. By doing this, you know that at any point in your iterative development process, the application can run inside that container. This helps avoid any unpleasant surprises when you go to test or deploy your application down the road. Containers run quickly and do not have a major impact on the speed of your iterative development.

Additional prerequisites

Before you begin, you need to install Docker if it is not already installed. For installation instructions, refer to the official Docker documentation. You will build and run the application 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-docker.git
cd guide-docker

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

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

Before you begin, make sure you have all the necessary prerequisites.

Creating the Dockerfile

The first step to running your application inside of a Docker container is creating a Dockerfile. A Dockerfile is a collection of instructions for building a Docker image that can then be run as a container. Every Dockerfile begins with a parent or base image on top of which various commands are run. For example, you can start your image from scratch and run commands that download and install Java, or you can start from an image that already contains a Java installation.

Navigate to the start directory to begin.

Create the Dockerfile in the start directory.
Dockerfile

Dockerfile

 1# Start with OL runtime.
 2# tag::from[]
 3FROM icr.io/appcafe/open-liberty:kernel-slim-java11-openj9-ubi
 4# end::from[]
 5
 6ARG VERSION=1.0
 7ARG REVISION=SNAPSHOT
 8# tag::label[]
 9
10LABEL \
11  org.opencontainers.image.authors="Your Name" \
12  org.opencontainers.image.vendor="IBM" \
13  org.opencontainers.image.url="local" \
14  org.opencontainers.image.source="https://github.com/OpenLiberty/guide-docker" \
15  org.opencontainers.image.version="$VERSION" \
16  org.opencontainers.image.revision="$REVISION" \
17  vendor="Open Liberty" \
18  name="system" \
19  version="$VERSION-$REVISION" \
20  summary="The system microservice from the Docker Guide" \
21  # tag::description[]
22  description="This image contains the system microservice running with the Open Liberty runtime."
23  # end::description[]
24# end::label[]
25
26# tag::user-root[]
27USER root
28# end::user-root[]
29
30# tag::copy[]
31COPY --chown=1001:0 src/main/liberty/config/server.xml /config/
32RUN features.sh
33COPY --chown=1001:0 target/*.war /config/apps/
34# end::copy[]
35RUN configure.sh
36# tag::user[]
37USER 1001
38# end::user[]

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

In this case, you’re using the icr.io/appcafe/open-liberty:kernel-slim-java11-openj9-ubi image as your parent image, which comes with the latest Open Liberty runtime.

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 Liberty configuration file that is located at src/main/liberty/config/server.xml is copied to the /config/ destination directory.

Writing a .dockerignore file

.dockerignore

1.DS_Store
2pom.xml

When Docker runs a build, it sends all of the files and directories that are located in the same directory as the Dockerfile to its build context, making them available for use in instructions like ADD and COPY. If there are files or directories you wish to exclude from the build context, you can add them to a .dockerignore file. By adding files that aren’t nessecary for building your image to the .dockerignore file, you can decrease the image’s size and speed up the building process. You may also want to exclude files that contain sensitive information, such as a .git folder or private keys, from the build context.

A .dockerignore file is available to you in the start directory. This file includes the pom.xml file and some system files.

Launching Open Liberty in dev mode

The Open Liberty Maven plug-in includes a devc goal that builds a Docker image, mounts the required directories, binds the required ports, and then runs the application inside of a container. This dev mode, also listens for any changes in the application source code or configuration and rebuilds the image and restarts the container as necessary.

Build and run the container by running the devc goal from the start directory:

mvn liberty:devc

After you see the following message, your Liberty instance is ready in dev mode:

**************************************************************
*    Liberty is running in dev mode.

Open another command-line session and run the following command to make sure that your container is running and didn’t crash:

docker ps

You should see something similar to the following output:

CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                                                    NAMES
ee2daf0b33e1        guide-docker-dev-mode   "/opt/ol/helpers/run…"   2 minutes ago       Up 2 minutes        0.0.0.0:7777->7777/tcp, 0.0.0.0:9080->9080/tcp, 0.0.0.0:9443->9443/tcp   liberty-dev

To view a full list of all available containers, you can run the docker ps -a command.

If your container runs without problems, go to the http://localhost:9080/system/properties URL swhere you can see a JSON response that contains the system properties of the JVM in your container.

Updating the application while the container is running

With your container running, make the following update to the source code:

Update the PropertiesResource class.
src/main/java/io/openliberty/guides/rest/PropertiesResource.java

PropertiesResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 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 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.rest;
13
14import jakarta.ws.rs.Path;
15import jakarta.ws.rs.core.MediaType;
16import jakarta.ws.rs.GET;
17import jakarta.ws.rs.Produces;
18
19import jakarta.json.JsonObject;
20import jakarta.json.JsonObjectBuilder;
21import jakarta.json.Json;
22
23// tag::Path[]
24@Path("properties-new")
25// end::Path[]
26public class PropertiesResource {
27
28    @GET
29    @Produces(MediaType.APPLICATION_JSON)
30    public JsonObject getProperties() {
31
32        JsonObjectBuilder builder = Json.createObjectBuilder();
33
34        System.getProperties()
35              .entrySet()
36              .stream()
37              .forEach(entry -> builder.add((String) entry.getKey(),
38                                            (String) entry.getValue()));
39
40       return builder.build();
41    }
42}

Change the endpoint of your application from properties to properties-new by changing the @Path annotation to "properties-new".

After you make the file changes, Open Liberty automatically updates the application. To see these changes reflected in the application, go to the http://localhost:9080/system/properties-new URL.

Testing the container

You can test this service manually by starting a Liberty instance and going to the http://localhost:9080/system/properties-new URL. However, automated tests are a much better approach because they trigger a failure if a change introduces a bug. JUnit and the JAX-RS Client API provide a simple environment to test the application. You can write tests for the individual units of code outside of a running Liberty instance, or you can write them to call the instance directly. In this example, you will create a test that calls the instance directly.

Create the EndpointIT test class.
src/test/java/it/io/openliberty/guides/rest/EndpointIT.java

EndpointIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 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 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package it.io.openliberty.guides.rest;
13
14import static org.junit.jupiter.api.Assertions.assertEquals;
15
16import org.junit.jupiter.api.Test;
17
18import jakarta.json.JsonObject;
19
20import jakarta.ws.rs.client.Client;
21import jakarta.ws.rs.client.ClientBuilder;
22import jakarta.ws.rs.client.WebTarget;
23import jakarta.ws.rs.core.Response;
24
25
26public class EndpointIT {
27
28    @Test
29    public void testGetProperties() {
30        String port = System.getProperty("liberty.test.port");
31        String url = "http://localhost:" + port + "/";
32
33        Client client = ClientBuilder.newClient();
34
35        WebTarget target = client.target(url + "system/properties-new");
36        Response response = target.request().get();
37        JsonObject obj = response.readEntity(JsonObject.class);
38
39        assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
40
41        assertEquals("/opt/ol/wlp/output/defaultServer/",
42                     obj.getString("server.output.dir"),
43                     "The system property for the server output directory should match "
44                     + "the Open Liberty container image.");
45
46        response.close();
47    }
48}

This test makes a request to the /system/properties-new endpoint and checks to make sure that the response has a valid status code, and that the information in the response is correct.

Running the tests

Because you started Open Liberty in dev mode, you can run the tests by pressing the enter/return key from the command-line session where you started dev mode.

You will see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.rest.EndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.884 sec - in it.io.openliberty.guides.rest.EndpointIT

Results :

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

When you are finished, press CTRL+C in the session that the dev mode was started from to stop and remove the container.

Starting dev mode with run options

Another useful feature of dev mode with a container is the ability to pass additional options to the docker run command. You can do this by adding the dockerRunOpts tag to the pom.xml file under the configuration tag of the Liberty Maven Plugin. Here is an example of an environment variable being passed in:

<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>3.10</version>
<configuration>
    <dockerRunOpts>-e ENV_VAR=exampleValue</dockerRunOpts>
</configuration>

If the Dockerfile isn’t located in the directory that the devc goal is being run from, you can add the dockerfile tag to specify the location. Using this parameter sets the context for building the Docker image to the directory that contains this file.

Additionally, both of these options can be passed from the command line when running the devc goal by adding -D as such:

mvn liberty:devc \
-DdockerRunOpts="-e ENV_VAR=exampleValue" \
-Ddockerfile="./path/to/file"

To learn more about dev mode with a container and its different features, check out the Documentation.

Great work! You’re done!

You just iteratively developed a simple REST application in a container with Open Liberty and Docker.

Guide Attribution

Using Docker containers to develop microservices by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

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