0
0
Spring Bootframework~5 mins

Dockerfile for Spring Boot in Spring Boot

Choose your learning style9 modes available
Introduction

A Dockerfile helps package your Spring Boot app into a container. This makes it easy to run your app anywhere without setup hassles.

You want to share your Spring Boot app with others who don't have Java installed.
You need to deploy your app to cloud services that use containers.
You want to test your app in a clean environment every time.
You want to run multiple versions of your app without conflicts.
You want to automate app deployment with consistent environments.
Syntax
Spring Boot
FROM openjdk:17-jdk-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

FROM sets the base image with Java installed.

COPY moves your built app jar into the container.

ENTRYPOINT runs your app when the container starts.

Examples
Basic Dockerfile copying a specific jar file and running it.
Spring Boot
FROM openjdk:17-jdk-slim
COPY target/myapp.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
Uses an argument to copy any jar file from target folder, useful if jar name changes.
Spring Boot
FROM openjdk:17-jdk-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
Adds EXPOSE to tell Docker the app listens on port 8080.
Spring Boot
FROM openjdk:17-jdk-slim
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
Sample Program

This Dockerfile creates a container image for your Spring Boot app. It uses Java 17, copies your built jar, exposes port 8080, and runs the app.

Spring Boot
FROM openjdk:17-jdk-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
OutputSuccess
Important Notes

Make sure your Spring Boot app is built (e.g., with ./mvnw package) before building the Docker image.

The EXPOSE instruction does not publish the port but documents it; use -p flag when running the container to map ports.

Use docker build -t myapp . to build and docker run -p 8080:8080 myapp to run your container.

Summary

A Dockerfile packages your Spring Boot app with Java into a container.

Use FROM, COPY, EXPOSE, and ENTRYPOINT to define the container.

Build your app first, then build and run the Docker image to run your app anywhere.