Containerizing Java application
Building image from code
- We are supposed to write a dockerfile which builds a package and then creates a image
- Challenge: the tools that are used to build a package are generally not required for running application.
- Solution: Docker introduced Multi stage Docker builds
Multi stage
FROM ....
EXPOSE
RUN
...
CMD
- Multi staged Docker file: Only last stage is your image
FROM ... AS builder
...
...
...
FROM ... As application
...
...
...
...
Spring petclinic
- To build spring pet clinic, we need
- Command to build spring petclinic is
mvn package
- Its a good idea to create .dockerignore
- Dockerfile
FROM maven:3-eclipse-temurin-21-alpine AS builder
COPY . /spc
WORKDIR /spc
RUN mvn package
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
COPY --from=builder --chown=spc:spc /spc/target/spring-petclinic-4.0.0-SNAPSHOT.jar /app/spring-petclinic-4.0.0-SNAPSHOT.jar
WORKDIR /app
CMD ["java", "-jar", "spring-petclinic-4.0.0-SNAPSHOT.jar"]
Docker container running modes
- The default mode of running containers is attached
docker run --name spc_attached -P spc:1.0. IN this mode the container runs in foreground. when you want to quit the terminal for doing something application stops as ctrl+c will kill the PID 1
- The detached mode is where we run the container in background
docker run --name spc_detached -d -P spc:1.0. In this mode it prints container id and container will be running in the backgroun. to experiment with container we can use docker logs or docker exec
- Interactive mode: In this mode while we create a container we give a shell or some tty
- A better alternative start a container in a detached mode and the execute interactive exec
Docker image layers
- Docker image is collection of Readonly layers
- Layers are created on the basic of Base Image and then any change in content (RUN/ADD/COPY) will lead to a creation of new layer
- Refer Here this article and also Refer Here
- Docker image layers are readonly.
Like this:
Like Loading...