Day 29: Hands-On with Docker – Build Your First Java Project Container from Scratch Using Dockerfile.
Today, we dive into one of the core concepts of Docker: understanding what a Dockerfile, Docker Image, and Container are, along with a real-life analogy (Maggi 😋) and practical demo to make things super easy to follow.
What is a Dockerfile, Image, and Container?
Let’s break it down:
Real-Life Example: Let’s Understand with Maggi
Just like we cook Maggi:
Practical Demo: Let's Get Started
Step 1: Login to Docker Hub
Before we can pull or push any Docker images, we need to log into Docker Hub.
docker login
Note: Sometimes the password doesn’t work. In that case, go to your Docker Hub account settings and create a personal access token to use instead of your password.
Step 2: Pull the hello-world Image
Let’s start with a very basic Docker image:
docker pull hello-world
Now check if the image was pulled successfully:
docker images
Step 3: Run the Image to Create a Container
Now run the pulled image:
docker run hello-world
This will create and run a container based on the hello-world image.
Step 4: Try a Server Image - MySQL
Let’s now pull a server-based image like MySQL:
docker pull mysql
Again, confirm it:
docker images
To run the MySQL image (which requires a root password), use:
docker run -d -e MYSQL_ROOT_PASSWORD=root mysql
Then check if the container is running:
docker ps
Now Let’s Create Our Own Dockerfile and Build a Container
We’ll now take a sample Java project from GitHub and create a Docker container for it.
Step 5: Setup Project Folder
First, create a new directory:
mkdir java-project cd java-project
Clone a Java project
git clone <your-java-project-link>
Step 6: Create a Dockerfile
Inside the project folder, create a Dockerfile:
vim Dockerfile
Example Dockerfile content
This Dockerfile sets up a basic Java environment and tells Docker how to run your project.
Step 7: Build the Docker Image
Now let’s build the Docker image using our Dockerfile:
docker build -t java-app .
Step 8: Run the Container
Once the image is built, run it:
docker run java-app
This will execute your Java project inside a Docker container.