NewRelic and Spring Boot with Gradle

Originally published on Medium.

The goal: integrate the NewRelic monitoring agent into a Dockerized Spring Boot REST application. I wanted to avoid two things — checking the agent JAR into the codebase, and baking it into a base Docker image. The solution is to pull it as a Gradle dependency and copy it into the build output before Docker picks it up.

The Setup

Three pieces work together: a Gradle configuration, a copy task, and the Dockerfile entry point.

1. Gradle Configuration

Declare a separate newRelic configuration so the agent doesn’t bleed into your regular compile or runtime classpaths, then add a copyNewRelic task that extracts the JAR into build/libs — the same directory your Spring Boot fat JAR lands in.

configurations {
  // other configurations if any...
  newRelic
}

dependencies {
  newRelic group: 'com.newrelic.agent.java', name: 'newrelic-agent', version: '3.44.1'
}

task copyNewRelic(type: Copy) {
    from configurations.newRelic
    into "${project.buildDir}/libs"
    rename { it.substring(0, it.indexOf("-")) + it.substring(it.lastIndexOf("."), it.size()) }
}

assemble.dependsOn copyNewRelic

The rename closure strips the version number from the JAR filename — so newrelic-agent-3.44.1.jar becomes newrelic.jar — which is what the Dockerfile expects.

2. newrelic.yml

Place newrelic.yml in the root directory of the application. It will be copied into the Docker image alongside the agent JAR.

3. Dockerfile

WORKDIR /deploy

EXPOSE 8080

ENTRYPOINT java -javaagent:newrelic.jar -Dspring.profiles.active=${PROFILES} -jar application.jar

COPY --from=builder /source/build/libs/* ./
COPY --from=builder /source/newrelic.yml ./

The multi-stage build keeps the final image lean. Both the application JAR and newrelic.jar (built by the copyNewRelic task) land in build/libs/*, so a single COPY line brings them both across.

Why This Way?

  • No agent JAR in source control
  • No special base image required
  • Agent version is controlled in build.gradle like any other dependency
  • Works cleanly with CI — gradle assemble handles everything

Open to better approaches if anyone has them.