Nick Anderson Nick Anderson - 3 months ago 20
Java Question

Write to file in Java App running on Docker

Background



I am trying to create a compiler web service, so a user could post code written in some language I made a compiler for, then it would compile, run, and return the printed results. My second iteration involves using Docker images to isolate the running of the code POST'ed into my running web server.

Problem



I am trying to write the posted code to a text file to run my compiler on it, but my compiler is failing on trying to create a file. My file paths should be correct, and my other test route is working. Here is some demo code that I'm trying to run, but fails:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("/raw/compile-source.slacc"), "utf-8"))) {
writer.write(req.body());
}


In my Dockerfile that I'm using to start this, I have created the /raw directory, if it matters. I'm imagining that Docker doesn't want Java processes to create arbitrary files. Any thoughts? Below is my Dockerfile.

My Dockerfile



FROM java:8

# Install maven
RUN apt-get update
RUN apt-get install -y maven

WORKDIR /code

# Prepare by downloading dependencies
ADD pom.xml /code/pom.xml
RUN ["mvn", "dependency:resolve"]
RUN ["mvn", "verify"]

# Adding source, compile and package into a fat jar
ADD src /code/src
RUN ["mvn", "package"]

CMD ["java", "-version"]

CMD ["mkdir", "/raw"]
CMD ["mkdir", "/classfiles"];
CMD ["mkdir", "/out"];
EXPOSE 4567
CMD ["mvn", "exec:java"]

Answer

I had CMD and RUN confused. I only need to have the final

mvn exec:java

in a CMD block, but the others needed to be runs. This is my final output. I also omitted getting scala. :)

FROM java:8

# Install Scala
ENV SCALA_HOME /usr/local/share/scala
ENV PATH $PATH:$SCALA_HOME/bin

ENV SCALA_VERSION 2.11.8

RUN wget --quiet http://downloads.lightbend.com/scala/$SCALA_VERSION/scala-$SCALA_VERSION.tgz && \
tar -xf scala-$SCALA_VERSION.tgz && \
rm scala-$SCALA_VERSION.tgz && \
mv scala-$SCALA_VERSION $SCALA_HOME

# Install maven
RUN apt-get update
RUN apt-get install -y maven

WORKDIR /code

# Prepare by downloading dependencies
ADD pom.xml /code/pom.xml
RUN ["mvn", "dependency:resolve"]
RUN ["mvn", "verify"]

# Adding source, compile and package into a fat jar
ADD src /code/src
RUN ["mvn", "package"]

RUN ["java", "-version"]

RUN ["mkdir", "/raw"]
RUN ["chmod", "a+w", "/raw"]
RUN ["mkdir", "/classfiles"];
RUN ["mkdir", "/out"];
EXPOSE 4567
CMD ["mvn", "exec:java"]

Thank you everyone for responding and helping me out.