Add Java get started guide (#12725)

* Adg Java get started guide

Signed-off-by: Usha Mandya <usha.mandya@docker.com>

* Address review comments

Signed-off-by: Usha Mandya <usha.mandya@docker.com>

* Fix alignment issues

Signed-off-by: Usha Mandya <usha.mandya@docker.com>

* Fix style issues

Signed-off-by: Usha Mandya <usha.mandya@docker.com>
This commit is contained in:
Usha Mandya 2021-04-26 09:37:29 +01:00 committed by GitHub
parent 0ea0a6173f
commit 27b31d4758
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 1203 additions and 10 deletions

View File

@ -85,6 +85,18 @@ guides:
section: section:
- title: "Overview" - title: "Overview"
path: /language/java/ path: /language/java/
- title: "Build images"
path: /language/java/build-images/
- title: "Run containers"
path: /language/java/run-containers/
- title: "Develop your app"
path: /language/java/develop/
- title: "Run your tests"
path: /language/java/run-tests/
- title: "Configure CI/CD"
path: /language/java/configure-ci-cd/
- title: "Deploy your app"
path: /language/java/deploy/
- sectiontitle: Develop with Docker - sectiontitle: Develop with Docker
section: section:
- path: /develop/ - path: /develop/

View File

@ -0,0 +1,239 @@
---
title: "Build your Java image"
keywords: Java, build, images, dockerfile
description: Learn how to build your first Docker image by writing a Dockerfile
---
{% include_relative nav.html selected="1" %}
## Prerequisites
Work through the orientation and setup in Get started [Part 1](../../get-started/index.md){:target="_blank" rel="noopener" class="_"} to understand Docker concepts. Refer to the following section for Java prerequisites.
## Overview
Now that we have a good overview of containers and the Docker platform, lets take a look at building our first image. An image includes everything needed to run an application - the code or binary, runtime, dependencies, and any other file system objects required.
To complete this tutorial, you need the following:
- Java OpenJDK version 15 or later. [Download and install Java](https://jdk.java.net/){: target="_blank" rel="noopener" class="_"}
- Docker running locally. Follow the instructions to [download and install Docker](../../get-docker.md)
- A Git client
- An IDE or a text editor to edit files. We recommend using [IntelliJ Community Edition](https://www.jetbrains.com/idea/download/){: target="_blank" rel="noopener" class="_"}.
## Sample application
Lets clone the sample application that we'll be using in this module to our local development machine. Run the following commands in a terminal to clone the repo.
```console
$ cd /path/to/working/directory
$ git clone https://github.com/spring-projects/spring-petclinic.git
$ cd spring-petclinic
```
## Test the application
Lets start our application and make sure it is running properly. Maven will manage all the project processes (compiling, tests, packaging, etc). The **Spring Pets Clinic** project we cloned earlier contains an embedded version of Maven. Therefore, we don't need to install Maven separately on your local machine.
Open your terminal and navigate to the working directory we created and run the following command:
```console
$ ./mvnw spring-boot:run
```
This downloads the dependencies, builds the project, and starts it.
To test that the application is working properly, open a new browser and navigate to `http://localhost:8080`.
Switch back to the terminal where our server is running and you should see the following requests in the server logs. The data will be different on your machine.
```console
o.s.s.petclinic.PetClinicApplication : Started
PetClinicApplication in 11.743 seconds (JVM running for 12.364)
```
## Create a Dockerfile for Java
Now that our application is running properly, lets take a look at creating a Dockerfile.
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. When we tell Docker to build our image by executing the `docker build` command, Docker reads these instructions and execute them sequentially and creates a Docker image.
Lets walk through the steps on creating a Dockerfile for our application. In the root of your working directory, create a file named `Dockerfile` and open this file in your text editor.
> **Note**
>
> The name of the Dockerfile is not important but the default filename for many commands is simply `Dockerfile`. Therefore, well use that as our filename throughout this series.
The first line to add to the Dockerfile is a [`# syntax` parser directive](/engine/reference/builder/#syntax).
While _optional_, this directive instructs the Docker builder what syntax to use
when parsing the Dockerfile, and allows older Docker versions with BuildKit enabled
to upgrade the parser before starting the build. Parser directives
must appear before any other comment, whitespace, or Dockerfile instruction in
your Dockerfile, and should be the first line in Dockerfiles.
```dockerfile
# syntax=docker/dockerfile:1
```
We recommend using `docker/dockerfile:1`, which always points to the latest release
of the version 1 syntax. BuildKit automatically checks for updates of the syntax
before building, making sure you are using the most current version.
Next, we need to add a line in our Dockerfile that tells Docker what base image
we would like to use for our application.
```dockerfile
# syntax=docker/dockerfile:1
FROM openjdk:16-alpine3.13
```
Docker images can be inherited from other images. Therefore, instead of creating our own base image, well use the official Maven image with Java JDK that already has all the tools and packages that we need to run a Java application.
> **Note**
>
> To learn more about creating your own base images, see [Creating base images](https://docs.docker.com/develop/develop-images/baseimages/).
To make things easier when running the rest of our commands, lets create a working directory. This instructs Docker to use this path as the default location for all subsequent commands. By doing this, we do not have to type out full file paths but can use relative paths based on the working directory.
```dockerfile
WORKDIR /app
```
Usually, the very first thing you do once youve downloaded a project written in Java which is using Maven for project management is to install dependencies.
Before we can run `mvnw dependency`, we need to get the Maven wrapper and our `pom.xml` file into our image. Well use the `COPY` command to do this. The `COPY` command takes two parameters. The first parameter tells Docker what file(s) you would like to copy into the image. The second parameter tells Docker where you want that file(s) to be copied to. Well copy all those files and directories into our working directory - `/app`.
```dockerfile
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
```
Once we have our `pom.xml` file inside the image, we can use the `RUN` command to execute the command `mvnw dependency:go-offline`. This works exactly the same way as if we were running `mvnw` (or mvn) dependency locally on our machine, but this time the dependencies will be installed into the image.
```dockerfile
RUN ./mvnw dependency:go-offline
```
At this point, we have an Alpine version 3.13 image that is based on OpenJDK version 16, and we have also installed our dependencies. The next thing we need to do is to add our source code into the image. Well use the `COPY` command just like we did with our `pom.xml` file above.
```dockerfile
COPY src ./src
```
This `COPY` command takes all the files located in the current directory and copies them into the image. Now, all we have to do is to tell Docker what command we want to run when our image is executed inside a container. We do this using the `CMD` command.
```dockerfile
CMD ["./mvnw", "spring-boot:run"]
```
Here's the complete Dockerfile.
```dockerfile
# syntax=docker/dockerfile:1
FROM openjdk:16-alpine3.13
WORKDIR /app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY src ./src
CMD ["./mvnw", "spring-boot:run"]
```
### Create a `.dockerignore` file
To use a file in the build context, the Dockerfile refers to the file specified in an instruction, for example, a `COPY` instruction. To increase the performance of the build, and to exclude files and directories, we recommend that you create a `.dockerignore` file to the context directory. To improve the context load time, add a `target` directory within the `.dockerignore` file.
## Build an image
Now that weve created our Dockerfile, lets build our image. To do this, we use the `docker build` command. The `docker build` command builds Docker images from a Dockerfile and a “context”. A builds context is the set of files located in the specified PATH or URL. The Docker build process can access any of the files located in this context.
The build command optionally takes a `--tag` flag. The tag is used to set the name of the image and an optional tag in the format `name:tag`. Well leave off the optional `tag` for now to help simplify things. If we do not pass a tag, Docker uses “latest” as its default tag. You can see this in the last line of the build output.
Lets build our first Docker image.
```console
$ docker build --tag java-docker .
```
```console
Sending build context to Docker daemon 5.632kB
Step 1/7 : FROM java:3.7-alpine
Step 2/7 : WORKDIR /app
...
Successfully built a0bb458aabd0
Successfully tagged java-docker:latest
```
## View local images
To see a list of images we have on our local machine, we have two options. One is to use the CLI and the other is to use [Docker Desktop](../../desktop/dashboard.md#explore-your-images). As we are currently working in the terminal lets take a look at listing images using the CLI.
To list images, simply run the `docker images` command.
```console
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
java-docker latest b1b5f29f74f0 47 minutes ago 567MB
```
You should see at least the we just built `java-docker:latest`.
## Tag images
An image name is made up of slash-separated name components. Name components may contain lowercase letters, digits, and separators. A separator is defined as a period, one or two underscores, or one or more dashes. A name component may not start or end with a separator.
An image is made up of a manifest and a list of layers. Do not worry too much about manifests and layers at this point other than a “tag” points to a combination of these artifacts. You can have multiple tags for an image. Lets create a second tag for the image we built and take a look at its layers.
To create a new tag for the image weve built above, run the following command:
```console
$ docker tag java-docker:latest java-docker:v1.0.0
```
The `docker tag` command creates a new tag for an image. It does not create a new image. The tag points to the same image and is just another way to reference the image.
Now, run the `docker images` command to see a list of our local images.
```console
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
java-docker latest b1b5f29f74f0 59 minutes ago 567MB
java-docker v1.0.0 b1b5f29f74f0 59 minutes ago 567MB
```
You can see that we have two images that start with `java-docker`. We know they are the same image because if you take a look at the `IMAGE ID` column, you can see that the values are the same for the two images.
Lets remove the tag that we just created. To do this, well use the `rmi` command. The `rmi` command stands for “remove image”.
```console
$ docker rmi java-docker:v1.0.0
Untagged: java-docker:v1.0.0
```
Note that the response from Docker tells us that the image has not been removed but only “untagged”. You can check this by running the `docker images` command.
```console
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
java-docker latest b1b5f29f74f0 59 minutes ago 567MB
```
Our image that was tagged with `:v1.0.0` has been removed, but we still have the `java-docker:latest` tag available on our machine.
## Next steps
In this module, we took a look at setting up our example Java application that we'll use for the rest of the tutorial. We also created a Dockerfile that we used to build our Docker image. Then, we took a look at tagging our images and removing images. In the next module, well take a look at how to:
[Run your image as a container](run-containers.md){: .button .primary-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

View File

@ -0,0 +1,300 @@
---
title: "Configure CI/CD for your application"
keywords: Java, CI/CD, local, development
description: Learn how to Configure CI/CD for your application
---
{% include_relative nav.html selected="5" %}
This page guides you through the process of setting up a GitHub Action CI/CD pipeline with Docker containers. Before setting up a new pipeline, we recommend that you take a look at [Ben's blog](https://www.docker.com/blog/best-practices-for-using-docker-hub-for-ci-cd/){:target="_blank" rel="noopener" class="_"} on CI/CD best practices .
This guide contains instructions on how to:
1. Use a sample Docker project as an example to configure GitHub Actions
2. Set up the GitHub Actions workflow
3. Optimize your workflow to reduce the number of pull requests and the total build time
4. Push only specific versions to Docker Hub
5. Optimize your image using multi-stage builds
## Set up a Docker project
Lets get started. This guide uses a simple Docker project as an example. The [SimpleWhaleDemo](https://github.com/usha-mandya/SimpleWhaleDemo){:target="_blank" rel="noopener" class="_"} repository contains an Ngnix alpine image. You can either clone this repository, or use your own Docker project.
![SimpleWhaleDemo](../../ci-cd/images/simplewhaledemo.png){:width="500px"}
Before we start, ensure you can access [Docker Hub](https://hub.docker.com/) from any workflows you create. To do this:
1. Add your Docker ID as a secret to GitHub. Navigate to your GitHub repository and click **Settings** > **Secrets** > **New secret**.
2. Create a new secret with the name `DOCKER_HUB_USERNAME` and your Docker ID as value.
3. Create a new Personal Access Token (PAT). To create a new token, go to [Docker Hub Settings](https://hub.docker.com/settings/security) and then click **New Access Token**.
4. Lets call this token **simplewhaleci**.
![New access token](../../ci-cd/images/github-access-token.png){:width="500px"}
5. Now, add this Personal Access Token (PAT) as a second secret into the GitHub secrets UI with the name `DOCKER_HUB_ACCESS_TOKEN`.
![GitHub Secrets](../../ci-cd/images/github-secrets.png){:width="500px"}
## Set up the GitHub Actions workflow
In the previous section, we created a PAT and added it to GitHub to ensure we can access Docker Hub from any workflow. Now, lets set up our GitHub Actions workflow to build and store our images in Hub. We can achieve this by creating two Docker actions:
1. The first action enables us to log in to Docker Hub using the secrets we stored in the GitHub Repository.
2. The second one is the build and push action.
In this example, let us set the push flag to `true` as we also want to push. Well then add a tag to specify to always go to the latest version. Lastly, well echo the image digest to see what was pushed.
To set up the workflow:
1. Go to your repository in GitHub and then click **Actions** > **New workflow**.
2. Click **set up a workflow yourself** and add the following content:
First, we will name this workflow:
```yaml
name: CI to Docker Hub
```
Then, we will choose when we run this workflow. In our example, we are going to do it for every push against the main branch of our project:
```yaml
on:
push:
branches: [ main ]
```
Now, we need to specify what we actually want to happen within our action (what jobs), we are going to add our build one and select that it runs on the latest Ubuntu instances available:
```yaml
jobs:
build:
runs-on: ubuntu-latest
```
Now, we can add the steps required. The first one checks-out our repository under `$GITHUB_WORKSPACE`, so our workflow can access it. The second is to use our PAT and username to log into Docker Hub. The third is the Builder, the action uses BuildKit under the hood through a simple Buildx action which we will also setup
{% raw %}
```yaml
steps:
- name: Check Out Repo
uses: actions/checkout@v2
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
context: ./
file: ./Dockerfile
push: true
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/simplewhale:latest
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
```
{% endraw %}
Now, let the workflow run for the first time and then tweak the Dockerfile to make sure the CI is running and pushing the new image changes:
![CI to Docker Hub](../../ci-cd/images/ci-to-hub.png){:width="500px"}
## Optimize the workflow
Next, lets look at how we can optimize the GitHub Actions workflow through build cache. This has two main advantages:
1. Build cache reduces the build time as it will not have to re-download all of the images, and
2. It also reduces the number of pulls we complete against Docker Hub. We need to make use of GitHub cache to make use of this.
Let us set up a Builder with a build cache. First, we need to set up cache for the builder. In this example, let us add the path and keys to store this under using GitHub cache for this.
{% raw %}
```yaml
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
```
{% endraw %}
And lastly, after adding the builder and build cache snippets to the top of the Actions file, we need to add some extra attributes to the build and push step. This involves:
Setting up the builder to use the output of the buildx step, and then
Using the cache we set up earlier for it to store to and to retrieve
{% raw %}
```yaml
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
context: ./
file: ./Dockerfile
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/simplewhale:latest
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
```
{% endraw %}
Now, run the workflow again and verify that it uses the build cache.
## Push tagged versions to Docker Hub
Earlier, we learnt how to set up a GitHub Actions workflow to a Docker project, how to optimize the workflow by setting up a builder with build cache. Lets now look at how we can improve it further. We can do this by adding the ability to have tagged versions behave differently to all commits to master. This means, only specific versions are pushed, instead of every commit updating the latest version on Docker Hub.
You can consider this approach to have your commits go to a local registry to then use in nightly tests. By doing this, you can always test what is latest while reserving your tagged versions for release to Docker Hub.
This involves two steps:
1. Modifying the GitHub workflow to only push commits with specific tags to Docker Hub
2. Setting up a GitHub Actions file to store the latest commit as an image in the GitHub registry
First, let us modify our existing GitHub workflow to only push to Hub if theres a particular tag. For example:
{% raw %}
```yaml
on:
push:
tags:
- "v*.*.*"
```
{% endraw %}
This ensures that the main CI will only trigger if we tag our commits with `V.n.n.n.` Lets test this. For example, run the following command:
```bash
git tag -a v1.0.2
git push origin v1.0.2
```
Now, go to GitHub and check your Actions
![Push tagged version](../../ci-cd/images/push-tagged-version.png){:width="500px"}
Now, lets set up a second GitHub action file to store our latest commit as an image in the GitHub registry. You may want to do this to:
1. Run your nightly tests or recurring tests, or
2. To share work in progress images with colleagues.
Lets clone our previous GitHub action and add back in our previous logic for all pushes. This will mean we have two workflow files, our previous one and our new one we will now work on.
Next, change your Docker Hub login to a GitHub container registry login:
{% raw %}
```yaml
if: github.event_name != 'pull_request'
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GHCR_TOKEN }}
```
{% endraw %}
Remember to change how the image is tagged. The following example keeps latest as the only tag. However, you can add any logic to this if you prefer:
{% raw %}
```yaml
tags: ghcr.io/${{ github.repository_owner }}/simplewhale:latest
```
{% endraw %}
![Update tagged images](../../ci-cd/images/ghcr-logic.png){:width="500px"}
Now, we will have two different flows: one for our changes to master, and one for our pull requests. Next, we need to modify what we had before to ensure we are pushing our PRs to the GitHub registry rather than to Docker Hub.
## Optimize your image using multi-stage builds
Now, lets take a look at the Dockerfile and see how we can optimize it to work in development, as well as get smaller images to run containers in production. As this is the last step in the file, it will be used by default to build the image when you run a docker build without specifying the target:
```console
$ docker build --tag java-docker .
docker build --tag java-docker .
[+] Building 1.2s (15/15) FINISHED
=> [internal] load build definition from Dockerfile
=> => transferring dockerfile: 37B
=> [internal] load .dockerignore
=> => transferring context: 2B
=> [internal] load metadata for docker.io/library/openjdk:11-jre-slim
=> [internal] load metadata for docker.io/library/openjdk:16-alpine3.13
=> [internal] load build context
=> => transferring context: 11.48kB
=> [production 1/2] FROM docker.io/library/openjdk:11-jre-slim@sha256:85795599f4c765182c414a1eb4e272841e18e2f267ce5010ea6a266f7f26e7f6
=> [base 1/6] FROM docker.io/library/openjdk:16-alpine3.13@sha256:49d822f4fa4deb5f9d0201ffeec9f4d113bcb4e7e49bd6bc063d3ba93aacbcae
=> CACHED [base 2/6] WORKDIR /app
=> CACHED [base 3/6] COPY .mvn/ .mvn
=> CACHED [base 4/6] COPY mvnw pom.xml ./
=> CACHED [base 5/6] RUN ./mvnw dependency:go-offline
=> CACHED [base 6/6] COPY src ./src
=> CACHED [build 1/1] RUN ./mvnw package
=> CACHED [production 2/2] COPY --from=build /app/target/spring-petclinic-*.jar /spring-petclinic.jar
=> exporting to image
=> => exporting layers
=> => writing image sha256:c17469b9e2f30537060f48bbe5d9d22003dd35edef7092348824a2438101ab3a
=> => naming to docker.io/library/java-docker
```
The second interesting point is that this step doesnt take the base target or a JDK image as reference. Instead, it uses a Java Runtime Environment image.
Note that you dont need a large image with all the development dependencies to run your application in production. Limiting the number of dependencies in production images can significantly limit the attack surface.
```dockerfile
FROM openjdk:11-jre-slim as production
EXPOSE 8080
COPY --from=build /app/target/spring-petclinic-*.jar /spring-petclinic.jar
CMD ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/spring-petclinic.jar"]
```
The container will also automatically expose its 8080 port and copies the Java Archive produced in build step to use it at container startup.
The production image built in this way only contains a runtime environment with the final application archive, just what you need to start your Spring Pet Clinic application.
```console
$ docker build --tag java-docker:jdk . --target development
$ docker build --tag java-docker:jre .
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
java-docker jre c17469b9e2f3 3 hours ago 270MB
java-docker jdk 4c15436d8ab7 5 hours ago 567MB
```
## Next steps
In this module, you have learnt how to set up GitHub Actions workflow to an existing Docker project, optimize your workflow to improve build times and reduce the number of pull requests, and finally, we learnt how to push only specific versions to Docker Hub. You can also set up nightly tests against the latest tag, test each PR, or do something more elegant with the tags we are using and make use of the Git tag for the same tag in our image.
You can also consider deploying your application to the cloud. For detailed instructions, see:
[Deploy your application to the cloud](deploy.md){: .button .primary-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

29
language/java/deploy.md Normal file
View File

@ -0,0 +1,29 @@
---
title: "Deploy your app to the cloud"
keywords: deploy, ACI, ECS, Java, local, development
description: Learn how to deploy your application to the cloud.
---
{% include_relative nav.html selected="6" %}
Now, that we have configured a CI/CD pipleline, let's look at how we can deploy the application to cloud. Docker supports deploying containers on Azure ACI and AWS ECS.
## Docker and ACI
The Docker Azure Integration enables developers to use native Docker commands to run applications in Azure Container Instances (ACI) when building cloud-native applications. The new experience provides a tight integration between Docker Desktop and Microsoft Azure allowing developers to quickly run applications using the Docker CLI or VS Code extension, to switch seamlessly from local development to cloud deployment.
For detailed instructions, see [Deploying Docker containers on Azure](../../cloud/aci-integration.md).
## Docker and ECS
The Docker ECS Integration enables developers to use native Docker commands in Docker Compose CLI to run applications in Amazon EC2 Container Service (ECS) when building cloud-native applications.
The integration between Docker and Amazon ECS allows developers to use the Docker Compose CLI to set up an AWS context in one Docker command, allowing you to switch from a local context to a cloud context and run applications quickly and easily simplify multi-container application development on Amazon ECS using Compose files.
For detailed instructions, see [Deploying Docker containers on ECS](../../cloud/ecs-integration.md).
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

198
language/java/develop.md Normal file
View File

@ -0,0 +1,198 @@
---
title: "Use containers for development"
keywords: Java, local, development, run,
description: Learn how to develop your application locally.
---
{% include_relative nav.html selected="3" %}
## Prerequisites
Work through the steps to build an image and run it as a containerized application in [Run your image as a container](run-containers.md).
## Introduction
In this module, well walk through setting up a local development environment for the application we built in the previous modules. Well use Docker to build our images and Docker Compose to make everything a whole lot easier.
## Run a database in a container
First, well take a look at running a database in a container and how we use volumes and networking to persist our data and allow our application to talk with the database. Then well pull everything together into a Compose file which allows us to setup and run a local development environment with one command. Finally, well take a look at connecting a debugger to our application running inside a container.
Instead of downloading MySQL, installing, configuring, and then running the MySQL database as a service, we can use the Docker Official Image for MySQL and run it in a container.
Before we run MySQL in a container, we'll create a couple of volumes that Docker can manage to store our persistent data and configuration. Lets use the managed volumes feature that Docker provides instead of using bind mounts. You can read all about [Using volumes](../../storage/volumes.md) in our documentation.
Lets create our volumes now. Well create one for the data and one for configuration of MySQL.
```console
$ docker volume create mysql
$ docker volume create mysql_config
```
Now well create a network that our application and database will use to talk to each other. The network is called a user-defined bridge network and gives us a nice DNS lookup service which we can use when creating our connection string.
```console
$ docker network create mysqlnet
```
Now, let's run MySQL in a container and attach to the volumes and network we created above. Docker pulls the image from Hub and runs it locally.
```console
$ docker run -it --rm -d -v mysql_data:/var/lib/mysql \
-v mysql_config:/etc/mysql/conf.d \
--network mysqlnet \
--name mysqlserver \
-e MYSQL_USER=petclinic -e MYSQL_PASSWORD=petclinic \
-e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=petclinic \
-p 3306:3306 mysql:8.0.23
```
Okay, now that we have a running MySQL, lets update our Dockerfile to activate the MySQL Spring profile defined in the application and switch from an in-memory H2 database to the MySQL server we just created.
We only need to add the MySQL profil as an argument to the `CMD` definition.
```dockerfile
CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.profiles=mysql"]
```
Let's build our image
```console
$ docker build --tag java-docker .
```
Now, lets run our container. This time, we need to set the `MYSQL_URL` environment variable so that our application knows what connection string to use to access the database. Well do this using the `docker run` command.
```console
$ docker run --rm -d \
--name springboot-server \
--network mysqlnet \
-e MYSQL_URL=jdbc:mysql://mysqlserver/petclinic \
-p 8080:8080 java-docker
```
Lets test that our application is connected to the database and is able to list Veterinarians.
```console
$ curl --request GET \
--url http://localhost:8080/vets \
--header 'content-type: application/json'
```
You should receive the following json back from our service.
```json
{"vetList":[{"id":1,"firstName":"James","lastName":"Carter","specialties":[],"nrOfSpecialties":0,"new":false},{"id":2,"firstName":"Helen","lastName":"Leary","specialties":[{"id":1,"name":"radiology","new":false}],"nrOfSpecialties":1,"new":false},{"id":3,"firstName":"Linda","lastName":"Douglas","specialties":[{"id":3,"name":"dentistry","new":false},{"id":2,"name":"surgery","new":false}],"nrOfSpecialties":2,"new":false},{"id":4,"firstName":"Rafael","lastName":"Ortega","specialties":[{"id":2,"name":"surgery","new":false}],"nrOfSpecialties":1,"new":false},{"id":5,"firstName":"Henry","lastName":"Stevens","specialties":[{"id":1,"name":"radiology","new":false}],"nrOfSpecialties":1,"new":false},{"id":6,"firstName":"Sharon","lastName":"Jenkins","specialties":[],"nrOfSpecialties":0,"new":false}]}
```
## Use Compose to develop locally
In this section, well create a Compose file to start our `java-docker` and the MySQL database using a single command. Well also set up the Compose file to start the `java-docker` application in debug mode so that we can connect a debugger to the running Java process.
Open the `petclinic` in your IDE or a text editor and create a new file named `docker-compose.dev.yml`. Copy and paste the following commands into the file.
```yaml
version: '3.8'
services:
petclinic:
build:
context: .
ports:
- 8000:8000
- 8080:8080
environment:
- SERVER_PORT=8080
- MYSQL_URL=jdbc:mysql://mysqlserver/petclinic
volumes:
- ./:/app
command: ./mvnw spring-boot:run -Dspring-boot.run.profiles=mysql -Dspring-boot.run.jvmArguments="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000"
mysqlserver:
image: mysql:8.0.23
ports:
- 3306:3306
environment:
- MYSQL_ROOT_PASSWORD=
- MYSQL_ALLOW_EMPTY_PASSWORD=true
- MYSQL_USER=petclinic
- MYSQL_PASSWORD=petclinic
- MYSQL_DATABASE=petclinic
volumes:
- mysql_data:/var/lib/mysql
- mysql_config:/etc/mysql/conf.d
volumes:
mysql_data:
mysql_config:
```
This Compose file is super convenient as we do not have to type all the parameters to pass to the `docker run` command. We can declaratively do that using a Compose file.
We expose port 8000 and declare the debug configuration for the JVM so that we can attach a debugger.
Another really cool feature of using a Compose file is that we have service resolution set up to use the service names. Therefore, we are now able to use `mysqlserver` in our connection string. The reason we use `mysqlserver` is because that is what we've named our MySQL service as in the Compose file.
Now, to start our application and to confirm that it is running properly.
```console
$ docker-compose -f docker-compose.dev.yml up --build
```
We pass the `--build` flag so Docker will compile our image and then starts the containers. You should see similar output if it runs successfully:
![Java Compose output](images/java-compose-output.png)
Now lets test our API endpoint. Run the following curl commands:
```console
$ curl --request GET \
--url http://localhost:8080/vets \
--header 'content-type: application/json'
```
You should receive the following response:
```json
{"vetList":[{"id":1,"firstName":"James","lastName":"Carter","specialties":[],"nrOfSpecialties":0,"new":false},{"id":2,"firstName":"Helen","lastName":"Leary","specialties":[{"id":1,"name":"radiology","new":false}],"nrOfSpecialties":1,"new":false},{"id":3,"firstName":"Linda","lastName":"Douglas","specialties":[{"id":3,"name":"dentistry","new":false},{"id":2,"name":"surgery","new":false}],"nrOfSpecialties":2,"new":false},{"id":4,"firstName":"Rafael","lastName":"Ortega","specialties":[{"id":2,"name":"surgery","new":false}],"nrOfSpecialties":1,"new":false},{"id":5,"firstName":"Henry","lastName":"Stevens","specialties":[{"id":1,"name":"radiology","new":false}],"nrOfSpecialties":1,"new":false},{"id":6,"firstName":"Sharon","lastName":"Jenkins","specialties":[],"nrOfSpecialties":0,"new":false}]}
```
## Connect a Debugger
Well use the debugger that comes with the IntelliJ IDEA. You can use the community version of this IDE. Open your project in IntelliJ IDEA and then go to the **Run** menu > **Edit Configuration**. Add a new Remote JVM Debug configuration similar to the following:
![Java Connect a Debugger](images/connect-debugger.png)
Let's set a breakpoint
Open the following file `src/main/java/org/springframework/samples/petclinic/vet/VetController.java` and add a breakpoint inside the `showResourcesVetList` function, line 54 for example.
Start your debug session, **Run** menu and then **Debug _NameOfYourConfiguration_**
![Debug menu](images/debug-menu.png)
You should now see the connection in the logs of your Compose application.
![Compose log file ](images/compose-logs.png)
We can now call the server endpoint.
```console
$ curl --request GET --url http://localhost:8080/vets
```
You should have seen the code break on line 54 and now you are able to use the debugger just like you would normally. You can also inspect and watch variables, set conditional breakpoints, view stack traces and a do bunch of other stuff.
![Debugger code breakpoint](images/debugger-breakpoint.png)
You can also activate the live reload option provided by SpringBoot Dev Tools. Check out the [SpringBoot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-devtools-remote){:target="_blank" rel="noopener" class="_"} for information on how to connect to a remote application.
## Next steps
In this module, we took a look at creating a general development image that we can use pretty much like our normal command line. We also set up our Compose file to expose the debugging port and configure Spring Boot to live reload our changes.
In the next module, well take a look at how to run unit tests in Docker. See
[Run your tests](run-tests.md){: .button .primary-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.

Binary file not shown.

After

Width:  |  Height:  |  Size: 740 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 751 KiB

View File

@ -1,20 +1,25 @@
--- ---
description: Containerize Java apps using Docker title: Getting started with Java
keywords: Docker, getting started, java, language keywords: Docker, getting started, java, language
title: What will you learn in this module? description: Containerize Java apps using Docker
toc_min: 1 toc_min: 1
toc_max: 2 toc_max: 2
--- ---
> ### Coming soon The Java getting started guide teaches you how to create a containerized Spring Boot application using Docker. In this module, youll learn how to:
>
> Thanks for your interest in learning how to containerize a Java application. We are actively writing this guide. Watch this space!
Meanwhile, here's an outline of the tasks we are planning to cover. Here's an outline of what we'd like to cover. Using the Java getting started guide, you'll learn how to:
* Clone and run a Spring Boot application with Maven
* Create a new Dockerfile which contains instructions required to build a Java image * Create a new Dockerfile which contains instructions required to build a Java image
* Build an image and run the newly built image as a container * Run the newly built image as a container
* Set up a local development environment to connect a database to the container, and use Docker Compose to run the application. * Set up a local development environment to connect a database to the container
* Configure a CI/CD pipeline for your application using GitHub Actions. * Use Docker Compose to run the Spring Boot application
* Configure a CI/CD pipeline for your application using GitHub Actions
* Deploy your application to the cloud
After completing the Java getting started modules, you should be able to containerize your own Java application based on the examples and instructions provided in this guide.
Lets get started!
[Build your first Java image](build-images.md){: .button .primary-btn}
<br /> <br />

8
language/java/nav.html Normal file
View File

@ -0,0 +1,8 @@
<ul class="pagination">
<li {% if include.selected=="1"%}class="active"{% endif %}><a href="/language/java/build-images/">Build images</a></li>
<li {% if include.selected=="2"%}class="active"{% endif %}><a href="/language/java/run-containers/">Run your image as a container</a></li>
<li {% if include.selected=="3"%}class="active"{% endif %}><a href="/language/java/develop/">Use containers for development</a></li>
<li {% if include.selected=="4"%}class="active"{% endif %}><a href="/language/java/run-tests/">Run tests</a></li>
<li {% if include.selected=="5"%}class="active"{% endif %}><a href="/language/java/configure-ci-cd/">Configure CI/CD</a></li>
<li {% if include.selected=="6"%}class="active"{% endif %}><a href="/language/java/deploy/">Deploy your app</a></li>
</ul>

View File

@ -0,0 +1,185 @@
---
title: "Run your image as a container"
keywords: Java, run, image, container,
description: Learn how to run the image as a container.
---
{% include_relative nav.html selected="2" %}
## Prerequisites
Work through the steps to build a Java image in [Build your Java image](build-images.md).
## Overview
In the previous module, we created our sample application and then we created a Dockerfile that we used to build an image. We created our image using the command `docker build`. Now that we have an image, we can run that image and see if our application is running correctly.
A container is a normal operating system process except that this process is isolated and has its own file system, its own networking, and its own isolated process tree separated from the host.
To run an image inside a container, we use the `docker run` command. The `docker run` command requires one parameter which is the name of the image. Lets start our image and make sure it is running correctly. Run the following command in your terminal:
```console
$ docker run java-docker
```
After running this command, youll notice that we did not to the command prompt. This is because our application is a REST server and runs in a loop waiting for incoming requests without returning control back to the OS until we stop the container.
Lets open a new terminal then make a `GET` request to the server using the `curl` command.
```console
$ curl --request GET \
--url http://localhost:8080/actuator/health \
--header 'content-type: application/json'
curl: (7) Failed to connect to localhost port 8080: Connection refused
```
As you can see, our `curl` command failed because the connection to our server was refused. This means, we were not able to connect to the localhost on port 8080. This is expected because our container is run in isolation which includes networking. Lets stop the container and restart with port 8080 published on our local network.
To stop the container, press `ctrl-c`. This will return you to the terminal prompt.
To publish a port for our container, well use the `--publish flag` (`-p` for short) on the `docker run` command. The format of the `--publish` command is `[host port]:[container port]`. So, if we wanted to expose port 8000 inside the container to port 8080 outside the container, we would pass `8080:8000` to the `--publish` flag.
Start the container and expose port 8080 to port 8080 on the host.
```console
$ docker run --publish 8080:8080 java-docker
```
Now, lets rerun the curl command from above.
```console
$ curl --request GET \
--url http://localhost:8080/actuator/health \
--header 'content-type: application/json'
{"status":"UP"}
```
Success! We were able to connect to the application running inside of our container on port 8080.
Now, press ctrl-c to stop the container.
## Run in detached mode
This is great so far, but our sample application is a web server and we don't have to be connected to the container. Docker can run your container in detached mode or in the background. To do this, we can use the `--detach` or `-d` for short. Docker starts your container as earlier, but this time, it will “detach” from the container and return you to the terminal prompt.
```console
$ docker run -d -p 8080:8080 java-docker
5ff83001608c7b787dbe3885277af018aaac738864d42c4fdf5547369f6ac752
```
Docker started our container in the background and printed the Container ID on the terminal.
Again, lets make sure that our container is running properly. Run the same curl command from above.
```console
$ curl --request GET \
--url http://localhost:8080/actuator/health \
--header 'content-type: application/json'
{"status":"UP"}
```
## List containers
As we ran our container in the background, how do we know if our container is running, or what other containers are running on our machine? Well, we can run the `docker ps` command. Just like how we run the `ps` command in Linux to see a list of processes on our machine, we can run the `docker ps` command to view a list of containers running on our machine.
```console
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5ff83001608c java-docker "./mvnw spring-boot:…" About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp trusting_beaver
```
The `docker ps` command provides a bunch of information about our running containers. We can see the container ID, the image running inside the container, the command that was used to start the container, when it was created, the status, ports that exposed and the name of the container.
You are probably wondering where the name of our container is coming from. Since we didnt provide a name for the container when we started it, Docker generated a random name. Well fix this in a minute, but first we need to stop the container. To stop the container, run the `docker stop` command which does just that, stops the container. We need to pass the name of the container or we can use the container ID.
```console
$ docker stop trusting_beaver
trusting_beaver
```
Now, rerun the `docker ps` command to see a list of running containers.
```console
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
```
## Stop, start, and name containers
You can start, stop, and restart Docker containers. When we stop a container, it is not removed, but the status is changed to stopped and the process inside the container is stopped. When we ran the `docker ps` command in the previous module, the default output only shows running containers. When we pass the `--all` or `-a` for short, we see all containers on our machine, irrespective of their start or stop status.
```console
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5ff83001608c java-docker "./mvnw spring-boot:…" 5 minutes ago Exited (143) 18 seconds ago trusting_beaver
630f2872ddf5 java-docker "./mvnw spring-boot:…" 11 minutes ago Exited (1) 8 minutes ago modest_khayyam
a28f9d587d95 java-docker "./mvnw spring-boot:…" 17 minutes ago Exited (1) 11 minutes ago lucid_greider
```
You should now see several containers listed. These are containers that we started and stopped, but have not been removed.
Lets restart the container that we just stopped. Locate the name of the container we just stopped and replace the name of the container below using the `restart` command.
```console
$ docker restart trusting_beaver
```
Now, list all the containers again using the `docker ps` command.
```console
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5ff83001608c java-docker "./mvnw spring-boot:…" 10 minutes ago Up 2 seconds 0.0.0.0:8080->8080/tcp trusting_beaver
630f2872ddf5 java-docker "./mvnw spring-boot:…" 16 minutes ago Exited (1) 13 minutes ago modest_khayyam
a28f9d587d95 java-docker "./mvnw spring-boot:…" 22 minutes ago Exited (1) 16 minutes ago lucid_greider
```
Notice that the container we just restarted has been started in detached mode and has port 8080 exposed. Also, observe the status of the container is “Up X seconds”. When you restart a container, it starts with the same flags or commands that it was originally started with.
Now, lets stop and remove all of our containers and take a look at fixing the random naming issue. Find the name of your running container and replace the name in the command below with the name of the container on your system.
```console
$ docker stop trusting_beaver
trusting_beaver
```
Now that our container is stopped, lets remove it. When you remove a container, the process inside the container will be stopped and the metadata for the container will been removed.
To remove a container, simple run the `docker rm` command passing the container name. You can pass multiple container names to the command using a single command. Again, replace the container names in the following command with the container names from your system.
```console
$ docker rm trusting_beaver modest_khayyam lucid_greider
trusting_beaver
modest_khayyam
lucid_greider
```
Run the `docker ps --all` command again to see that all containers are removed.
Now, lets address the random naming issue. The standard practice is to name your containers for the simple reason that it is easier to identify what is running in the container and what application or service it is associated with.
To name a container, we just need to pass the `--name` flag to the `docker run` command.
```console
$ docker run --rm -d -p 8080:8080 --name springboot-server java-docker
2e907c68d1c98be37d2b2c2ac6b16f353c85b3757e549254de68746a94a8a8d3
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2e907c68d1c9 java-docker "./mvnw spring-boot:…" 8 seconds ago Up 8 seconds 0.0.0.0:8080->8080/tcp springboot-server
```
Thats better! We can now easily identify our container based on the name.
## Next steps
In this module, we took a look at running containers, publishing ports, and running containers in detached mode. We also took a look at managing containers by starting, stopping, and, restarting them. We also looked at naming our containers so they are more easily identifiable.
In the next module, well learn how to run a database in a container and connect it to our application. See:
[Use containers for development](develop.md){: .button .primary-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

217
language/java/run-tests.md Normal file
View File

@ -0,0 +1,217 @@
---
title: "Run your tests"
keywords: Java, build, test
description: How to build and run your Tests
---
{% include_relative nav.html selected="4" %}
## Prerequisites
Work through the steps to build an image and run it as a containerized application in [Use your container for development](develop.md).
## Introduction
Testing is an essential part of modern software development. Testing can mean a lot of things to different development teams. There are unit tests, integration tests and end-to-end testing. In this guide we take a look at running your unit tests in Docker.
## Refactor Dockerfile to run tests
The **Spring Pet Clinic** source code has already tests defined in the test directory `src/test/java/org/springframework/samples/petclinic`. You just need to update the JaCoCo version in your `pom.xml` to ensure your tests work with JDK v15 or higher with `<jacoco.version>0.8.6</jacoco.version>`, so we can use the following Docker command to start the container and run tests:
```shell
$ docker run -it --rm --name springboot-test java-docker ./mvnw test
...
[INFO] Results:
[INFO]
[WARNING] Tests run: 40, Failures: 0, Errors: 0, Skipped: 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:49 min
```
### Multi-stage Dockerfile for testing
Lets take a look at pulling the testing commands into our Dockerfile. Below is a multi-stage Dockerfile that we will use to build our production image and our test image. Add the highlighted lines to your Dockerfile
```dockerfile
# syntax=docker/dockerfile:1
FROM openjdk:16-alpine3.13 as base
WORKDIR /app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY src ./src
FROM base as test
CMD ["./mvnw", "test"]
FROM base as development
CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.profiles=mysql", "-Dspring-boot.run.jvmArguments='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000'"]
FROM base as build
RUN ./mvnw package
FROM openjdk:11-jre-slim as production
EXPOSE 8080
COPY --from=build /app/target/spring-petclinic-*.jar /spring-petclinic.jar
CMD ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/spring-petclinic.jar"]
```
We first add a label to the `FROM openjdk:16-alpine3.13` statement. This allows us to refer to this build stage in other build stages. Next, we added a new build stage labeled `test`. We'll use this stage for running our tests.
Now lets rebuild our image and run our tests. We will run the `docker build` command as above, but this time we will add the `--target test` flag so that we specifically run the test build stage.
```shell
$ docker build -t java-docker --target test .
[+] Building 0.7s (6/6) FINISHED
...
=> => writing image sha256:967ac80cb7799a5d12a4bdfc67c37b5a6533c6e418c903907d3e86b7d4ebf89a
=> => naming to docker.io/library/java-docker
```
Now that our test image is built, we can run it as a container and see if our tests pass.
```shell
$ docker run -it --rm --name springboot-test java-docker
[INFO] Scanning for projects...
[INFO]
[INFO] ------------< org.springframework.samples:spring-petclinic >------------
[INFO] Building petclinic 2.4.2
...
[INFO] Results:
[INFO]
[WARNING] Tests run: 40, Failures: 0, Errors: 0, Skipped: 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:22 min
```
The build output is truncated, but you can see that the Maven test runner was successful and all our tests passed.
This is great. However, we'll have to run two Docker commands to build and run our tests. We can improve this slightly by using a `RUN` statement instead of the `CMD` statement in the test stage. The `CMD` statement is not executed during the building of the image, but is executed when you run the image in a container. When using the `RUN` statement, our tests run when the building the image, and stop the build when they fail.
Update your Dockerfile with the highlighted line below.
```dockerfile
# syntax=docker/dockerfile:1
FROM openjdk:16-alpine3.13 as base
WORKDIR /app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY src ./src
FROM base as test
RUN ["./mvnw", "test"]
FROM base as development
CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.profiles=mysql", "-Dspring-boot.run.jvmArguments='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000'"]
FROM base as build
RUN ./mvnw package
FROM openjdk:11-jre-slim as production
EXPOSE 8080
COPY --from=build /app/target/spring-petclinic-*.jar /spring-petclinic.jar
CMD ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/spring-petclinic.jar"]
```
Now, to run our tests, we just need to run the `docker build` command as above.
```shell
$ docker build -t java-docker --target test .
[+] Building 27.6s (11/12)
=> CACHED [base 3/6] COPY .mvn/ .mvn
=> CACHED [base 4/6] COPY mvnw pom.xml ./
=> CACHED [base 5/6] RUN ./mvnw dependency:go-offline
=> CACHED [base 6/6] COPY src ./src
=> [test 1/1] RUN ["./mvnw", "test", "-Dspring-boot.run.profiles=mysql"]
=> exporting to image
=> => exporting layers
=> => writing image sha256:10cb585a7f289a04539e95d583ae97bcf8725959a6bd32c2f5632d0e7c1d16a0
=> => naming to docker.io/library/java-docker
```
The build output is truncated for simplicity, but you can see that our tests ran succesfully and passed. Lets break one of the tests and observe the output when our tests fail.
Open the `src/test/java/org/springframework/samples/petclinic/model/ValidatorTests.java` file and change **line 57** to the following.
```shell
55 ConstraintViolation<Person> violation = constraintViolations.iterator().next();
57 assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
57 assertThat(violation.getMessage()).isEqualTo("must be empty");
58 }
```
Now, run the `docker build` command from above and observe that the build fails and the failing testing information is printed to the console.
```shell
$ docker build -t java-docker --target test .
=> [base 6/6] COPY src ./src
=> ERROR [test 1/1] RUN ["./mvnw", "test", "-Dspring-boot.run.profiles=mysql"]
...
------
executor failed running [./mvnw test]: exit code: 1
```
### Multi-stage Dockerfile for development
The new version of the Dockerfile produces a final image which is ready for production, but as you can notice, you also have a dedicated step to produce a development container.
```dockerfile
FROM base as development
CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.profiles=mysql", "-Dspring-boot.run.jvmArguments='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000'"]
```
We can now update of our `docker-compose.dev.yml` to use this specific target to build the `petclinic` service and remove the `command` definition as follows:
```dockerfile
services:
petclinic:
build:
context: .
target: development
ports:
- 8000:8000
- 8080:8080
environment:
- SERVER_PORT=8080
- MYSQL_URL=jdbc:mysql://mysqlserver/petclinic
volumes:
- ./:/app
```
Now, let's run the Compose application. You should now see that application behaves as previously and you can still debug it.
```shell
$ docker-compose -f docker-compose.dev.yml up --build
```
## Next steps
In this module, we took a look at running tests as part of our Docker image build process.
In the next module, well take a look at how to set up a CI/CD pipeline using GitHub Actions. See:
[Configure CI/CD](configure-ci-cd.md){: .button .primary-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs](https://github.com/docker/docker.github.io/issues/new?title=[Java%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />