How to run a Gradle Java project in Docker?

I have a simple Java server project with a build.gradle script. gradle run runs perfectly on my laptop. I create a simple Dockerfile for this

FROM gradle:4.3-jdk-alpine
ADD . /code
CMD ["gradle", "--stacktrace", "run"]

Is there a better way to Dockerize a Gradle project?

I build it with docker build -t my-server-app .

Then I run with docker run --rm my-server-app

The error I get is:

Caused by: org.gradle.api.UncheckedIOException: Failed to create parent directory '/code/.gradle/4.3' when creating directory '/code/.gradle/4.3/fileHashes'
	at org.gradle.util.GFileUtils.mkdirs(

Obviously, the docker container should be running as root. Why would I get this error?

It’s not, as the base image you’re using, gradle:4.3-jdk-alpine, declares that the process should be run as user gradle. You can overwrite that in your own Dockerfile or use ADD --chown=gradle . /code to match what the base image is already expecting.