Lets try to containerize a java application
Building image from a Java Package
- Steps:
- Ensure Java 21 is installed
- This application uses port 8080
- Command to run this application is
java -jar spring-petclinic-3.3.0-SNAPSHOT.jar
- Context:
- We need to find a base image with java 21 installed. lets choose eclipsetemurin or amazon correto
- Dockerfile-version1
FROM eclipse-temurin:21-alpine
LABEL author=shaikkhajaibrahim
LABEL project=learning
LABEL version=3.3.0
EXPOSE 8080
RUN wget https://referenceappslt.s3.ap-south-1.amazonaws.com/spring-petclinic-3.3.0-SNAPSHOT.jar
CMD ["java", "-jar", "spring-petclinic-3.3.0-SNAPSHOT.jar"]
- Dockerfile instructions
- LABEL
- RUN: Run instruction is used to execute any command during image building
- CMD: This instruction will be used to execute while container is starting (PID 1)
- ADD: Add is similar to copy and it also allows downloding from URLs
- WORKDIR
-
Commands in Dockerfile have two forms
- Shell form:
- we directly write the command
- example
ping -c 4 google.com
- In RUN Instruction we prefer using shell form
- Exec form:
- we enclose the command in square brackets
- example:
[ "ping", "-c", "4", "google.com" ]
- IN CMD/ENTRYPOINT we use Exec form
-
Dockerfile-version2
FROM eclipse-temurin:21-alpine
LABEL author=shaikkhajaibrahim
LABEL project=learning
LABEL version=3.3.0
EXPOSE 8080
ADD https://referenceappslt.s3.ap-south-1.amazonaws.com/spring-petclinic-3.3.0-SNAPSHOT.jar /spring-petclinic-3.3.0-SNAPSHOT.jar
CMD ["java", "-jar", "/spring-petclinic-3.3.0-SNAPSHOT.jar"]
- It is not a good idea to copy files in root directory
FROM eclipse-temurin:21-alpine
LABEL author=shaikkhajaibrahim
LABEL project=learning
LABEL version=3.3.0
EXPOSE 8080
ADD https://referenceappslt.s3.ap-south-1.amazonaws.com/spring-petclinic-3.3.0-SNAPSHOT.jar /app/spring-petclinic-3.3.0-SNAPSHOT.jar
WORKDIR /app
CMD ["java", "-jar", "spring-petclinic-3.3.0-SNAPSHOT.jar"]
-
Its a security risk to run as root user inside a docker image. This means we need to create a user in a image and run our application as that user
-
Exercise:
- how to create a linux user
- with a home directory
/app
- with no prompts and passwords set
- Dockerfile
FROM eclipse-temurin:21-alpine
LABEL author=shaikkhajaibrahim
LABEL project=learning
LABEL version=3.3.0
RUN adduser -D -h /app -s /bin/sh spc
USER spc
EXPOSE 8080
ADD --chown=spc:spc https://referenceappslt.s3.ap-south-1.amazonaws.com/spring-petclinic-3.3.0-SNAPSHOT.jar /app/spring-petclinic-3.3.0-SNAPSHOT.jar
WORKDIR /app
CMD ["java", "-jar", "spring-petclinic-3.3.0-SNAPSHOT.jar"]
- Exercise:
- Try redoing all of this amazon correto 21 as base image.
- Find the slimmest jre iamge to run spc.
Like this:
Like Loading...