Welcome!

Blog Feed Post

Multi-stage Docker Image Build for Java Applications

A few days back, I discovered a new Docker feature—multi-stage builds. The multi-stage build feature helps you create thin Docker images by making it possible to divide the image building process into multiple stages. Artifacts produced in one stage can be reused by another stage. This is very beneficial for languages like Java as multiple steps are required to build the Docker image. The main advantage of the multi-stage build feature is that it can help you create smaller size images. This feature is not yet available in stable versions of Docker. It will become available in Docker 17.05. To use this feature, you have to use the edge version of Docker CE.

To build a Docker image for a Java application, you first need to build the Java project. Java build process needs JDK and a build tool like Maven, Gradle, or Ant. Once a Java binary artifact is produded, you can package the binary in a Docker image. For running a Java binary, you only need JRE, so you don’t have to pay the cost of bundling the whole JDK.

One of the ways people have handled the multiple staging builds is by using the Builder pattern. This pattern requires you to have two Dockerfile files — Dockerfile and Dockerfile_build. The Dockerfile_build file will be used to build the Java binary, and Dockerfile will be used to create the final runtime image. Below is the content of the Dockerfile_build file for a Spring Boot Gradle project.

FROM openjdk:8
ENV APP_HOME=/root/dev/myapp/
RUN mkdir -p $APP_HOME/src/main/java
WORKDIR $APP_HOME
COPY build.gradle gradlew gradlew.bat $APP_HOME
COPY gradle $APP_HOME/gradle
# download dependencies
RUN ./gradlew build -x :bootRepackage -x test --continue
COPY . .
RUN ./gradlew build

The above Dockerfile first downloads all the dependencies and then builds the project. Please note that we are copying source code after downloading the dependencies. This allows Docker to reuse the layer that downloaded Gradle dependencies. We will be changing the source code more often so we have kept it later in the Dockerfile.

To create the Java artifact, we will first build a Docker image and then create the container using the commands mentioned below.

$ docker build -t myapp_build -f Dockerfile_build .
$ docker create --name myapp-build-container myapp_build

Now, you have to copy the artifact from the myapp-build-container using the docker cp command and create the final image that will be used for execution.

As you’ll see, it is a tedious process requiring you to maintain multiple Dockerfiles.

https://i1.wp.com/blog.xebialabs.com/wp-content/uploads/2017/05/diving-i... 150w, https://i1.wp.com/blog.xebialabs.com/wp-content/uploads/2017/05/diving-i... 300w, https://i1.wp.com/blog.xebialabs.com/wp-content/uploads/2017/05/diving-i... 768w, https://i1.wp.com/blog.xebialabs.com/wp-content/uploads/2017/05/diving-i... 120w" sizes="(max-width: 256px) 100vw, 256px" data-recalc-dims="1" />

ON DEMAND WEBINAR

Diving into Docker 

What it means for your Enterprise DevOps strategy

What does Docker mean for enterprise IT teams? Dive into this educational webinar and learn what Docker means for your software delivery processes, practical considerations to successfully implement containers as part of your release pipeline, and much more.

Docker Multi-build Feature to the Rescue

With multi-stage builds, a Dockerfile can contain multiple FROM directives. The last FROM directive output is the resultant image. So, now you have to maintain a single Dockerfile that will build the Java artifact in the first stage and then create the final image in the second stage using the artifact produced in the first stage.

FROM openjdk:8 AS BUILD_IMAGE
ENV APP_HOME=/root/dev/myapp/
RUN mkdir -p $APP_HOME/src/main/java
WORKDIR $APP_HOME
COPY build.gradle gradlew gradlew.bat $APP_HOME
COPY gradle $APP_HOME/gradle
# download dependencies
RUN ./gradlew build -x :bootRepackage -x test --continue
COPY . .
RUN ./gradlew build

FROM openjdk:8-jre
WORKDIR /root/
COPY --from=BUILD_IMAGE /root/dev/myapp/build/libs/myapp.jar .
EXPOSE 8080
CMD ["java","-jar","myapp.jar"]

