In this tutorial, you are going to learn what is Docker and how we can use it to Dockerize a Spring application.
Dockerfile
Dockerfile is just a .txt file. Dockerfile allows you to run commands that help you build an image. These commands can be useful if you want to specify the layers of the image. One thing to note is that we can also run these commands from the command line by passing them instead of including them in the file.
There are a couple of keywords that you have to know when you work with dockerfiles:
- FROM: this keyword tells Docker to use a given base image. If the image is not local however, Docker will perform an online search on DockerHub.
- MAINTAINER: identifies the author of the image.
- RUN: executes shell command line within the target system.
- COPY: copies files from local file sytem into the image.
- WORKDIR: sets the current working directory.
Let’s look at a simple example:
FROM alpine:3.2 MAINTAINER javatutorial.net ADD target/demo-0.0.1-SNAPSHOT.jar app.jar RUN sh -c 'touch /app.jar'
You should save the docker file in the root folder.
Now, we need a .jar file which will be used to create the Docker image. To create the .jar file run:
mvn clean install
if you are using Maven.
After you have saved the docker file, it’s time to build our Docker image.
Navigate to your Spring app root folder and type the following:
docker build -t springboot-app:latest
If however, you are executing the build command from another folder, the structure of the build command should be like this:
docker built -t springboot-app:latest -f path-to-the-dockerfile
Done! We built our Docker image. Now, to start the container, type the following:
docker run -p 8080:8080 app
The above command breakdown:
- The container is an isolated environment so that means we need to map the port of the host operation system which we set to 8080 (the first one) and the port inside the container itself (8080 the second one).
- -p 8080:8080
And to access it, type the following:
docker exec -ti app bash
To access the logs:
docker logs app