Docker Community Forums

Share and learn in the Docker community.

Dockerfile VOLUME

I am trying to better understand what VOLUME directive works.
Here is an Docker example that works:
FROM openjdk:7

WORKDIR /usr/src/apps
COPY ./src /usr/src/apps
RUN javac Hello.java
CMD [“java”, “Hello”]

Here is an equivalent Dockerfile that does NOT work: Why?
FROM openjdk:7

WORKDIR /usr/src/apps
COPY ./src /usr/src/apps
VOLUME /usr/src/apps
RUN javac Hello.java
CMD [ “java”, “Hello” ]

When I build and run the image in a container I get this:
Sending build context to Docker daemon 23.55kB
Step 1/6 : FROM openjdk:7
—> d735a2057e60
Step 2/6 : WORKDIR /usr/src/apps
—> Using cache
—> e2edf0b3b5c8
Step 3/6 : COPY ./src /usr/src/apps
—> Using cache
—> 639b1ebc7a1a
Step 4/6 : VOLUME /usr/src/apps
—> Running in c60f4fe287db
Removing intermediate container c60f4fe287db
—> fd900d528141
Step 5/6 : RUN javac Hello.java
—> Running in cdfb259fb70f
Removing intermediate container cdfb259fb70f
—> 66750ad94f0f
Step 6/6 : CMD [ “java”, “Hello” ]
—> Running in d67329238ce4
Removing intermediate container d67329238ce4
—> eaed5343512f
Successfully built eaed5343512f
Successfully tagged demo:latest

sudo docker run --name demo_1 -it demo
Error: Could not find or load main class Hello

But if I change the Dockerfile to:
FROM openjdk:7

WORKDIR /usr/src/apps
COPY ./src /usr/src/apps
RUN javac Hello.java
VOLUME /usr/src/apps
CMD [ “java”, “Hello” ]

Here is the result! Why?
1st run: WORKS
sudo docker run --name demo_1 -it demo
Hello, World
This is my first java Application

2nd run: FAILS
sudo docker run --name demo_2 -it -v $PWD/src:/usr/src/apps demo
Error: Could not find or load main class Hello