Dockerizing a Spring Boot application involves creating a Docker image that contains your application and its dependencies, allowing you to run the application in a containerized environment. Here’s a step-by-step guide on how to Dockerize a Spring Boot application:
Step 1: Install Docker
Make sure Docker is installed on your machine. You can download it from the official Docker website: Docker Downloads
Step 2: Create a Dockerfile
Create a file named
Dockerfile in the root of your Spring Boot project. This file contains instructions on how to build the Docker image.
# Use the official OpenJDK base image
# Set the working directory inside the container
# Copy the JAR file into the container at /app
COPY target/your-spring-boot-app.jar /app/your-spring-boot-app.jar
# Expose the port that your application will run on
# Specify the command to run your application
CMD [“java”, “-jar”, “your-spring-boot-app.jar”]
your-spring-boot-app.jar with the actual name of your Spring Boot JAR file.
Step 3: Build the Docker Image
Open a terminal, navigate to the directory containing your
Dockerfile, and run the following command:
docker build -t your-docker-image-name .
your-docker-image-name with the desired name for your Docker image.
Step 4: Run the Docker Container
After building the Docker image, you can run a container based on that image:
docker run -p 8080:8080 your-docker-image-name
This command maps port 8080 from the container to port 8080 on your host machine. Adjust the ports as needed.
- If the app that runs inside accesses outside environment, you will need to point it with “host.docker.internal” instead of “localhost”.
- Make sure your Spring Boot application is configured to use an externalized configuration. You can use environment variables or configuration files outside the JAR for this purpose.
- Consider using a multi-stage Dockerfile to reduce the size of your Docker image by building the application in one stage and packaging it in a minimal runtime image in the next stage.