Dockerfile
Dockerfile is a set of instructions (a blueprint) used to create a Docker Image. Docker Image is a package used to create a Docker Container. Docker Container is a running instance of the Docker Image.
Dockerfile → Docker Image → Docker Container
How to make or What Dockerfile contains :
In this tutorial, we will build a Dockerfile for a simple java project. A project that prints "Hello, Docker! Current date: ". This simple code is by Shubham Londhe . Repository Link : https://github.com/LondheShubham153/simple-java-docker.git Clone it and practice making Dockerfile, read and follow this tutorial. NOTE : If Dockerfile is already in this repository, delete it try to make on your own.
Base Image (Environment)
First we need Base Image (Environment) so here we use openjdk:17-jdk-alpine
because the application is in Java.
FROM openjdk:17-jdk-alpine
openjdk
is image name for Java 17
is a version of Java jdk-alpine
is a image tag (alpine is a lightweight version of image)
NOTE : The choice of Base Image is depends on requirement of application or what your Developer specifies.
Working Directory
Then we need a directory known as Working Directory where the application’s file will be copied and executed. We made directory name as app, you can give any name you want. This helps container to have organized file structure.
WORKDIR /app
Copy the Code
After this we need a code, so we copy the code from wherever it is present to the Working Directory we made and give it a name. In our case code Main.java is in src directory. This allows container to access the code for Compilation and Execution.
COPY /src/Main.java /app/Main.java
Dependencies and Compilation
We need some dependencies or libraries to run the code, the code is in java so we use javac
(Java compiler) to run the Main.java
file
RUN javac Main.java
Execution command
Dockerfile specifies a CMD or ENTRYPOINT. This command ensure the container to run the application when started
CMD ["java","Main"]
Here’s the Dockerfile script
Now you have Dockerfile along with src in your project’s directory
Now make the Docker Image
docker build -t java-app .
docker build
is used to create a Docker Image -t
means tag & java-app
is a tag name .
is used because Dockerfile is in current directory only
If you see docker images
java-app image is created, Lets run this by
docker run java-app:latest
You can see it runs and prints the Hello, Docker! Current date: <date>
NOTE : If you have an app with graphical interface, will cover that topic in Docker Container Blog, so follow and stay updated. That’s all about Dockerfile ! Practice it on your system, Follow and keep learning with us.
LinkedIn | GitHub | Hashnode
Subscribe to my newsletter
Read articles from Saad Asif Mujawar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by