- 1 year ago
Create a Docker File and Building a Docker-Image with maven and spring-boot on Windows
To create a Dockerfile and build a Docker image with Maven and Spring Boot on Windows, follow these steps:
Install Docker: Download and install Docker Desktop for Windows from the official Docker website (https://www.docker.com/products/docker-desktop).
Create a Dockerfile: Create a new file called
Dockerfile
(without any file extension) in the root directory of your Spring Boot project.Open the Dockerfile in a text editor and add the following content:
Dockerfile# Use a base image with Java and Maven pre-installed
FROM maven:3.8.3-openjdk-11-slim AS build
# Set the working directory in the container
WORKDIR /app
# Copy the Maven project files to the container
COPY pom.xml .
# Download the Maven dependencies (this layer will be cached if the pom.xml file hasn't changed)
RUN mvn dependency:go-offline -B
# Copy the source code to the container
COPY src ./src
# Build the application
RUN mvn package -DskipTests
# Create a new stage for the final image
FROM openjdk:11-jre-slim
# Set the working directory in the container
WORKDIR /app
# Copy the built JAR file from the previous stage to the current stage
COPY --from=build /app/target/*.jar app.jar
# Set the command to run the Spring Boot application
CMD ["java", "-jar", "app.jar"]
Save the Dockerfile.
Build the Docker image:
- Open a command prompt or PowerShell.
- Navigate to the directory where the Dockerfile is located (the root directory of your Spring Boot project).
- Run the following command to build the Docker image:
Replaceperldocker build -t my-spring-boot-app .
my-spring-boot-app
with the desired name for your Docker image.
Wait for the Docker image to be built. This process may take a few minutes, as it downloads the base images and dependencies.
Verify the Docker image:
- Run the following command to see the list of Docker images:
docker images
- You should see your newly built image (
my-spring-boot-app
) listed.
- Run the following command to see the list of Docker images:
Now you have successfully created a Dockerfile and built a Docker image with Maven and Spring Boot on Windows. You can run the image using the docker run
command to start a container with your Spring Boot application.
Note: Make sure that your Spring Boot project is set up correctly and the necessary Maven dependencies and build configurations are in place before building the Docker image.