Using Docker containers to develop microservices

duration 20 minutes


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
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.


 1# Start with OL runtime.
 2# tag::from[]
 4# end::from[]
 8# tag::label[]
11  org.opencontainers.image.authors="Your Name" \
12  org.opencontainers.image.vendor="IBM" \
13  org.opencontainers.image.url="local" \
14  org.opencontainers.image.source="" \
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[]
26# tag::user-root[]
27USER root
28# end::user-root[]
30# tag::copy[]
31COPY --chown=1001:0 src/main/liberty/config/server.xml /config/
33COPY --chown=1001:0 target/*.war /config/apps/
34# end::copy[]
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 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



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>7777/tcp,>9080/tcp,>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.

 1// tag::copyright[]
 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 *
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
19import jakarta.json.JsonObject;
20import jakarta.json.JsonObjectBuilder;
21import jakarta.json.Json;
23// tag::Path[]
25// end::Path[]
26public class PropertiesResource {
28    @GET
29    @Produces(MediaType.APPLICATION_JSON)
30    public JsonObject getProperties() {
32        JsonObjectBuilder builder = Json.createObjectBuilder();
34        System.getProperties()
35              .entrySet()
36              .stream()
37              .forEach(entry -> builder.add((String) entry.getKey(),
38                                            (String) entry.getValue()));
40       return;
41    }

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.

 1// tag::copyright[]
 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 *
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
14import static org.junit.jupiter.api.Assertions.assertEquals;
16import org.junit.jupiter.api.Test;
18import jakarta.json.JsonObject;
26public class EndpointIT {
28    @Test
29    public void testGetProperties() {
30        String port = System.getProperty("liberty.test.port");
31        String url = "http://localhost:" + port + "/";
33        Client client = ClientBuilder.newClient();
35        WebTarget target = + "system/properties-new");
36        Response response = target.request().get();
37        JsonObject obj = response.readEntity(JsonObject.class);
39        assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
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.");
46        response.close();
47    }

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
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.884 sec - in

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:

    <dockerRunOpts>-e ENV_VAR=exampleValue</dockerRunOpts>

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" \

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


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.