Containerizing my Spring Boot Application with Docker

September 13, 2024 (3mo ago)

tech

hello

Welcome to my first offcial article! I just wanted to talk about what the things I learned while trying to containerize my spring boot application with Docker.

I am containerizing my application in Docker to be able to use a vps (virtual private server) to be able to host my backend. The reason why I want to do this versus just deploying through the vps is because with Docker you are able to have the same enviroment no matter the machine. This gets rid of any problems of the deployment software working on one machine but not another.

To start, inside my IDE (Intellij), I went into the Maven settings and under Lifecycle, I cleaned the project (removes the prebuilt version of the application (could be outdated versions running. )) then I installed the project, which gave me a target folder. Inside that target folder should be two jar files.

Now we create our Dockerfile. I had to download the application from the offical website for the dockerfile to work (Docker App Download). Inside the docker file, these are the instructions I put inside the file

# Base image used to create the java 17 runtime environment for my app
FROM eclipse-temurin:17

# Define an argument for the JAR file location (not used in this snippet)
ARG JAR_FILE=target/*.jar

# Copies JAR file into Docker image -> root directory of the container app.jar
COPY ./target/<filename>.jar app.jar

# set command to be executed: uses java to run JAR file, -jar tells java to run a jar file. /app.jar is the path to JAR file in container
ENTRYPOINT ["java","-jar","/app.jar"]

We use eclipse temurin because openjdk is being depreciated and I couldn't get it to work on my system (ARM).

To run the docker file, we use the command docker build -t <whatever you want to name your container>:latest in the terminal in the path where our folder is at.

To get back the information of the container, we use the command docker container ls.

To run the container, we use the command docker run -p 8000:8080 <container name>.

To run the container in the background or dormant mode, we use the command docker run -d -p 8000:8080 <container name>.

To get running container info, we use the command docker container ls.

To remove the container, we can use the command docker rm -f <container id>.