Running your Java project in a Docker container ensures a consistent environment and simplifies deployment. In this guide, I will walk you through the process of setting up Docker for a Java project. Follow these steps to get your Java application up and running in no time!
Step 1: Clone the GitHub Repository
Start by cloning the GitHub repository containing your Java project:
git clone https://github.com/LondheShubham153/simple-java-docker.git
Step 2: Remove the Old Dockerfile
If there's an existing Dockerfile, remove it:
rm Dockerfile
Step 3: Show Main.java File
Ensure you have a Main.java file in the appropriate directory. You can use cat or less to display it:
cat javapr/src/Main.java
Adjust the path according to your project's structure.
Step 4: Create a New Dockerfile
Create a new Dockerfile using vim or any other text editor:
vim Dockerfile
Step 5: Write Docker Code
Write the following Docker code in your Dockerfile:
# OS with env
FROM openjdk:17-jdk-alpine
# Working Dir
WORKDIR /app
# Code
COPY src/Main.java /app/Main.java
# Libraries
RUN javac Main.java
#Run
CMD ["java","Main"]
Save and exit the editor (:wq in vim).
Step 6: Build the Docker Image
Build your Docker image using the following command:
docker build -t java-app .
Step 7: List Docker Images
Verify that the Docker image was created successfully:
docker images
Step 8: Run the Docker Container
Finally, run a container using the newly created Docker image:
docker run java-app:latest