This is my "Hello World" of creating my own docker image for running a Java program in Java 7 environment.
You can find information about Docker here. Developers need to understand concepts like Docker, docker-machine and how to write a Dockerfile to be able to create own docker images.
You can find information about Docker here. Developers need to understand concepts like Docker, docker-machine and how to write a Dockerfile to be able to create own docker images.
Create Dockerfile
This is how a Dockerfile for our project would look like:
FROM java:7
MAINTAINER tuhin.gupta@gmail.com
COPY ./src/main/java /usr/src/myjavaapp
WORKDIR /usr/src/myjavaapp
RUN javac com/tuhin/example/Main.java
CMD ["java", "com.tuhin.example.Main"]
see details of Dockerfile syntax here
In our project we are using following instructions:
FROM - tell docker to pull java 7 image
MAINTAINER - instruction allows to set the author field
COPY - instruction is to copy the java source code to docker image file system
WORKDIR - sets the work directory in docker image
RUN - runs javac at the specified location
CMD - this instruction can run any command that can be run from command prompt.
Java code in Main.java is:
package com.tuhin.example;
/**
* @author Tuhin Gupta
*
*/
public class Main {
public static void main(String[] args) {
System.out.println("This is the main class.");
}
}
Build Docker Image
Once the Dockerfile is created, now we need to build the docker image for java application
$ docker build -f <path-to-docker-context>/docker/Dockerfile -t myjavaapp <path-to-docker-context>
Above command will build the docker image.
-f : is used to specify the path to docker file within docker context. Dockerfile must be in docker context.
-t : Repository name (and optionally a tag) for the image
This command will build the docker image and you can view your recently created image using following command:
$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
myjavaapp latest 45a3aacd5bd0 1 hours ago 590.1 MB
Run your Docker Image
To run the newly created image and the java program inside the image, use following command:
$ docker run -t --rm --name test-myjavaapp myjavaapp
This will run myjavaapp image and Main.java class within it.
Save your Docker Image as tar file for sharing
Using following command, you can save a docker image as tar file and share between developers.
$ docker save -o <path-to-save>/myjavaapp.tar <image id>
<image id>: image id from docker images command
Refer to my Github site - https://github.com/tuhingupta/docker-simple-java and download the Dockerfile.
Refer to my Github site - https://github.com/tuhingupta/docker-simple-java and download the Dockerfile.
No comments:
Post a Comment