Summary
Dockerfile
FROM java:8-jre-alpine
COPY target/demo-0.0.1-SNAPSHOT.jar /usr/app/
WORKDIR /usr/app
ENTRYPOINT ["java","-jar","demo-0.0.1-SNAPSHOT.jar"]
Build Image
docker build -t demo-spring-boot-app:0.0.1 .
Run Image
docker run --rm -p 80:8080 --name demo-spring-boot-application demo-spring-boot-app:0.0.1
COPY target/demo-0.0.1-SNAPSHOT.jar /usr/app/
WORKDIR /usr/app
ENTRYPOINT ["java","-jar","demo-0.0.1-SNAPSHOT.jar"]
Build Image
docker build -t demo-spring-boot-app:0.0.1 .
Run Image
docker run --rm -p 80:8080 --name demo-spring-boot-application demo-spring-boot-app:0.0.1
My example is a Spring Boot application. This method is not restricted to spring boot application. Can be used to execute any JAR file.
Explaination of above
Dockerfile
To run any application on Docker, we need Dockerfile.
Create a file at root of your project. Name it 'Dockerfile'. And below are contents - edit as per requirement.
Create a file at root of your project. Name it 'Dockerfile'. And below are contents - edit as per requirement.
FROM java:8-jdk-alpine
COPY target/demo-0.0.1-SNAPSHOT.jar /usr/app/
WORKDIR /usr/app
ENTRYPOINT ["java","-jar","demo-0.0.1-SNAPSHOT.jar"]
I am using maven as a build tool. It generates output JAR file in /target folder. Hence I copy output JAR from target/
ENTRYPOINT is the command that is fired to run application. We are using "java - jar demo-0.0.1-SNAPSHOT.jar" as our command.
ENTRYPOINT is the command that is fired to run application. We are using "java - jar demo-0.0.1-SNAPSHOT.jar" as our command.
Build
docker build -t demo-spring-boot-app:0.0.1 .
Last . refers to location where Dockerfile is kept - I kept it at my project root folder.
>> demo-spring-boot-app is name of my Docker image.
>> 0.0.1 is version I will be creating.
docker images
to see if above mentioned docker image was build successfully.
Run application
docker run --rm -p 80:8080 --name demo-spring-boot-application demo-spring-boot-app:0.0.1
>> --rm => deletes container after container is stopped.
>> -p 80:8080 => application is running at port 8080 inside docker container. It is exposed to system on port 80.
>> --name => gives a name to container that is created by running image. It is an alias handle for container.
I could now access my application as
where /greet/harsh serves a greeting in my application.
A followup article for Java 11 is available here.
Comments
Post a Comment