In the Dockerfile shown above,

  1. We have two FROM commands. FROM command can also take an alias name so that you can reference the name later. If you don’t provide an alias, then you can refer using the index starting from 0. There can be more than two stages. The example above uses two stages.
  2. The first FROM command uses openjdk:8 image as the base image as it needs to build the project. The second FROM command uses openjdk:8-jre as it needs to run the binary.
  3. We used the from option of COPY command to copy the artifact produced by first image into the second image. The from option can either use the alias name that you can mention with FROM command or it can be an index starting from 0. For example, if we remove AS BUILD_IMAGE in the first FROM command then we can write COPY command as COPY –from=0 /root/dev/myapp/build/libs/myapp.jar .

To build the image and run the application, you can use standard commands as shown below.

$ docker build -t myapp .
$ docker run -d -p 8080:8080 myapp

The size of the image is drastically small compared to the image used for building the Java binary as shown below.

$ docker images
myapp               latest              45f3dfc8c0bc        10 minutes ago   
325MB
myapp_build         latest              b2115749abff        32 minutes ago    857MB

Conclusion

You should certainly give Docker multi-stage build feature a try for your applications. It can streamline your Docker image building process, helping you maintain fewer Dockerfiles and smaller Docker images.

The post Multi-stage Docker Image Build for Java Applications appeared first on XebiaLabs.

Read the original blog entry...

More Stories By XebiaLabs Blog

XebiaLabs is the technology leader for automation software for DevOps and Continuous Delivery. It focuses on helping companies accelerate the delivery of new software in the most efficient manner. Its products are simple to use, quick to implement, and provide robust enterprise technology.

Latest Stories
For organizations that have amassed large sums of software complexity, taking a microservices approach is the first step toward DevOps and continuous improvement / development. Integrating system-level analysis with microservices makes it easier to change and add functionality to applications at any time without the increase of risk. Before you start big transformation projects or a cloud migration, make sure these changes won’t take down your entire organization.
Automation is enabling enterprises to design, deploy, and manage more complex, hybrid cloud environments. Yet the people who manage these environments must be trained in and understanding these environments better than ever before. A new era of analytics and cognitive computing is adding intelligence, but also more complexity, to these cloud environments. How smart is your cloud? How smart should it be? In this power panel at 20th Cloud Expo, moderated by Conference Chair Roger Strukhoff, paneli...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
SYS-CON Events announced today that TMC has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo and Big Data at Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Global buyers rely on TMC’s content-driven marketplaces to make purchase decisions and navigate markets. Learn how we can help you reach your marketing goals.
Managing mission-critical SAP systems and landscapes has never been easy. Add public cloud with its myriad of powerful cloud native services and this may not change any time soon. Public cloud offers exciting new possibilities for enterprise workloads. But to make use of these possibilities and capabilities, IT teams need to re-think everything they have done before. Otherwise, they will just end up using public cloud as a hosting platform for their workloads, aka known as “lift and shift.”
Cloud promises the agility required by today’s digital businesses. As organizations adopt cloud based infrastructures and services, their IT resources become increasingly dynamic and hybrid in nature. Managing these require modern IT operations and tools. In his session at 20th Cloud Expo, Raj Sundaram, Senior Principal Product Manager at CA Technologies, will discuss how to modernize your IT operations in order to proactively manage your hybrid cloud and IT environments. He will be sharing bes...
Cloud applications are seeing a deluge of requests to support the exploding advanced analytics market. “Open analytics” is the emerging strategy to deliver that data through an open data access layer, in the cloud, to be directly consumed by external analytics tools and popular programming languages. An increasing number of data engineers and data scientists use a variety of platforms and advanced analytics languages such as SAS, R, Python and Java, as well as frameworks such as Hadoop and Spark...
SYS-CON Events announced today that TechTarget has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TechTarget storage websites are the best online information resource for news, tips and expert advice for the storage, backup and disaster recovery markets.
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Published in Silicon Valley, Silicon India magazine is the premiere platform for CIOs to discuss their innovative enterprise solutions and allows IT vendors to learn about new solutions that can help grow their business.
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organi...